mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
Merge main into feat/stylus-wheel
This commit is contained in:
commit
e0ff711f8b
291 files changed
+17872
-1637
No files matched your search
Generated
+1
@@ -6477,6 +6477,7 @@ dependencies = [
|
||||
"vectorcraft-text",
|
||||
"vectorcraft-three-d",
|
||||
"vectorcraft-trace",
|
||||
"wat",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1382,6 +1382,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)
|
||||
@@ -1853,6 +1861,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)];
|
||||
|
||||
+204
-37
@@ -140,6 +140,21 @@ pub fn tiff_orientation(bytes: &[u8]) -> Option<u16> {
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::Orientation).ok().flatten()
|
||||
}
|
||||
|
||||
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
|
||||
/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with
|
||||
/// extra samples) has its Orientation tag read from its first image ([`tiff_orientation`]). Reads
|
||||
/// only the image's header and metadata; `None` for an [`oversized_tiff`], which no decoder opens.
|
||||
pub fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
use image::ImageDecoder as _;
|
||||
use image::metadata::Orientation;
|
||||
if oversized_tiff(bytes).is_some() {
|
||||
return None;
|
||||
}
|
||||
let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok();
|
||||
let tagged = || tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?));
|
||||
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
|
||||
}
|
||||
|
||||
/// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)?
|
||||
fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1)
|
||||
@@ -151,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 {
|
||||
@@ -180,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
|
||||
@@ -318,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
|
||||
|
||||
@@ -286,7 +286,9 @@ impl Document {
|
||||
self.next_id = self.next_id.max(id);
|
||||
}
|
||||
|
||||
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
|
||||
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data), then give
|
||||
/// the objects outside the layer tree (opacity-mask art, symbols, graph designs and patterns)
|
||||
/// whose id is missing or already taken a new one, so each stored object has an id of its own.
|
||||
pub fn fix_next_id(&mut self) {
|
||||
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
|
||||
// counter up there: new ids start under them and never reach them, where counting on from
|
||||
@@ -297,13 +299,12 @@ impl Document {
|
||||
max = max.max(id);
|
||||
}
|
||||
};
|
||||
for l in &self.layers {
|
||||
l.walk(&mut |n| see(n.id.0));
|
||||
}
|
||||
self.visit_stored(|n, _| see(n.id.0));
|
||||
self.slices.iter().for_each(|s| see(s.id.0));
|
||||
self.assets.iter().for_each(|a| see(a.id));
|
||||
let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0);
|
||||
self.next_id = counter.max(max.saturating_add(1));
|
||||
self.renumber_stored_duplicates();
|
||||
}
|
||||
|
||||
/// Find a node anywhere in the tree.
|
||||
|
||||
@@ -554,6 +554,13 @@ impl Document {
|
||||
t.cached_baselines.clear();
|
||||
t.cached_ink = None;
|
||||
}
|
||||
// Opacity-mask art is stored art too: the copy's gets ids of its own.
|
||||
if let Some(art) = n.extras().mask.as_ref().map(|m| Arc::clone(&m.art)) {
|
||||
let art = Arc::new(self.reid(&art));
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
m.art = art;
|
||||
}
|
||||
}
|
||||
let on_path = n.extras().objects_on_path.is_some();
|
||||
let mut renamed = std::collections::HashMap::new();
|
||||
if let Some(ch) = n.children_mut() {
|
||||
|
||||
@@ -142,6 +142,7 @@ mod graphic_style;
|
||||
mod guides;
|
||||
mod limits;
|
||||
mod records;
|
||||
mod stored_art;
|
||||
mod units;
|
||||
|
||||
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
|
||||
@@ -154,6 +155,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
|
||||
use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use stored_art::{StoredPlace, StoredRoot};
|
||||
pub use units::{ColorMode, Unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -144,6 +144,25 @@ impl Selection {
|
||||
self.key = None;
|
||||
}
|
||||
}
|
||||
/// [`Self::remove`] for each of `ids`, going through the selected objects once.
|
||||
pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
let ids: HashSet<NodeId> = ids.into_iter().collect();
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
self.objects.retain(|x| !ids.contains(x));
|
||||
for id in &ids {
|
||||
self.anchors.remove(id);
|
||||
self.segments.remove(id);
|
||||
}
|
||||
if self.key.is_some_and(|k| ids.contains(&k)) {
|
||||
self.key = None;
|
||||
}
|
||||
}
|
||||
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
|
||||
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
|
||||
@@ -16,6 +16,35 @@ fn basic_ops() {
|
||||
assert!(s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_all_does_what_removing_each_does() {
|
||||
let mut s = Selection::default();
|
||||
for i in 1..=6 {
|
||||
s.add(NodeId(i));
|
||||
}
|
||||
for i in [2, 4, 5] {
|
||||
s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)]));
|
||||
s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)]));
|
||||
}
|
||||
s.key = Some(NodeId(4));
|
||||
s.target = Some(NodeId(3));
|
||||
s.slices = vec![NodeId(9)];
|
||||
s.guides = vec![NodeId(10)];
|
||||
s.on_path_member = Some(NodeId(11));
|
||||
let mut one_by_one = s.clone();
|
||||
for id in [NodeId(4), NodeId(1), NodeId(4), NodeId(7)] {
|
||||
one_by_one.remove(id);
|
||||
}
|
||||
let mut all = s.clone();
|
||||
all.remove_all([NodeId(4), NodeId(1), NodeId(4), NodeId(7)]);
|
||||
assert_eq!(all, one_by_one);
|
||||
assert_eq!(all.objects, [NodeId(2), NodeId(3), NodeId(5), NodeId(6)]);
|
||||
// Removing nothing leaves the selection as it was.
|
||||
let mut none = s.clone();
|
||||
none.remove_all([]);
|
||||
assert_eq!(none, s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_are_selected_on_their_own() {
|
||||
let mut s = Selection::default();
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Every object a document stores, wherever it is kept: in the layers, in opacity-mask art, and in
|
||||
//! the art of symbols, graph designs and pattern swatches. [`Document::node`] finds objects in the
|
||||
//! layer tree only; the lookups here find the others by their ids too, which
|
||||
//! [`Document::fix_next_id`] keeps unique across all of them.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::limits::MAX_NEXT_ID;
|
||||
use super::{Document, Node, NodeId};
|
||||
|
||||
/// The art a stored object belongs to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StoredRoot {
|
||||
/// Layer `index` of [`Document::layers`].
|
||||
Layer(usize),
|
||||
/// Symbol `index` of [`Document::symbols`].
|
||||
Symbol(usize),
|
||||
/// Graph design `index` of [`Document::graph_designs`].
|
||||
GraphDesign(usize),
|
||||
/// Object `art` of pattern swatch `pattern` of [`Document::patterns`].
|
||||
Pattern { pattern: usize, art: usize },
|
||||
}
|
||||
|
||||
/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs
|
||||
/// to (the innermost one when masks hold masks).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct StoredPlace {
|
||||
pub root: StoredRoot,
|
||||
pub mask_of: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl StoredPlace {
|
||||
/// Is the object in the layer tree itself, where [`Document::node`] finds it and the canvas
|
||||
/// draws it as itself?
|
||||
pub fn in_layers(self) -> bool {
|
||||
matches!(self.root, StoredRoot::Layer(_)) && self.mask_of.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// One step down from a node: to its child at an index, or to its opacity-mask art.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Step {
|
||||
Child(usize),
|
||||
Mask,
|
||||
}
|
||||
|
||||
/// `n` and everything below it with its place, the opacity-mask art right after the object it
|
||||
/// masks, then the children.
|
||||
fn visit<'a>(n: &'a Arc<Node>, place: StoredPlace, f: &mut dyn FnMut(&'a Arc<Node>, StoredPlace)) {
|
||||
f(n, place);
|
||||
if let Some(m) = &n.extras().mask {
|
||||
visit(&m.art, StoredPlace { mask_of: Some(n.id), ..place }, f);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, place, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps from `n` to the first node in [`visit`] order with id `id`, and the object whose mask
|
||||
/// holds it last on the way.
|
||||
fn find(n: &Node, id: NodeId, steps: &mut Vec<Step>, mask_of: &mut Option<NodeId>) -> bool {
|
||||
if n.id == id {
|
||||
return true;
|
||||
}
|
||||
if let Some(m) = &n.extras().mask {
|
||||
steps.push(Step::Mask);
|
||||
let before = *mask_of;
|
||||
*mask_of = Some(n.id);
|
||||
if find(&m.art, id, steps, mask_of) {
|
||||
return true;
|
||||
}
|
||||
*mask_of = before;
|
||||
steps.pop();
|
||||
}
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
steps.push(Step::Child(i));
|
||||
if find(c, id, steps, mask_of) {
|
||||
return true;
|
||||
}
|
||||
steps.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The node `steps` below `n`.
|
||||
fn at<'a>(mut n: &'a Arc<Node>, steps: &[Step]) -> Option<&'a Arc<Node>> {
|
||||
for s in steps {
|
||||
n = match s {
|
||||
Step::Mask => &n.extras().mask.as_ref()?.art,
|
||||
Step::Child(i) => n.children()?.get(*i)?,
|
||||
};
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// The node `steps` below `n` to change, the nodes on the way copied when shared.
|
||||
fn at_mut<'a>(mut n: &'a mut Arc<Node>, steps: &[Step]) -> Option<&'a mut Node> {
|
||||
for s in steps {
|
||||
let node = Arc::make_mut(n);
|
||||
n = match s {
|
||||
Step::Mask => &mut node.extras_if_any()?.mask.as_mut()?.art,
|
||||
Step::Child(i) => node.children_mut()?.get_mut(*i)?,
|
||||
};
|
||||
}
|
||||
Some(Arc::make_mut(n))
|
||||
}
|
||||
|
||||
/// Gives every node from `n` down that `fresh` names a new id from `next`, counting nodes in
|
||||
/// [`visit`] order from `*count`; only the nodes on the way to one are copied. Each part below is
|
||||
/// renumbered through a second handle, so a new pointer marks a change.
|
||||
fn renumber(n: &mut Arc<Node>, fresh: &HashSet<usize>, count: &mut usize, next: &mut u64) {
|
||||
let own = fresh.contains(count);
|
||||
*count += 1;
|
||||
let mask = n.extras().mask.as_ref().and_then(|m| {
|
||||
let mut art = Arc::clone(&m.art);
|
||||
renumber(&mut art, fresh, count, next);
|
||||
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
|
||||
});
|
||||
let mut slots = vec![];
|
||||
// Children's new ids by their old ones, for an Objects on Path group, which names its path and
|
||||
// members by id. An id another child keeps still names that child.
|
||||
let mut renamed = std::collections::HashMap::new();
|
||||
let mut kept = HashSet::new();
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
let mut new = Arc::clone(c);
|
||||
renumber(&mut new, fresh, count, next);
|
||||
if new.id == c.id {
|
||||
kept.insert(c.id);
|
||||
} else {
|
||||
renamed.insert(c.id, new.id);
|
||||
}
|
||||
if !Arc::ptr_eq(&new, c) {
|
||||
slots.push((i, new));
|
||||
}
|
||||
}
|
||||
renamed.retain(|old, _| !kept.contains(old));
|
||||
if !own && mask.is_none() && slots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let node = Arc::make_mut(n);
|
||||
if own {
|
||||
node.id = NodeId(*next);
|
||||
*next += 1;
|
||||
}
|
||||
if let (Some(art), Some(m)) = (mask, node.extras_if_any().and_then(|e| e.mask.as_mut())) {
|
||||
m.art = art;
|
||||
}
|
||||
if let Some(children) = node.children_mut() {
|
||||
for (i, c) in slots {
|
||||
if let Some(slot) = children.get_mut(i) {
|
||||
*slot = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !renamed.is_empty()
|
||||
&& let Some(on_path) = node.extras_if_any().and_then(|e| e.objects_on_path.as_mut())
|
||||
{
|
||||
on_path.rename(&renamed);
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// The roots of the art kept outside the layers, each with its [`StoredRoot`].
|
||||
fn definition_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
|
||||
let symbols = self.symbols.iter().enumerate().map(|(i, s)| (&s.art, StoredRoot::Symbol(i)));
|
||||
let designs = self.graph_designs.iter().enumerate().map(|(i, g)| (&g.art, StoredRoot::GraphDesign(i)));
|
||||
let patterns = self
|
||||
.patterns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a })));
|
||||
symbols.chain(designs).chain(patterns)
|
||||
}
|
||||
|
||||
/// Every root of stored art: the layers, then the art of symbols, graph designs and patterns.
|
||||
fn stored_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
|
||||
self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots())
|
||||
}
|
||||
|
||||
/// The root `root` names, to change.
|
||||
fn stored_root_mut(&mut self, root: StoredRoot) -> Option<&mut Arc<Node>> {
|
||||
match root {
|
||||
StoredRoot::Layer(i) => self.layers.get_mut(i),
|
||||
StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art),
|
||||
StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art),
|
||||
StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visit every stored object with its place: the layer tree with the opacity-mask art of its
|
||||
/// objects, then the art of symbols, graph designs and pattern swatches (their definitions,
|
||||
/// once each, never the copies instances and tiles draw).
|
||||
pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) {
|
||||
self.visit_stored_arcs(|n, place| f(n, place));
|
||||
}
|
||||
|
||||
/// [`Self::visit_stored`] with each object's shared handle, which keeps its identity from one
|
||||
/// look to the next while the object is unchanged (for caches such as thumbnails).
|
||||
pub fn visit_stored_arcs<'a>(&'a self, mut f: impl FnMut(&'a Arc<Node>, StoredPlace)) {
|
||||
for (root, r) in self.stored_roots() {
|
||||
visit(root, StoredPlace { root: r, mask_of: None }, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where object `id` is stored: the root, and the steps from it.
|
||||
fn stored_path(&self, id: NodeId) -> Option<(StoredPlace, Vec<Step>)> {
|
||||
if let Some(path) = self.index_path(id) {
|
||||
let (first, rest) = path.split_first()?;
|
||||
return Some((StoredPlace { root: StoredRoot::Layer(*first), mask_of: None }, rest.iter().map(|i| Step::Child(*i)).collect()));
|
||||
}
|
||||
// Not in the layer tree: in mask art (in the layers too) or in a definition's art.
|
||||
for (root, r) in self.stored_roots() {
|
||||
let (mut steps, mut mask_of) = (vec![], None);
|
||||
if find(root, id, &mut steps, &mut mask_of) {
|
||||
return Some((StoredPlace { root: r, mask_of }, steps));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Stored object `id` (see [`Self::visit_stored`]) with its place: one in the layer tree as
|
||||
/// [`Self::node`] finds it, else the first in visiting order.
|
||||
pub fn stored_node(&self, id: NodeId) -> Option<(&Arc<Node>, StoredPlace)> {
|
||||
let (place, steps) = self.stored_path(id)?;
|
||||
let root = self.stored_roots().find(|(_, r)| *r == place.root)?.0;
|
||||
Some((at(root, &steps)?, place))
|
||||
}
|
||||
|
||||
/// [`Self::stored_node`] to change; the nodes on the way are copied when shared.
|
||||
pub fn stored_node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
|
||||
let (place, steps) = self.stored_path(id)?;
|
||||
at_mut(self.stored_root_mut(place.root)?, &steps)
|
||||
}
|
||||
|
||||
/// Gives the objects outside the layer tree (in opacity-mask art and in the art of symbols,
|
||||
/// graph designs and patterns) whose id is 0, past the id range, or already taken by an object
|
||||
/// visited before them (the layer tree's own objects first) a new id, so every stored object
|
||||
/// can be named by its id. Returns how many changed; the id counter then stands above them.
|
||||
pub(crate) fn renumber_stored_duplicates(&mut self) -> usize {
|
||||
let mut seen: HashSet<NodeId> = HashSet::new();
|
||||
for l in &self.layers {
|
||||
l.walk(&mut |n| {
|
||||
seen.insert(n.id);
|
||||
});
|
||||
}
|
||||
self.slices.iter().for_each(|s| {
|
||||
seen.insert(s.id);
|
||||
});
|
||||
// Per root, the visiting indices of the nodes that take a new id.
|
||||
let mut fresh: Vec<(StoredRoot, HashSet<usize>)> = vec![];
|
||||
for (root, r) in self.stored_roots() {
|
||||
let (mut i, mut here) = (0, HashSet::new());
|
||||
visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| {
|
||||
if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) {
|
||||
here.insert(i);
|
||||
}
|
||||
i += 1;
|
||||
});
|
||||
if !here.is_empty() {
|
||||
fresh.push((r, here));
|
||||
}
|
||||
}
|
||||
let total = fresh.iter().map(|(_, f)| f.len()).sum();
|
||||
if total == 0 {
|
||||
return 0;
|
||||
}
|
||||
// No id left to give: the objects keep theirs rather than share one given out later.
|
||||
if self.peek_next_id().saturating_add(total as u64) > MAX_NEXT_ID {
|
||||
return 0;
|
||||
}
|
||||
let mut next = self.peek_next_id();
|
||||
for (r, f) in fresh {
|
||||
if let Some(root) = self.stored_root_mut(r) {
|
||||
renumber(root, &f, &mut 0, &mut next);
|
||||
}
|
||||
}
|
||||
self.raise_next_id(next);
|
||||
total
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{GraphDesign, OpacityMask, PatternDef, Symbol};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
fn rect(id: u64) -> Node {
|
||||
Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), crate::Appearance::default_art())
|
||||
}
|
||||
|
||||
fn masked(id: u64, art: Node) -> Node {
|
||||
rect(id).with_mask(Some(Box::new(OpacityMask::new(art, true))))
|
||||
}
|
||||
|
||||
/// A document with object 10 in its layer, mask art 11 on it, and one object in a symbol,
|
||||
/// a graph design and a pattern (ids `defs`).
|
||||
fn doc(defs: [u64; 3]) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, masked(10, rect(11))).unwrap();
|
||||
d.symbols.push(Symbol { name: "S".into(), art: Arc::new(rect(defs[0])), dynamic: false });
|
||||
d.graph_designs.push(GraphDesign { name: "G".into(), art: Arc::new(rect(defs[1])) });
|
||||
d.patterns.push(PatternDef::new("P", vec![Arc::new(rect(defs[2]))]));
|
||||
d.raise_next_id(20);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_objects_are_found_in_every_art() {
|
||||
let d = doc([12, 13, 14]);
|
||||
let place = |id: u64| d.stored_node(NodeId(id)).map(|(n, p)| (n.id.0, p));
|
||||
assert!(place(10).unwrap().1.in_layers());
|
||||
assert_eq!(place(11).unwrap().1, StoredPlace { root: StoredRoot::Layer(0), mask_of: Some(NodeId(10)) });
|
||||
assert_eq!(place(12).unwrap().1.root, StoredRoot::Symbol(0));
|
||||
assert_eq!(place(13).unwrap().1.root, StoredRoot::GraphDesign(0));
|
||||
assert_eq!(place(14).unwrap().1.root, StoredRoot::Pattern { pattern: 0, art: 0 });
|
||||
assert!(d.node(NodeId(11)).is_none() && d.node(NodeId(12)).is_none(), "the layer lookup stays the layer tree's");
|
||||
assert!(d.stored_node(NodeId(99)).is_none());
|
||||
let mut seen = vec![];
|
||||
d.visit_stored(|n, _| seen.push(n.id.0));
|
||||
assert_eq!(seen, [d.layers[0].id.0, 10, 11, 12, 13, 14]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_objects_change_by_id() {
|
||||
let mut d = doc([12, 13, 14]);
|
||||
let before = d.clone();
|
||||
d.stored_node_mut(NodeId(13)).unwrap().name = Some("changed".into());
|
||||
assert_eq!(d.graph_designs[0].art.name.as_deref(), Some("changed"));
|
||||
assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art), "other art is not copied");
|
||||
assert_eq!(before.graph_designs[0].art.name, None, "the earlier document is unchanged");
|
||||
d.stored_node_mut(NodeId(11)).unwrap().name = Some("mask".into());
|
||||
assert_eq!(d.stored_node(NodeId(11)).unwrap().0.name.as_deref(), Some("mask"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fix_next_id_gives_nested_duplicates_new_ids() {
|
||||
// The symbol's object repeats the layer's object, the design's has no id, and the pattern's
|
||||
// repeats the mask art's.
|
||||
let mut d = doc([10, 0, 11]);
|
||||
d.next_id = 1;
|
||||
d.fix_next_id();
|
||||
let mut ids = vec![];
|
||||
d.visit_stored(|n, _| ids.push(n.id.0));
|
||||
let unique: HashSet<u64> = ids.iter().copied().collect();
|
||||
assert_eq!(unique.len(), ids.len(), "{ids:?}");
|
||||
assert!(!ids.contains(&0));
|
||||
assert_eq!(&ids[..3], &[d.layers[0].id.0, 10, 11], "the layer tree and the first mask art keep theirs");
|
||||
assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id());
|
||||
// Ids already unique are kept, and a second pass changes nothing.
|
||||
let again = d.clone();
|
||||
assert_eq!(d.renumber_stored_duplicates(), 0);
|
||||
assert_eq!(d, again);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renumbered_objects_on_path_keep_their_path_and_members() {
|
||||
// A symbol's Objects on Path group whose path repeats the layer's object 10 and whose
|
||||
// member has no id.
|
||||
let mut d = doc([12, 13, 14]);
|
||||
let (path, member) = (rect(10), rect(0));
|
||||
let rec = crate::objects_on_path::ObjectsOnPath::new(path.id, &[&member], crate::objects_on_path::CENTER, 0.0);
|
||||
let mut g = Node::new(NodeId(15), crate::NodeKind::Group { children: vec![Arc::new(path), Arc::new(member)], clip: false });
|
||||
g.extras_mut().objects_on_path = Some(Box::new(rec));
|
||||
d.symbols[0].art = Arc::new(g);
|
||||
d.fix_next_id();
|
||||
let art = &d.symbols[0].art;
|
||||
let kids: Vec<NodeId> = art.children().unwrap().iter().map(|c| c.id).collect();
|
||||
assert!(kids.iter().all(|id| id.0 != 10 && id.0 != 0), "{kids:?}");
|
||||
let on_path = art.extras().objects_on_path.as_ref().unwrap();
|
||||
assert_eq!(on_path.path, kids[0]);
|
||||
assert_eq!(on_path.members.iter().map(|m| m.id).collect::<Vec<_>>(), [kids[1]]);
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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, ¶ms, seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(bounds, ¶ms, 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, ¶ms), 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, ¶ms, at.seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(at.bounds, ¶ms, 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.
|
||||
|
||||
+159
-29
@@ -27,7 +27,16 @@ pub fn is_revolve(id: &str) -> bool {
|
||||
/// Most bytes the copies of the object's paint in the faces may take together. Each face and the
|
||||
/// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of
|
||||
/// thousands of faces took gigabytes; past this the source path is drawn.
|
||||
const MAX_PAINT_COPIES: usize = 256 << 20;
|
||||
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.
|
||||
@@ -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, ¶ms, &mut graphic_copies);
|
||||
if i == target {
|
||||
graphics?;
|
||||
}
|
||||
check_shadow(¶ms, [&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, ¶ms).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:?}");
|
||||
}
|
||||
+608
-61
@@ -5,8 +5,9 @@ use std::sync::Arc;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View};
|
||||
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
use vectorcraft_pathops::BoolOp;
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View};
|
||||
|
||||
#[cfg(test)]
|
||||
use vectorcraft_doc::color::Color;
|
||||
@@ -20,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;
|
||||
@@ -79,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()));
|
||||
@@ -504,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))),
|
||||
}
|
||||
@@ -678,7 +681,8 @@ fn built_solids<'a>(
|
||||
/// What a face of one of the solids [`art_for`] draws in one order was built from: the facet's
|
||||
/// depth, whether it is a side face and whether it is turned away from the viewer, the bounds of
|
||||
/// its polygon, the index of its shape, and whether its solid is that shape's fill or one of its
|
||||
/// strokes that covers the fill's whole edge.
|
||||
/// strokes that covers the fill's whole edge. A face that [`convex_face`] takes also keeps its
|
||||
/// polygon and plane, for [`local_order`]; every other face has an empty `outline` and no `plane`.
|
||||
struct Placed {
|
||||
depth: f64,
|
||||
side: bool,
|
||||
@@ -686,6 +690,8 @@ struct Placed {
|
||||
bounds: Rect,
|
||||
member: usize,
|
||||
paints: Paints,
|
||||
outline: Vec<Point>,
|
||||
plane: Option<DepthPlane>,
|
||||
}
|
||||
|
||||
/// The part of its shape a face's solid is built from ([`Placed`]).
|
||||
@@ -694,13 +700,22 @@ enum Paints {
|
||||
Fill,
|
||||
/// A stroke whose solid holds the fill's whole edge and hides it: one with a width, without
|
||||
/// dashes, a width profile or a brush, painted with a solid color or a gradient without
|
||||
/// transparent stops, on a shape whose subpaths are all closed.
|
||||
/// transparent stops, on a shape whose subpaths are all closed, extruded (an inflated fill can
|
||||
/// rise in front of its stroke).
|
||||
Stroke,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// Can a stroke's solid on a shape with outline `path` hold the fill's edge ([`Paints::Stroke`])
|
||||
/// under the effect `effect`? Only when the subpaths are all closed and the effect extrudes: an
|
||||
/// inflated fill can rise in front of its stroke.
|
||||
fn holds_edge(effect: &str, path: &PathData) -> bool {
|
||||
effect != INFLATE && path.subpaths.iter().all(|p| p.closed)
|
||||
}
|
||||
|
||||
impl Paints {
|
||||
/// What `item` of a shape is, the shape's subpaths all closed when `closed`.
|
||||
/// What `item` of a shape is, its stroke's solid able to hold the fill's edge when `closed`
|
||||
/// ([`holds_edge`]).
|
||||
fn of(item: &AppearanceItem, closed: bool) -> Self {
|
||||
match item {
|
||||
AppearanceItem::Fill(_) => Paints::Fill,
|
||||
@@ -729,10 +744,446 @@ impl Placed {
|
||||
fn of(f: &Facet, member: usize, paints: Paints) -> Self {
|
||||
let mut points = f.contours.iter().flatten();
|
||||
let bounds = points.next().map_or(Rect::ZERO, |p| points.fold(Rect::from_points(*p, *p), |r, q| r.union_pt(*q)));
|
||||
Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints }
|
||||
let local = convex_face(f).is_some();
|
||||
let outline = f.contours.first().filter(|_| local).cloned().unwrap_or_default();
|
||||
let plane = f.plane.filter(|_| local);
|
||||
Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints, outline, plane }
|
||||
}
|
||||
}
|
||||
|
||||
/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares;
|
||||
/// the pairs they have not reached by then keep the order of their depths.
|
||||
const MAX_LOCAL_CHECKS: usize = 4_000_000;
|
||||
|
||||
/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other
|
||||
/// than a planar end, with a plane and one convex contour: a face [`local_order`] and
|
||||
/// [`cut_stroke_faces`] work on.
|
||||
fn convex_face(f: &Facet) -> Option<(&[Point], f64)> {
|
||||
if f.away || f.end.is_some() || f.plane.is_none() || f.contours.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let c = f.contours.first()?;
|
||||
Some((c, convex(c)?))
|
||||
}
|
||||
|
||||
/// The bounds of polygon `p` (`Rect::ZERO` when it has no points).
|
||||
fn polygon_bounds(p: &[Point]) -> Rect {
|
||||
let mut points = p.iter();
|
||||
points.next().map_or(Rect::ZERO, |q| points.fold(Rect::from_points(*q, *q), |r, q| r.union_pt(*q)))
|
||||
}
|
||||
|
||||
/// Do rectangles `a` and `b` overlap (more than along an edge)?
|
||||
fn rects_overlap(a: Rect, b: Rect) -> bool {
|
||||
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
|
||||
}
|
||||
|
||||
/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces
|
||||
/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within
|
||||
/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies
|
||||
/// of the costliest stroke's paint.
|
||||
fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, paint_bytes: usize) -> usize {
|
||||
let per_face = items
|
||||
.filter(|item| matches!(item, AppearanceItem::Stroke(_)))
|
||||
.map(|item| {
|
||||
let mut copies = 0usize;
|
||||
crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item));
|
||||
copies
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.max(1);
|
||||
let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face;
|
||||
MAX_OBJECT_FACES.saturating_sub(faces).min(affordable)
|
||||
}
|
||||
|
||||
/// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a
|
||||
/// stroke that does not cover the fill's edge ([`Paints::Other`]) that passes through the plane of a
|
||||
/// face of the same shape's fill, or of a face of another of the shape's strokes, where the two
|
||||
/// overlap on the drawing ([`cut_through`]). Of two such strokes, the later one's faces are cut
|
||||
/// against the earlier one's; a covering stroke's faces ([`Paints::Stroke`]) are never cut, and an
|
||||
/// other stroke's faces are cut against them. At most `room` pieces are added, the object's solids
|
||||
/// together.
|
||||
fn cut_stroke_faces(solids: &mut [(Paints, usize, &mut Vec<Facet>)], mut room: usize) {
|
||||
let mut checks = 0usize;
|
||||
for k in 0..solids.len() {
|
||||
let Some((Paints::Other, shape)) = solids.get(k).map(|(p, s, _)| (*p, *s)) else { continue };
|
||||
let walls: Vec<usize> = (0..solids.len())
|
||||
.filter(|&j| {
|
||||
solids.get(j).is_some_and(|(p, s, _)| {
|
||||
*s == shape
|
||||
&& match p {
|
||||
Paints::Fill | Paints::Stroke => true,
|
||||
Paints::Other => j < k,
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for j in walls {
|
||||
let (wall, stroke) = if j < k {
|
||||
let (before, from) = solids.split_at_mut(k);
|
||||
(&**before[j].2, &mut *from[0].2)
|
||||
} else {
|
||||
let (before, from) = solids.split_at_mut(j);
|
||||
(&**from[0].2, &mut *before[k].2)
|
||||
};
|
||||
cut_through(wall, stroke, &mut room, &mut checks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cut each face of `stroke` that passes through the plane of a face of `solid` (the fill's or
|
||||
/// another stroke's) where their polygons overlap on the drawing, along the line where their depths
|
||||
/// meet, so that each piece is wholly in front of or behind that face there ([`local_order`] can
|
||||
/// then order them). A dash's end, which crosses the edge of the fill it is drawn on, is cut into its
|
||||
/// part outside the fill, in front of the fill's wall, and its part inside, behind it. A piece keeps
|
||||
/// the part of the face's curved outline on its side of the cut. The first piece of a face takes its
|
||||
/// place, the others go at the end. Each cut adds a face out of `room`, and each pair compared counts
|
||||
/// in `checks` ([`MAX_LOCAL_CHECKS`]); cutting stops when either runs out.
|
||||
fn cut_through(solid: &[Facet], stroke: &mut Vec<Facet>, room: &mut usize, checks: &mut usize) {
|
||||
// The faces from left to right: a face is compared with those that start left of its end.
|
||||
let mut walls: Vec<(&Facet, &[Point], f64, Rect)> =
|
||||
solid.iter().filter_map(|f| convex_face(f).map(|(c, turn)| (f, c, turn, polygon_bounds(c)))).collect();
|
||||
if walls.is_empty() {
|
||||
return;
|
||||
}
|
||||
walls.sort_by(|a, b| a.3.x0.total_cmp(&b.3.x0));
|
||||
let mut k = 0;
|
||||
while k < stroke.len() {
|
||||
let mut extent = stroke.get(k).and_then(convex_face).map(|(c, _)| polygon_bounds(c));
|
||||
for &(wall, outline, turn, bounds) in &walls {
|
||||
let Some(at) = extent.filter(|e| bounds.x0 < e.x1) else { break };
|
||||
if *checks >= MAX_LOCAL_CHECKS || *room == 0 {
|
||||
return;
|
||||
}
|
||||
*checks += 1;
|
||||
if !rects_overlap(at, bounds) {
|
||||
continue;
|
||||
}
|
||||
let Some(s) = stroke.get(k) else { break };
|
||||
let Some((c, _)) = convex_face(s) else { break };
|
||||
if let Some((near, far)) = cut(s, c, wall, outline, turn) {
|
||||
*room -= 1;
|
||||
extent = convex_face(&near).map(|(c, _)| polygon_bounds(c));
|
||||
stroke[k] = near;
|
||||
stroke.push(far);
|
||||
}
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Face `s` (polygon `c`) cut where its depth meets that of face `wall` (convex polygon `outline`,
|
||||
/// turning with sign `turn`): its piece nearer the viewer than the wall's plane and its piece
|
||||
/// farther. `None` when the two do not overlap on the drawing or `s` is on one side of the wall's
|
||||
/// plane wherever they do.
|
||||
fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Option<(Facet, Facet)> {
|
||||
let ahead = |p: Point| Some(s.depth_at(p)? - wall.depth_at(p)?);
|
||||
let overlap = clip_convex(c, outline, turn);
|
||||
centroid(&overlap)?;
|
||||
let tolerance = 1e-6;
|
||||
let (mut nearer, mut farther) = (false, false);
|
||||
for p in &overlap {
|
||||
let d = ahead(*p)?;
|
||||
nearer |= d > tolerance;
|
||||
farther |= d < -tolerance;
|
||||
}
|
||||
if !(nearer && farther) {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = (s.plane?, wall.plane?);
|
||||
let values: Vec<f64> = match (a.eye, b.eye) {
|
||||
(Some(e), Some(f)) if e == f && a.center == b.center => {
|
||||
// With perspective the depths themselves are not linear on the drawing, but where they
|
||||
// meet is a line: (dA - aA e)(nzB - aB) = (dB - aB e)(nzA - aA), with aX = (nX · p) / e,
|
||||
// whose difference is linear. Its sign is that of the depths' difference over the
|
||||
// product of the two denominators, taken at the middle of the face.
|
||||
let at = |p: Point| {
|
||||
let (x, y) = (p.x - a.center.x, p.y - a.center.y);
|
||||
let (aa, ab) = ((a.normal[0] * x + a.normal[1] * y) / e, (b.normal[0] * x + b.normal[1] * y) / e);
|
||||
let (da, db) = (a.normal[2] - aa, b.normal[2] - ab);
|
||||
((a.offset - aa * e) * db - (b.offset - ab * e) * da, da * db)
|
||||
};
|
||||
let sign = at(centroid(c)?).1.signum();
|
||||
c.iter().map(|p| at(*p).0 * sign).collect()
|
||||
}
|
||||
_ => c.iter().map(|p| ahead(*p)).collect::<Option<_>>()?,
|
||||
};
|
||||
let piece = |sign: f64| {
|
||||
let points = half(c, &values, sign);
|
||||
let mid = centroid(&points)?;
|
||||
let mut f = s.clone();
|
||||
f.depth = s.depth_at(mid).unwrap_or(s.depth);
|
||||
f.contours = vec![points];
|
||||
f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign));
|
||||
Some(f)
|
||||
};
|
||||
Some((piece(1.0)?, piece(-1.0)?))
|
||||
}
|
||||
|
||||
/// Curved outline `outline` of a face with polygon `c`, cut along the line where `values` (one per
|
||||
/// point of `c`, varying linearly along each edge) is 0, keeping the side where `sign` times them is
|
||||
/// at least 0. `None` when the line does not cross `c` at two points or nothing is left.
|
||||
fn clip_to_side(outline: &PathData, c: &[Point], values: &[f64], sign: f64) -> Option<PathData> {
|
||||
let mut crossings = vec![];
|
||||
for (j, (&a, &va)) in c.iter().zip(values).enumerate() {
|
||||
let k = (j + 1) % c.len();
|
||||
let (Some(&b), Some(&vb)) = (c.get(k), values.get(k)) else { continue };
|
||||
if (va >= 0.0) != (vb >= 0.0) {
|
||||
crossings.push(a.lerp(b, va / (va - vb)));
|
||||
}
|
||||
}
|
||||
let &[q0, q1] = crossings.as_slice() else { return None };
|
||||
let along = q1 - q0;
|
||||
let length = along.hypot();
|
||||
if length.is_nan() || length <= 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let along = along / length;
|
||||
let (inside, _) = c.iter().zip(values).find(|(_, v)| **v * sign > 0.0)?;
|
||||
let mut across = Vec2::new(-along.y, along.x);
|
||||
if (*inside - q0).dot(across) < 0.0 {
|
||||
across = -across;
|
||||
}
|
||||
let bounds = outline.bounds()?.union(polygon_bounds(c));
|
||||
let reach = 2.0 * (bounds.width() + bounds.height() + (q0 - bounds.center()).hypot()) + 1.0;
|
||||
let mut side = BezPath::new();
|
||||
side.move_to(q0 - along * reach);
|
||||
side.line_to(q0 + along * reach);
|
||||
side.line_to(q0 + along * reach + across * reach);
|
||||
side.line_to(q0 - along * reach + across * reach);
|
||||
side.close_path();
|
||||
let kept = vectorcraft_pathops::boolean(outline, FillRule::NonZero, &PathData::from_bezpath(&side), FillRule::NonZero, BoolOp::Intersect);
|
||||
kept.bounds().is_some().then_some(kept)
|
||||
}
|
||||
|
||||
/// The part of polygon `p` where `sign` times `values` (one per point, varying linearly along each
|
||||
/// edge) is at least 0.
|
||||
fn half(p: &[Point], values: &[f64], sign: f64) -> Vec<Point> {
|
||||
let mut out = vec![];
|
||||
for (j, (&a, &va)) in p.iter().zip(values).enumerate() {
|
||||
let k = (j + 1) % p.len();
|
||||
let (Some(&b), Some(&vb)) = (p.get(k), values.get(k)) else { continue };
|
||||
let (sa, sb) = (va * sign, vb * sign);
|
||||
if sa >= 0.0 {
|
||||
out.push(a);
|
||||
}
|
||||
if (sa >= 0.0) != (sb >= 0.0) {
|
||||
out.push(a.lerp(b, sa / (sa - sb)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `order` (back to front), when it draws a face of one of a shape's strokes and an overlapping face
|
||||
/// of the same shape's fill or strokes the wrong way round for their depths where they overlap on
|
||||
/// the drawing, with every pair of overlapping faces that keep a polygon and a plane
|
||||
/// ([`convex_face`]: turned toward the viewer, not a planar end), of any shape, put in the order of
|
||||
/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill
|
||||
/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each
|
||||
/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays
|
||||
/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`.
|
||||
/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place:
|
||||
/// no face moves across it. Otherwise `order` as it is.
|
||||
fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
use std::cmp::Reverse;
|
||||
// The faces of each shape that take part, from left to right for a sweep along x.
|
||||
let mut shapes: Vec<Vec<usize>> = vec![];
|
||||
for (k, f) in faces.iter().enumerate() {
|
||||
if f.outline.len() < 3 || f.plane.is_none() {
|
||||
continue;
|
||||
}
|
||||
if shapes.len() <= f.member {
|
||||
shapes.resize_with(f.member + 1, Vec::new);
|
||||
}
|
||||
shapes[f.member].push(k);
|
||||
}
|
||||
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) {
|
||||
return order;
|
||||
}
|
||||
for list in &mut shapes {
|
||||
list.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
|
||||
}
|
||||
// A fill wall and a face of the same shape's covering stroke keep the order [`draw_order`] gave
|
||||
// them: the stroke's solid holds the wall, which never shows.
|
||||
let covered = |f: &Placed, s: &Placed| f.paints == Paints::Fill && f.side && s.paints == Paints::Stroke && f.member == s.member;
|
||||
// Is there a face of a shape's strokes and a face of the same shape's fill or strokes that the
|
||||
// order of their depths draws the wrong way round where they overlap?
|
||||
let mut position = vec![0usize; faces.len()];
|
||||
for (at, &k) in order.iter().enumerate() {
|
||||
position[k] = at;
|
||||
}
|
||||
let mut checks = 0usize;
|
||||
let mut misordered = false;
|
||||
'shapes: for list in &shapes {
|
||||
for (i, &f) in list.iter().enumerate() {
|
||||
let a = &faces[f];
|
||||
for &s in list.iter().skip(i + 1).take_while(|&&s| faces[s].bounds.x0 < a.bounds.x1) {
|
||||
if checks >= MAX_LOCAL_CHECKS {
|
||||
break 'shapes;
|
||||
}
|
||||
checks += 1;
|
||||
let b = &faces[s];
|
||||
if (a.paints == Paints::Fill && b.paints == Paints::Fill) || covered(a, b) || covered(b, a) || !rects_overlap(a.bounds, b.bounds) {
|
||||
continue;
|
||||
}
|
||||
if nearer_where_overlapping(a, b).is_some_and(|a_nearer| a_nearer != (position[f] > position[s])) {
|
||||
misordered = true;
|
||||
break 'shapes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !misordered {
|
||||
return order;
|
||||
}
|
||||
// Moving those faces must not carry them past any other face they overlap, so every pair of
|
||||
// faces with a polygon and a plane that overlap goes in the order of their depths there.
|
||||
let mut sweep: Vec<usize> = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect();
|
||||
sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
|
||||
// For each face, the faces drawn after it, and for each, how many go before it.
|
||||
let mut after: Vec<Vec<usize>> = vec![vec![]; faces.len()];
|
||||
let mut waits = vec![0usize; faces.len()];
|
||||
'pairs: for (i, &k) in sweep.iter().enumerate() {
|
||||
let a = &faces[k];
|
||||
for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) {
|
||||
if checks >= MAX_LOCAL_CHECKS {
|
||||
break 'pairs;
|
||||
}
|
||||
checks += 1;
|
||||
let b = &faces[j];
|
||||
if !rects_overlap(a.bounds, b.bounds) {
|
||||
continue;
|
||||
}
|
||||
let a_later = if covered(a, b) || covered(b, a) {
|
||||
position[k] > position[j]
|
||||
} else {
|
||||
let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue };
|
||||
a_nearer
|
||||
};
|
||||
let (back, front) = if a_later { (j, k) } else { (k, j) };
|
||||
after[back].push(front);
|
||||
waits[front] += 1;
|
||||
}
|
||||
}
|
||||
// Each step draws the face that comes first in `order` of those whose faces before are drawn.
|
||||
let mut ready: std::collections::BinaryHeap<Reverse<(usize, usize)>> =
|
||||
(0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
|
||||
// The faces drawn last, in `order`: each goes only after every face before it in `order`.
|
||||
let last: Vec<usize> = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect();
|
||||
let mut next_last = 0usize;
|
||||
let mut drawn = vec![false; faces.len()];
|
||||
let mut out = Vec::with_capacity(order.len());
|
||||
let mut first = 0usize;
|
||||
while out.len() < order.len() {
|
||||
while last.get(next_last).is_some_and(|&k| drawn[k]) {
|
||||
next_last += 1;
|
||||
}
|
||||
let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]);
|
||||
let k = match ready.peek() {
|
||||
Some(&Reverse((at, k))) if at < limit => {
|
||||
ready.pop();
|
||||
k
|
||||
}
|
||||
_ => {
|
||||
// A cycle, or the faces left to draw before a face drawn last wait for faces after
|
||||
// it: the first face in `order` not drawn yet goes next.
|
||||
while order.get(first).is_some_and(|&k| drawn[k]) {
|
||||
first += 1;
|
||||
}
|
||||
let Some(&k) = order.get(first) else { break };
|
||||
k
|
||||
}
|
||||
};
|
||||
if drawn[k] {
|
||||
continue;
|
||||
}
|
||||
drawn[k] = true;
|
||||
out.push(k);
|
||||
for &j in &after[k] {
|
||||
waits[j] = waits[j].saturating_sub(1);
|
||||
if waits[j] == 0 && !drawn[j] {
|
||||
ready.push(Reverse((position[j], j)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing,
|
||||
/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is
|
||||
/// not convex, or when they are at the same depth there.
|
||||
fn nearer_where_overlapping(a: &Placed, b: &Placed) -> Option<bool> {
|
||||
let (pa, pb) = (a.plane?, b.plane?);
|
||||
let turn = convex(&b.outline)?;
|
||||
convex(&a.outline)?;
|
||||
let overlap = clip_convex(&a.outline, &b.outline, turn);
|
||||
let mid = centroid(&overlap)?;
|
||||
let (da, db) = (pa.depth_at(mid)?, pb.depth_at(mid)?);
|
||||
let tolerance = 1e-6 * (1.0 + da.abs().max(db.abs()));
|
||||
((da - db).abs() > tolerance).then_some(da > db)
|
||||
}
|
||||
|
||||
/// The sign of the turns of convex polygon `p` (`None` when it is not convex or has no area).
|
||||
fn convex(p: &[Point]) -> Option<f64> {
|
||||
let n = p.len();
|
||||
let mut sign = 0.0;
|
||||
for i in 0..n {
|
||||
let (a, b, c) = (p[i], p[(i + 1) % n], p[(i + 2) % n]);
|
||||
let cross = (b - a).cross(c - b);
|
||||
if cross.abs() <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
if sign == 0.0 {
|
||||
sign = cross.signum();
|
||||
} else if cross.signum() != sign {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(sign != 0.0).then_some(sign)
|
||||
}
|
||||
|
||||
/// The part of polygon `subject` inside convex polygon `clip`, whose turns have sign `turn`
|
||||
/// (Sutherland–Hodgman).
|
||||
fn clip_convex(subject: &[Point], clip: &[Point], turn: f64) -> Vec<Point> {
|
||||
let mut out = subject.to_vec();
|
||||
for i in 0..clip.len() {
|
||||
if out.is_empty() {
|
||||
break;
|
||||
}
|
||||
let (e0, e1) = (clip[i], clip[(i + 1) % clip.len()]);
|
||||
let side = |p: Point| (e1 - e0).cross(p - e0) * turn;
|
||||
let input = std::mem::take(&mut out);
|
||||
for j in 0..input.len() {
|
||||
let (p, q) = (input[j], input[(j + 1) % input.len()]);
|
||||
let (sp, sq) = (side(p), side(q));
|
||||
if sp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (sp >= 0.0) != (sq >= 0.0) {
|
||||
let t = sp / (sp - sq);
|
||||
out.push(p.lerp(q, t));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The centroid of polygon `p`, `None` when it has (almost) no area. It is measured from the
|
||||
/// polygon's first point, so a small polygon far from the origin keeps its area.
|
||||
fn centroid(p: &[Point]) -> Option<Point> {
|
||||
let origin = *p.first()?;
|
||||
let n = p.len();
|
||||
let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0);
|
||||
for i in 0..n {
|
||||
let (a, b) = (p[i] - origin, p[(i + 1) % n] - origin);
|
||||
let cross = a.x * b.y - b.x * a.y;
|
||||
area += cross;
|
||||
cx += (a.x + b.x) * cross;
|
||||
cy += (a.y + b.y) * cross;
|
||||
}
|
||||
(area.abs() > 1e-9).then(|| origin + Vec2::new(cx / (3.0 * area), cy / (3.0 * area)))
|
||||
}
|
||||
|
||||
/// The most bounds comparisons [`draw_order`] makes; the fill walls it has not reached by then keep
|
||||
/// their depths.
|
||||
const MAX_OVERLAP_CHECKS: usize = 4_000_000;
|
||||
@@ -742,7 +1193,8 @@ const MAX_OVERLAP_CHECKS: usize = 4_000_000;
|
||||
/// of a shape's fill turned toward the viewer is drawn before each face of the same shape's
|
||||
/// covering strokes ([`Paints::Stroke`]), turned toward the viewer, whose bounds overlap its own.
|
||||
/// Such a stroke's closed solid holds the fill's walls, so they never show and can be drawn under
|
||||
/// any other face.
|
||||
/// any other face. A shape's fill faces and the faces of its other strokes then go in the order of
|
||||
/// their depths where they overlap ([`local_order`]).
|
||||
fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
|
||||
// Each face's depth to sort by, and whether it was moved before a stroke face at that depth.
|
||||
let mut keys: Vec<(f64, bool)> = faces.iter().map(|f| (f.depth, false)).collect();
|
||||
@@ -781,7 +1233,7 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
|
||||
// A stable sort: faces at the same depth keep the order of the appearance, and a fill's side
|
||||
// face moved to a stroke face's depth goes before it.
|
||||
order.sort_by(|&a, &b| keys[a].0.total_cmp(&keys[b].0).then(keys[b].1.cmp(&keys[a].1)));
|
||||
order
|
||||
local_order(faces, order)
|
||||
}
|
||||
|
||||
/// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before`
|
||||
@@ -806,7 +1258,9 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
|
||||
/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as
|
||||
/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's
|
||||
/// fill walls before the faces of its covering strokes that overlap them: [`draw_order`]), the
|
||||
/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and
|
||||
/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the
|
||||
/// order of their depths where they overlap: [`draw_order`]), the
|
||||
/// faces of a solid in a gradient with transparent stops in runs that carry its opacity mask
|
||||
/// ([`in_runs`]);
|
||||
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
|
||||
@@ -995,18 +1449,22 @@ type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>
|
||||
|
||||
/// [`with_graphics`] of built surfaces, each drawn whole.
|
||||
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts)
|
||||
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts)
|
||||
}
|
||||
|
||||
/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each
|
||||
/// right after its surface, with that surface's scopes and its opacity mask (a gradient's
|
||||
/// transparency), so a graphic is hidden where its cap is.
|
||||
fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc<Node>)>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
/// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts`
|
||||
/// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes
|
||||
/// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is.
|
||||
fn with_graphics<'s>(
|
||||
surfaces: Vec<(&'s [Scope], Arc<Node>)>,
|
||||
first: usize,
|
||||
arts: &[(usize, PlanarFace, Arc<Node>)],
|
||||
) -> Vec<(&'s [Scope], Arc<Node>)> {
|
||||
let mut out = Vec::with_capacity(surfaces.len() + arts.len());
|
||||
for (k, (scopes, s)) in surfaces.into_iter().enumerate() {
|
||||
let mask = s.extras().mask.clone();
|
||||
out.push((scopes, s));
|
||||
out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| {
|
||||
out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| {
|
||||
let mut art = art.clone();
|
||||
if let Some(mask) = &mask {
|
||||
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
|
||||
@@ -1058,7 +1516,7 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
}
|
||||
}
|
||||
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
|
||||
let out = with_graphics(out, &arts);
|
||||
let out = with_graphics(out, 0, &arts);
|
||||
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
@@ -1085,6 +1543,43 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
let (_, opacity, blend) = paint_of(item, *member);
|
||||
opacity >= 1.0 && blend == BlendMode::Normal
|
||||
});
|
||||
let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path));
|
||||
// A solid whose surface is one composite of all its facets ([`surface`]: a solid color under
|
||||
// colored lights with smooth shading) has no faces to order.
|
||||
let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some());
|
||||
// The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under
|
||||
// a member's opacity mask or blending, each member's faces go in one order of their own when its
|
||||
// fills and strokes are opaque, blend normally, carry no opacity mask and are not composites.
|
||||
let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f));
|
||||
let shape_order: Vec<bool> = (0..shapes.len())
|
||||
.map(|shape| {
|
||||
solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| {
|
||||
let (paint, opacity, blend) = paint_of(item, *member);
|
||||
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order };
|
||||
if solids.iter().any(|s| ordered(s.4)) {
|
||||
// A stroke face that passes through a fill wall or another stroke's face is cut where it
|
||||
// does. The pieces count against the limits as the faces did: cutting stops before the
|
||||
// faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that
|
||||
// draws uncut still draws.
|
||||
let counts: Vec<usize> = solids.iter().map(|(.., f, _)| f.len()).collect();
|
||||
let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes);
|
||||
let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids
|
||||
.iter_mut()
|
||||
.filter(|(.., shape)| ordered(*shape))
|
||||
.map(|(item, _, _, f, shape)| (Paints::of(item, closed(*shape)), *shape, f))
|
||||
.collect();
|
||||
cut_stroke_faces(&mut cuts, room);
|
||||
for ((item, _, _, f, _), before) in solids.iter().zip(counts) {
|
||||
let added = f.get(before..).unwrap_or_default();
|
||||
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(added, paint_ref(item), colored), paint_ref(item)) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let arts = if !graphics_on {
|
||||
vec![]
|
||||
} else {
|
||||
@@ -1100,11 +1595,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
.collect();
|
||||
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
|
||||
};
|
||||
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
|
||||
let surfaces: Vec<BuiltSurface> = solids
|
||||
.into_iter()
|
||||
.map(|(item, member, scopes, f, shape)| {
|
||||
let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed));
|
||||
let paints = Paints::of(item, closed);
|
||||
let paints = Paints::of(item, closed(shape));
|
||||
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
|
||||
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
|
||||
let (paint, opacity, blend) = paint_of(item, member);
|
||||
@@ -1112,50 +1607,86 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
(depths, art, scopes, ends)
|
||||
})
|
||||
.collect();
|
||||
if masks {
|
||||
return Some(masked(n.id, whole_surfaces(surfaces, &arts)));
|
||||
}
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. With
|
||||
// colored lights a surface can instead be one clipped composite of all its facets. A composite
|
||||
// has no faces to order, so when any surface is one, every surface of the solid, masked ones
|
||||
// included, draws whole in member order.
|
||||
let plain =
|
||||
surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
|
||||
// A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs
|
||||
// ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole,
|
||||
// each graphic right after its surface.
|
||||
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
|
||||
let masked_faces = masks.iter().any(Option::is_some);
|
||||
if !opaque || !plain || (masked_faces && !arts.is_empty()) {
|
||||
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
|
||||
}
|
||||
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
|
||||
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
|
||||
if let NodeKind::Group { children, .. } = s.kind {
|
||||
placed.extend(depths);
|
||||
faces.extend(children.into_iter().map(|face| Some((surface, face))));
|
||||
ends.extend(e);
|
||||
}
|
||||
}
|
||||
let sealed = match fx.id.as_str() {
|
||||
INFLATE => inflate_options(&p).cap,
|
||||
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
|
||||
_ => extrude_options(&p).cap,
|
||||
};
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. With
|
||||
// colored lights a surface can instead be one clipped composite of all its facets. A composite
|
||||
// has no faces to order, so it draws whole.
|
||||
let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len());
|
||||
if masks {
|
||||
// Each member's surfaces, in the scopes of its opacity mask or blending: its faces in one
|
||||
// order when it is opaque and plain, otherwise each surface whole.
|
||||
let mut out = vec![];
|
||||
let mut surfaces = surfaces.into_iter().zip(members).enumerate().peekable();
|
||||
while let Some((first, (s, member))) = surfaces.next() {
|
||||
let mut run = vec![s];
|
||||
while let Some((_, (s, _))) = surfaces.next_if(|(_, (_, m))| *m == member) {
|
||||
run.push(s);
|
||||
}
|
||||
let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none());
|
||||
if ordered(member) && flat {
|
||||
let scopes = run.first().map_or(&[][..], |s| s.2);
|
||||
out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed)))));
|
||||
} else {
|
||||
out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts));
|
||||
}
|
||||
}
|
||||
return Some(masked(n.id, out));
|
||||
}
|
||||
if !opaque || !surfaces.iter().all(plain) {
|
||||
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
|
||||
}
|
||||
Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))])
|
||||
}
|
||||
|
||||
/// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in
|
||||
/// one order ([`draw_order`], `sealed` for solids with caps), each of the graphics `arts` of those
|
||||
/// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops
|
||||
/// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of
|
||||
/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is.
|
||||
fn in_one_order(id: NodeId, surfaces: Vec<BuiltSurface<'_>>, first: usize, arts: &[(usize, PlanarFace, Arc<Node>)], sealed: bool) -> Vec<Arc<Node>> {
|
||||
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
|
||||
let arts: Vec<&(usize, PlanarFace, Arc<Node>)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect();
|
||||
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
|
||||
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
|
||||
if let NodeKind::Group { children, .. } = s.kind {
|
||||
placed.extend(depths);
|
||||
faces.extend(children.into_iter().map(|face| Some((surface, face))));
|
||||
ends.extend(e.into_iter().map(|end| end.map(|end| (surface, end))));
|
||||
}
|
||||
}
|
||||
let order = draw_order(&placed, sealed);
|
||||
if masked_faces {
|
||||
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
|
||||
return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]);
|
||||
}
|
||||
// Each face's graphics go right after the last of the faces they are drawn on.
|
||||
let last: Vec<Option<usize>> =
|
||||
arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect();
|
||||
let mut children = Vec::with_capacity(order.len() + arts.len());
|
||||
// Each graphic goes right after the last of the faces it is drawn on, among the surfaces that
|
||||
// share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a
|
||||
// mask that ends at its surface.
|
||||
let last: Vec<Option<usize>> = arts
|
||||
.iter()
|
||||
.map(|(at, face, _)| {
|
||||
let at = at - first;
|
||||
let from = if masks.get(at).is_some_and(Option::is_some) {
|
||||
at
|
||||
} else {
|
||||
masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1)
|
||||
};
|
||||
order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface)))
|
||||
})
|
||||
.collect();
|
||||
let mut drawn: Vec<(usize, Arc<Node>)> = Vec::with_capacity(order.len() + arts.len());
|
||||
for (at, k) in order.into_iter().enumerate() {
|
||||
children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face));
|
||||
children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone()));
|
||||
drawn.extend(faces.get_mut(k).and_then(Option::take));
|
||||
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| {
|
||||
let mut art = art.clone();
|
||||
if let Some(mask) = masks.get(surface - first).cloned().flatten() {
|
||||
Arc::make_mut(&mut art).extras_mut().mask = Some(mask);
|
||||
}
|
||||
// An index past the surfaces: the graphic goes in a run of its own, with its own mask.
|
||||
(masks.len(), art)
|
||||
}));
|
||||
}
|
||||
Some(vec![Arc::new(Node::group(n.id, children))])
|
||||
if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() }
|
||||
}
|
||||
|
||||
/// `faces` in their back-to-front order, each with the index of its surface, where some surfaces
|
||||
@@ -1311,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
|
||||
@@ -1357,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);
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -253,6 +253,468 @@ fn a_fills_walls_are_drawn_before_the_stroke_faces_over_them() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The faces of the solids effect `id` with `params` builds for `n`, in the order they are drawn,
|
||||
/// as [`surfaces_for`] orders them, each with the index of the part ([`solid_parts`]) it was built
|
||||
/// from and whether it is a stroke's.
|
||||
fn drawn_parts(n: &Node, id: &str, params: &Value) -> Vec<(Facet, usize, bool)> {
|
||||
let (path, rule) = profile(n).unwrap();
|
||||
let shapes = [Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }];
|
||||
let p = crate::merged_params(id, params);
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
let mut solids = vec![];
|
||||
for (part, ((item, _, _, _, _, member), f)) in parts.iter().zip(built_solids(id, &p, &parts, bounds, MAX_OBJECT_FACES)).enumerate() {
|
||||
let Some(f) = f.unwrap() else { continue };
|
||||
let closed = holds_edge(id, &shapes[*member].path);
|
||||
solids.push((Paints::of(item, closed), *member, f, part, matches!(item, AppearanceItem::Stroke(_))));
|
||||
}
|
||||
let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids.iter_mut().map(|(paints, member, f, _, _)| (*paints, *member, f)).collect();
|
||||
cut_stroke_faces(&mut cuts, MAX_OBJECT_FACES);
|
||||
let (mut placed, mut all) = (vec![], vec![]);
|
||||
for (paints, member, f, part, stroke) in solids {
|
||||
for facet in f {
|
||||
placed.push(Placed::of(&facet, member, paints));
|
||||
all.push((facet, part, stroke));
|
||||
}
|
||||
}
|
||||
let sealed = match id {
|
||||
INFLATE => inflate_options(&p).cap,
|
||||
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
|
||||
_ => extrude_options(&p).cap,
|
||||
};
|
||||
draw_order(&placed, sealed).into_iter().map(|k| all[k].clone()).collect()
|
||||
}
|
||||
|
||||
/// Is `p` inside the polygon of `f` (nonzero winding)?
|
||||
fn facet_contains(f: &Facet, p: Point) -> bool {
|
||||
let mut winding = 0i32;
|
||||
for c in &f.contours {
|
||||
for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) {
|
||||
let cross = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
|
||||
if a.y <= p.y && b.y > p.y && cross > 0.0 {
|
||||
winding += 1;
|
||||
} else if a.y > p.y && b.y <= p.y && cross < 0.0 {
|
||||
winding -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
winding != 0
|
||||
}
|
||||
|
||||
/// The points of a 1 pt grid over `faces` (drawn in that order, each with whether it is a stroke's)
|
||||
/// where the face drawn on top is the fill's while a face of the stroke turned toward the viewer is
|
||||
/// nearer the viewer there by more than 0.5 pt, or the other way round. Points within 0.3 pt of an
|
||||
/// edge are left out.
|
||||
fn wrong_on_top(faces: &[(Facet, bool)]) -> Vec<Point> {
|
||||
let polygons: Vec<&Facet> = faces.iter().map(|(f, _)| f).collect();
|
||||
let extent =
|
||||
polygons.iter().flat_map(|f| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p));
|
||||
let mut wrong = vec![];
|
||||
let mut y = extent.y0.floor() + 0.5;
|
||||
while y < extent.y1 {
|
||||
let mut x = extent.x0.floor() + 0.5;
|
||||
while x < extent.x1 {
|
||||
let p = Point::new(x, y);
|
||||
let well_inside = |f: &Facet| {
|
||||
[(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy)))
|
||||
};
|
||||
let top = faces.iter().rposition(|(f, _)| facet_contains(f, p));
|
||||
if let Some((f, stroke)) = top.and_then(|k| faces.get(k)).filter(|(f, _)| !f.away && well_inside(f)) {
|
||||
let nearest = |of_stroke: bool| {
|
||||
faces.iter().filter(|(g, s)| *s == of_stroke && !g.away && well_inside(g)).filter_map(|(g, _)| g.depth_at(p)).reduce(f64::max)
|
||||
};
|
||||
if let (Some(ds), Some(df)) = (nearest(true), nearest(false))
|
||||
&& (ds - df).abs() > 0.5
|
||||
&& (ds > df) != *stroke
|
||||
&& f.depth_at(p).is_some()
|
||||
{
|
||||
wrong.push(p);
|
||||
}
|
||||
}
|
||||
x += 1.0;
|
||||
}
|
||||
y += 1.0;
|
||||
}
|
||||
wrong
|
||||
}
|
||||
|
||||
/// The points of a 1 pt grid over `faces` (drawn in that order) where the face drawn on top is
|
||||
/// farther from the viewer than another face turned toward the viewer, of any part, by more than
|
||||
/// 0.5 pt. Points within 0.3 pt of an edge, and faces without a plane, are left out.
|
||||
fn misdrawn(faces: &[(Facet, usize, bool)]) -> Vec<Point> {
|
||||
let extent =
|
||||
faces.iter().flat_map(|(f, ..)| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p));
|
||||
let mut wrong = vec![];
|
||||
let mut y = extent.y0.floor() + 0.5;
|
||||
while y < extent.y1 {
|
||||
let mut x = extent.x0.floor() + 0.5;
|
||||
while x < extent.x1 {
|
||||
let p = Point::new(x, y);
|
||||
let well_inside = |f: &Facet| {
|
||||
[(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy)))
|
||||
};
|
||||
let top = faces.iter().rposition(|(f, ..)| facet_contains(f, p)).and_then(|k| faces.get(k)).filter(|(f, ..)| !f.away && well_inside(f));
|
||||
if let Some(on_top) = top.and_then(|(f, ..)| f.depth_at(p)) {
|
||||
let nearest = faces.iter().filter(|(g, ..)| !g.away && well_inside(g)).filter_map(|(g, ..)| g.depth_at(p)).reduce(f64::max);
|
||||
if nearest.is_some_and(|d| d - on_top > 0.5) {
|
||||
wrong.push(p);
|
||||
}
|
||||
}
|
||||
x += 1.0;
|
||||
}
|
||||
y += 1.0;
|
||||
}
|
||||
wrong
|
||||
}
|
||||
|
||||
/// The faces of a shape's fill and strokes are drawn in the order of their depths where they
|
||||
/// overlap: on a turned C, with or without perspective, under a stroke that does not cover the
|
||||
/// fill's whole edge (dashed, with a width profile, or with a brush), under a plain stroke and
|
||||
/// under two strokes whose faces pass through each other, no point shows a face farther from the
|
||||
/// viewer than another, in Extrude & Bevel and Extrude & Bevel (Classic), and only a few in
|
||||
/// Inflate, where curved puffs cross.
|
||||
#[test]
|
||||
fn fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap() {
|
||||
use vectorcraft_doc::{Dash, WidthProfile};
|
||||
let views = [
|
||||
json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}),
|
||||
json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10}),
|
||||
json!({"rotationX": -30, "rotationY": 50, "rotationZ": 5, "perspectiveAngle": 40}),
|
||||
json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}),
|
||||
];
|
||||
type Style<'a> = (&'a str, &'a dyn Fn(&mut Node));
|
||||
let first = |n: &mut Node, set: &dyn Fn(&mut StrokeLayer)| {
|
||||
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
set(s);
|
||||
}
|
||||
};
|
||||
let dash = |pattern: Vec<f64>, offset: f64| Some(Dash { pattern, offset, align_corners: false });
|
||||
let styles: [Style; 6] = [
|
||||
("plain", &|_| {}),
|
||||
("dashed", &|n| first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0))),
|
||||
("profiled", &|n| first(n, &|s| s.profile = Some(WidthProfile::lens()))),
|
||||
("brushed", &|n| first(n, &|s| s.brush = Some("brush".into()))),
|
||||
("dashed with perspective", &|n| first(n, &|s| s.dash = dash(vec![20.0, 6.0], 3.0))),
|
||||
("two strokes", &|n| {
|
||||
first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0));
|
||||
let mut wide = StrokeLayer::new(Paint::solid(RED), 14.0);
|
||||
wide.profile = Some(WidthProfile::lens());
|
||||
n.appearance.items.push(AppearanceItem::Stroke(wide));
|
||||
}),
|
||||
];
|
||||
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
|
||||
for (v, view) in views.iter().enumerate() {
|
||||
for (style, set) in &styles {
|
||||
// The last two views, for the plain and the two strokes only.
|
||||
if v >= 2 && !["plain", "two strokes"].contains(style) {
|
||||
continue;
|
||||
}
|
||||
let mut params = view.clone();
|
||||
params["depth"] = json!(60);
|
||||
if style.contains("perspective") {
|
||||
params["perspectiveAngle"] = json!(40);
|
||||
}
|
||||
let mut n = stroked(&letter_c());
|
||||
set(&mut n);
|
||||
let parts = drawn_parts(&n, id, ¶ms);
|
||||
let faces: Vec<(Facet, bool)> = parts.iter().map(|(f, _, s)| (f.clone(), *s)).collect();
|
||||
assert!(faces.iter().any(|(_, s)| *s) && faces.iter().any(|(_, s)| !*s), "{id} {view} {style}: faces of both");
|
||||
// Inflate's curved puffs cross each other along curves its flat facets only follow
|
||||
// roughly: a few points next to those crossings may still show the farther face.
|
||||
let allowed = if id == INFLATE { 5 } else { 0 };
|
||||
let wrong = wrong_on_top(&faces);
|
||||
assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points drawn in the wrong paint, first {:?}", wrong.len(), wrong.first());
|
||||
let wrong = misdrawn(&parts);
|
||||
assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points show a farther face, first {:?}", wrong.len(), wrong.first());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths of `art`'s faces in drawing order, leaving out the graphics (clip groups).
|
||||
fn face_paths(art: &Node) -> Vec<PathData> {
|
||||
fn walk(n: &Node, out: &mut Vec<PathData>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { clip: true, .. } => {}
|
||||
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ => out.extend(n.path_data().cloned()),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(art, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// A member of a 3D group with an opacity mask or a blending mode of its own draws its fill's and
|
||||
/// its strokes' faces in one order inside that mask, the order the same member draws them in
|
||||
/// without it, its dashes cut where they pass through the fill's walls. A member whose stroke is
|
||||
/// translucent still draws each surface whole.
|
||||
#[test]
|
||||
fn a_masked_members_fill_and_stroke_faces_go_in_one_order() {
|
||||
let mut member = stroked(&letter_c());
|
||||
if let Some(AppearanceItem::Stroke(s)) = member.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
|
||||
}
|
||||
let solid = |member: Node| {
|
||||
let mut g = Node::group(NodeId(2), vec![Arc::new(member)]);
|
||||
g.appearance.effects.push(fx(EXTRUDE, json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})));
|
||||
solid_art(&g).unwrap()
|
||||
};
|
||||
let cover = Node::path(
|
||||
NodeId(900),
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)),
|
||||
Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0),
|
||||
);
|
||||
let mut masked = member.clone();
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true)));
|
||||
let mut multiplied = member.clone();
|
||||
multiplied.blend = BlendMode::Multiply;
|
||||
let unmasked = face_paths(&solid(member.clone()));
|
||||
for (what, scoped) in [("masked", masked.clone()), ("multiplied", multiplied)] {
|
||||
let art = solid(scoped);
|
||||
let mut scopes = 0;
|
||||
art.walk(&mut |n| scopes += usize::from(n.extras().mask.is_some() || n.blend == BlendMode::Multiply));
|
||||
assert!(scopes > 0, "{what}: drawn in its scope");
|
||||
assert_eq!(face_paths(&art), unmasked, "{what}: the faces in the member's one order");
|
||||
}
|
||||
// A translucent stroke keeps its surface whole: the fill's faces, then the stroke's.
|
||||
if let Some(AppearanceItem::Stroke(s)) = masked.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
s.opacity = 0.5;
|
||||
}
|
||||
let art = solid(masked);
|
||||
let mut groups = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if n.opacity == 0.5 {
|
||||
groups.push(n.children().map_or(0, Vec::len));
|
||||
}
|
||||
});
|
||||
assert_eq!(groups.len(), 1, "the stroke's surface is one translucent group");
|
||||
}
|
||||
|
||||
/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the
|
||||
/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color,
|
||||
/// drawn as one composite of each surface's facets, still draws each surface whole.
|
||||
#[test]
|
||||
fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let gradient = |c: Color| {
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)],
|
||||
))))
|
||||
};
|
||||
let mut n = stroked(&letter_c());
|
||||
for item in &mut n.appearance.items {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => f.paint = gradient(RED),
|
||||
AppearanceItem::Stroke(s) => {
|
||||
s.paint = gradient(BLUE);
|
||||
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
// How many surfaces the art draws, and how many faces the first holds.
|
||||
let drawn = |n: &Node, lights: Option<Value>| {
|
||||
let mut n = n.clone();
|
||||
let mut p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60});
|
||||
if let Some(lights) = lights {
|
||||
p["lights"] = lights;
|
||||
}
|
||||
n.appearance.effects.push(fx(INFLATE, p));
|
||||
let art = solid_art(&n).unwrap();
|
||||
let surfaces = art.children().unwrap();
|
||||
(surfaces.len(), surfaces[0].children().map_or(0, Vec::len))
|
||||
};
|
||||
let colored = json!([{"color": "#ff8080"}]);
|
||||
let white = drawn(&n, None);
|
||||
assert_eq!(white.0, 1, "one order");
|
||||
let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len();
|
||||
assert_eq!(white.1, cut, "the white light's faces, cut");
|
||||
assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light");
|
||||
// A solid color under the colored light: a composite for each of the fill and the stroke.
|
||||
let solid = stroked(&letter_c());
|
||||
assert_eq!(drawn(&solid, Some(colored)).0, 2);
|
||||
}
|
||||
|
||||
/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they
|
||||
/// overlap is cut along the line where their depths meet, into the piece in front of the wall and
|
||||
/// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke
|
||||
/// and a cut past the room left are left whole.
|
||||
#[test]
|
||||
fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
|
||||
let facet = |x: f64, normal: [f64; 3], offset: f64| Facet {
|
||||
contours: vec![vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]],
|
||||
depth: 0.0,
|
||||
brightness: 1.0,
|
||||
illumination: [1.0; 3],
|
||||
normal,
|
||||
rgb_gradient: None,
|
||||
outline: None,
|
||||
side: true,
|
||||
away: false,
|
||||
end: None,
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
|
||||
// z = x - 8: behind the wall left of x = 8, in front of it right of it.
|
||||
let r = std::f64::consts::FRAC_1_SQRT_2;
|
||||
let mut through = facet(5.0, [-r, 0.0, r], -8.0 * r);
|
||||
// Its curved outline: the top edge bows up to y = -2.
|
||||
let mut curved = BezPath::new();
|
||||
curved.move_to((5.0, 0.0));
|
||||
curved.curve_to((8.0, -8.0 / 3.0), (12.0, -8.0 / 3.0), (15.0, 0.0));
|
||||
curved.line_to((15.0, 10.0));
|
||||
curved.line_to((5.0, 10.0));
|
||||
curved.close_path();
|
||||
through.outline = Some(PathData::from_bezpath(&curved));
|
||||
let extent = |f: &Facet| polygon_bounds(&f.contours[0]);
|
||||
let cut_with = |paints: Paints, member: usize, room: usize| {
|
||||
let (mut fill, mut stroke) = (vec![wall.clone()], vec![through.clone()]);
|
||||
let mut solids: Vec<(Paints, usize, &mut Vec<Facet>)> = vec![(Paints::Fill, 0, &mut fill), (paints, member, &mut stroke)];
|
||||
cut_stroke_faces(&mut solids, room);
|
||||
stroke
|
||||
};
|
||||
let pieces = cut_with(Paints::Other, 0, 10);
|
||||
assert_eq!(pieces.len(), 2);
|
||||
let (near, far) = (extent(&pieces[0]), extent(&pieces[1]));
|
||||
assert!((near.x0 - 8.0).abs() < 1e-9 && near.x1 == 15.0 && far.x0 == 5.0 && (far.x1 - 8.0).abs() < 1e-9, "{near:?} {far:?}");
|
||||
assert!(pieces[0].depth > 0.0 && pieces[1].depth < 0.0);
|
||||
// Each piece keeps its side of the curved outline, the bowed edge included.
|
||||
let curve = |f: &Facet| f.outline.as_ref().and_then(PathData::bounds).unwrap();
|
||||
let (near, far) = (curve(&pieces[0]), curve(&pieces[1]));
|
||||
assert!((near.x0 - 8.0).abs() < 1e-6 && (near.x1 - 15.0).abs() < 1e-6 && near.y0 < -1.5, "{near:?}");
|
||||
assert!((far.x0 - 5.0).abs() < 1e-6 && (far.x1 - 8.0).abs() < 1e-6 && far.y0 < -1.5, "{far:?}");
|
||||
let whole = std::slice::from_ref(&through);
|
||||
assert_eq!(cut_with(Paints::Other, 1, 10), whole, "another shape's stroke");
|
||||
assert_eq!(cut_with(Paints::Stroke, 0, 10), whole, "a covering stroke");
|
||||
assert_eq!(cut_with(Paints::Other, 0, 0), whole, "no room");
|
||||
let (mut fill, mut stroke) = (vec![wall.clone()], vec![facet(5.0, [0.0, 0.0, 1.0], 1.0)]);
|
||||
cut_stroke_faces(&mut [(Paints::Fill, 0, &mut fill), (Paints::Other, 0, &mut stroke)], 10);
|
||||
assert_eq!(stroke.len(), 1, "in front of the wall wherever they overlap");
|
||||
// Of two of a shape's strokes whose faces pass through each other, the later stroke's face is
|
||||
// cut against the earlier one's; a covering stroke's face is never cut, and the other stroke's
|
||||
// face is cut against it. Two shapes' strokes are left whole.
|
||||
for (case, (first, second, cut_first)) in
|
||||
[(Paints::Other, Paints::Other, false), (Paints::Stroke, Paints::Other, false), (Paints::Other, Paints::Stroke, true)].into_iter().enumerate()
|
||||
{
|
||||
let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]);
|
||||
cut_stroke_faces(&mut [(first, 0, &mut a), (second, 0, &mut b)], 10);
|
||||
assert_eq!((a.len(), b.len()), if cut_first { (2, 1) } else { (1, 2) }, "case {case}");
|
||||
}
|
||||
let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]);
|
||||
cut_stroke_faces(&mut [(Paints::Other, 0, &mut a), (Paints::Other, 1, &mut b)], 10);
|
||||
assert_eq!((a.len(), b.len()), (1, 1), "two shapes");
|
||||
}
|
||||
|
||||
/// A small polygon far from the origin keeps its area and centroid.
|
||||
#[test]
|
||||
fn a_small_polygon_far_away_has_a_centroid() {
|
||||
let far = 100_000_000.0;
|
||||
let square = [Point::new(far, far), Point::new(far + 1.0, far), Point::new(far + 1.0, far + 1.0), Point::new(far, far + 1.0)];
|
||||
let c = centroid(&square).unwrap();
|
||||
assert!((c.x - far - 0.5).abs() < 1e-6 && (c.y - far - 0.5).abs() < 1e-6, "{c:?}");
|
||||
assert!(centroid(&[]).is_none() && centroid(&square[..2]).is_none());
|
||||
}
|
||||
|
||||
/// Cutting adds no more faces than the object's face limit and the paint-copy allowance leave room
|
||||
/// for, so an effect that draws with its faces uncut still draws.
|
||||
#[test]
|
||||
fn cutting_stays_within_the_face_limit_and_the_paint_allowance() {
|
||||
let items = stroked(&letter_c()).appearance.items.clone();
|
||||
let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap();
|
||||
let mut one = 0usize;
|
||||
crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke));
|
||||
let max = crate::revolve::MAX_PAINT_COPIES;
|
||||
assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one));
|
||||
assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0);
|
||||
assert_eq!(cut_room(items.iter(), 10, max - 3 * one), 3);
|
||||
assert_eq!(cut_room(items.iter(), 10, max + 1), 0);
|
||||
}
|
||||
|
||||
/// Where a shape's fill wall and a face of its stroke that leaves gaps overlap, the one nearer the
|
||||
/// viewer there is drawn after the other, whichever their depths put first; a stroke face that
|
||||
/// overlaps no fill wall keeps its place.
|
||||
#[test]
|
||||
fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
let at = |depth: f64, x: f64, z: f64, paints: Paints| Placed {
|
||||
depth,
|
||||
side: true,
|
||||
away: false,
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member: 0,
|
||||
paints,
|
||||
outline: square(x),
|
||||
plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: z, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
// 0 a fill wall at z 0; 1 a stroke face over half of it, nearer, sorted before it; 2 a stroke
|
||||
// face elsewhere; 3 a stroke face over it, farther, sorted after it.
|
||||
let faces =
|
||||
[at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 1.0, Paints::Other), at(1.0, 20.0, 1.0, Paints::Other), at(6.0, 2.0, -1.0, Paints::Other)];
|
||||
assert_eq!(draw_order(&faces, true), [2, 3, 0, 1]);
|
||||
assert_eq!(draw_order(&faces, false), [2, 3, 0, 1]);
|
||||
// A covering stroke's faces keep the wall's own rule.
|
||||
let covering: Vec<Placed> = faces
|
||||
.iter()
|
||||
.map(|f| Placed { paints: if f.paints == Paints::Other { Paints::Stroke } else { f.paints }, outline: vec![], plane: None, ..*f })
|
||||
.collect();
|
||||
assert_eq!(draw_order(&covering, false), [2, 1, 0, 3]);
|
||||
// Another shape's stroke, and a stroke face at the same depth where they overlap, move nothing.
|
||||
let other_shape: Vec<Placed> =
|
||||
faces[..3].iter().map(|f| Placed { member: usize::from(f.paints == Paints::Other), outline: f.outline.clone(), ..*f }).collect();
|
||||
assert_eq!(draw_order(&other_shape, true), [2, 1, 0]);
|
||||
let level = [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 0.0, Paints::Other)];
|
||||
assert_eq!(draw_order(&level, true), [1, 0]);
|
||||
// A stroke face moved after its fill's wall does not pass a nearer face of another shape that
|
||||
// it overlaps: 0 a stroke face, 1 another shape's face in front of both, 2 the fill's wall.
|
||||
let in_front = Placed { member: 1, ..at(2.0, 5.0, 2.0, Paints::Fill) };
|
||||
let shapes = [at(1.0, 5.0, 1.0, Paints::Other), in_front, at(3.0, 0.0, 0.0, Paints::Fill)];
|
||||
assert_eq!(draw_order(&shapes, true), [2, 0, 1]);
|
||||
// A shape with a covering stroke as well keeps its fill wall before the covering stroke's face,
|
||||
// even where that face is the farther: 0 the fill's wall, 1 the covering stroke's face behind
|
||||
// it, 2 the other stroke's face in front.
|
||||
let both = [at(3.0, 0.0, 0.0, Paints::Fill), at(3.0, 0.0, -1.0, Paints::Stroke), at(2.0, 5.0, 1.0, Paints::Other)];
|
||||
assert_eq!(draw_order(&both, true), [0, 1, 2]);
|
||||
// Faces of a shape's strokes go in the order of their depths where they overlap too, with no
|
||||
// fill face among them: 1 is nearer than 0 there, though sorted before it.
|
||||
for (case, (back, front)) in
|
||||
[(Paints::Other, Paints::Other), (Paints::Stroke, Paints::Other), (Paints::Stroke, Paints::Stroke)].into_iter().enumerate()
|
||||
{
|
||||
let strokes = [at(5.0, 0.0, 0.0, back), at(2.0, 5.0, 1.0, front)];
|
||||
assert_eq!(draw_order(&strokes, true), [0, 1], "case {case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap
|
||||
/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at
|
||||
/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer
|
||||
/// than 0. 3 is the cap.
|
||||
#[test]
|
||||
fn a_depth_cycle_keeps_the_cap_last() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed {
|
||||
depth,
|
||||
side: true,
|
||||
away: false,
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member: 0,
|
||||
paints: Paints::Other,
|
||||
outline: square(x),
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
let cap = Placed {
|
||||
depth: f64::MAX,
|
||||
side: false,
|
||||
away: false,
|
||||
bounds: Rect::new(0.0, 0.0, 18.0, 10.0),
|
||||
member: 0,
|
||||
paints: Paints::Other,
|
||||
outline: vec![],
|
||||
plane: None,
|
||||
};
|
||||
let faces = [at(1.0, 0.0, [0.0, 0.0, 1.0], 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, [0.0, 0.0, 1.0], 1.0), cap];
|
||||
assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]);
|
||||
}
|
||||
|
||||
/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a
|
||||
/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A
|
||||
/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an
|
||||
@@ -266,6 +728,8 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() {
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member,
|
||||
paints,
|
||||
outline: vec![],
|
||||
plane: None,
|
||||
};
|
||||
// 0 the fill's wall; 1 the stroke's wall over it; 2 another shape's stroke over it; 3 a stroke
|
||||
// wall elsewhere; 4 a stroke face turned away; 5 a fill cap; 6 the stroke's cap, nearer; 7 a
|
||||
@@ -292,6 +756,9 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() {
|
||||
};
|
||||
assert!(Paints::of(&stroke(&|_| {}), true) == Paints::Stroke);
|
||||
assert!(Paints::of(&stroke(&|_| {}), false) == Paints::Other, "an open shape");
|
||||
let closed = profile(&stroked(&letter_c())).unwrap().0;
|
||||
assert!(holds_edge(EXTRUDE, &closed) && holds_edge(CLASSIC_EXTRUDE, &closed));
|
||||
assert!(!holds_edge(INFLATE, &closed), "an inflated fill can rise in front of its stroke");
|
||||
assert!(Paints::of(&stroke(&|s| s.width = 0.0), true) == Paints::Other, "no width");
|
||||
let dash = vectorcraft_doc::Dash { pattern: vec![4.0, 4.0], offset: 0.0, align_corners: false };
|
||||
assert!(Paints::of(&stroke(&|s| s.dash = Some(dash.clone())), true) == Paints::Other, "dashes");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -620,6 +623,110 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
|
||||
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
|
||||
}
|
||||
|
||||
/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its
|
||||
/// clipping path), leaving out the graphics (clip groups of solid-color paths).
|
||||
fn face_paths(art: &Node) -> Vec<PathData> {
|
||||
fn walk(n: &Node, out: &mut Vec<PathData>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
let graphic = children.get(1).is_some_and(|inner| match &inner.kind {
|
||||
NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| {
|
||||
p.path_data().is_some()
|
||||
&& p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some()))
|
||||
}),
|
||||
_ => false,
|
||||
});
|
||||
if !graphic {
|
||||
out.extend(children.first().and_then(|c| c.path_data()).cloned());
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ => out.extend(n.path_data().cloned()),
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(art, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke
|
||||
/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without
|
||||
/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's.
|
||||
#[test]
|
||||
fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let d = document();
|
||||
let mut stop = GradientStop::new(1.0, red());
|
||||
stop.opacity = 0.25;
|
||||
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
|
||||
let solid = |graphics: Value| {
|
||||
let mut n = object(
|
||||
EXTRUDE,
|
||||
json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}),
|
||||
);
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = Paint::Gradient(Box::new(gradient.clone()));
|
||||
}
|
||||
// A gradient stroke: a solid color under the colored light would be one composite.
|
||||
let blues = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.5))],
|
||||
);
|
||||
let mut stroke = StrokeLayer::new(Paint::Gradient(Box::new(GradientPaint::new(blues))), 6.0);
|
||||
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
|
||||
n.appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
solid_art_in(Some(&d), &n).unwrap()
|
||||
};
|
||||
let with = solid(json!([{"symbol": "Mark"}]));
|
||||
let without = solid(json!([]));
|
||||
assert!(face_paths(&without).len() > 20, "the faces are found");
|
||||
assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order");
|
||||
// The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the
|
||||
// symbol's red square); the fill's, whose surface carries the mask, carries it too.
|
||||
let mut masked = vec![];
|
||||
with.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind
|
||||
&& let [_, inner] = children.as_slice()
|
||||
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
|
||||
&& paths.iter().any(|p| {
|
||||
p.appearance.items.iter().any(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3),
|
||||
AppearanceItem::Stroke(_) => false,
|
||||
})
|
||||
})
|
||||
{
|
||||
masked.push(c.extras().mask.is_some());
|
||||
}
|
||||
});
|
||||
masked.sort_unstable();
|
||||
assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask");
|
||||
// The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn
|
||||
// after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face,
|
||||
// the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds.
|
||||
let mut drawn: Vec<(&str, Rect)> = vec![];
|
||||
with.walk(&mut |c| {
|
||||
if let NodeKind::Group { children, clip: true } = &c.kind
|
||||
&& c.extras().mask.is_some()
|
||||
&& let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds)
|
||||
{
|
||||
drawn.push(("graphic", bounds));
|
||||
}
|
||||
let first_stop = c.appearance.items.iter().find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => match &f.paint {
|
||||
Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()),
|
||||
_ => None,
|
||||
},
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
});
|
||||
if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) {
|
||||
drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds));
|
||||
}
|
||||
});
|
||||
let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap();
|
||||
let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0;
|
||||
assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() {
|
||||
let d = document();
|
||||
@@ -692,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)));
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -778,6 +803,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
|
||||
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Document Info's category titles and the Objects category's count labels.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
|
||||
pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -132,8 +132,10 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let active = s.active;
|
||||
for i in 0..s.docs.len() {
|
||||
// Each document in turn is the one Save a Copy writes; switching tabs this way leaves every
|
||||
// document's tool and interaction alone, and the active one comes back below.
|
||||
// document's tool and interaction alone, and the active one comes back below. Its colors
|
||||
// are written through its own profiles.
|
||||
s.active = Some(i);
|
||||
s.sync_front_profiles();
|
||||
let Ok(st) = s.doc() else { continue };
|
||||
let title = st.doc.title.clone();
|
||||
let stem = fileio::file_stem(st.path.as_deref().unwrap_or(&title));
|
||||
@@ -160,6 +162,7 @@ fn export_all_open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
s.active = active;
|
||||
s.sync_front_profiles();
|
||||
Ok(json!({ "files": files, "failed": failed, "format": format.id }))
|
||||
}
|
||||
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
}
|
||||
|
||||
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
|
||||
/// its image, and the settings it is traced with. The tracer makes the same paths of the same
|
||||
/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own.
|
||||
/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the
|
||||
/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in
|
||||
/// for the command's own.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct TraceInputs {
|
||||
target: NodeId,
|
||||
@@ -538,6 +539,9 @@ struct TraceInputs {
|
||||
/// Document Library: the library's colours, which the JSON leaves out
|
||||
/// ([`tr::TraceParams::swatches`]).
|
||||
swatches: Vec<[u8; 3]>,
|
||||
/// The encoded image the tracer decodes: the blob under the image's key, shared with the
|
||||
/// document. Two blobs are equal when they are the same allocation or hold the same bytes.
|
||||
bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace.
|
||||
@@ -549,7 +553,6 @@ struct Prepared {
|
||||
params_json: Value,
|
||||
preset_label: String,
|
||||
library: Vec<([u8; 3], Paint)>,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
|
||||
@@ -597,8 +600,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let bytes = Arc::clone(&blob.bytes);
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
let traced_with = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes })
|
||||
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
|
||||
}
|
||||
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
|
||||
@@ -616,11 +619,11 @@ impl Traced {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got
|
||||
/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
|
||||
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
|
||||
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
|
||||
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
// An image over the tracer's size is traced scaled down (the paths are scaled back).
|
||||
let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if !steps(0, 0) {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
@@ -682,7 +685,8 @@ impl TraceRun {
|
||||
(self.prepared.inputs.image.width, self.prepared.inputs.image.height)
|
||||
}
|
||||
|
||||
/// Does it still apply: would the command trace the same object, image and settings now?
|
||||
/// Does it still apply: would the command trace the same object, image, pixels and settings
|
||||
/// now?
|
||||
pub fn current(&self, s: &Session) -> bool {
|
||||
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
|
||||
}
|
||||
@@ -691,13 +695,13 @@ impl TraceRun {
|
||||
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
|
||||
/// document, so it can run on any thread.
|
||||
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
|
||||
trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps)
|
||||
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?;
|
||||
let Prepared { inputs, trace, view, params_json, preset_label, library } = prepare(s, c, p)?;
|
||||
let group_by_color = expand && by_color_param(c, p)?;
|
||||
// A saved preset's settings join the journal entry, so a replay traces as this run did after
|
||||
// the preset is changed, renamed or deleted.
|
||||
@@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
};
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
|
||||
@@ -143,17 +143,13 @@ pub(crate) fn subpath_selected_segments(
|
||||
let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty());
|
||||
if has_explicit_segs {
|
||||
if let Some(segments) = seg_refs {
|
||||
for &(s, seg) in segments {
|
||||
if s == si && seg < seg_count {
|
||||
selected_segs.insert(seg);
|
||||
}
|
||||
}
|
||||
selected_segs.extend(super::path::subpath_refs(segments, si).filter(|&seg| seg < seg_count));
|
||||
}
|
||||
return selected_segs;
|
||||
}
|
||||
|
||||
if let Some(anchors) = anchor_refs {
|
||||
let sub_anchors: BTreeSet<usize> = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect();
|
||||
let sub_anchors: BTreeSet<usize> = super::path::subpath_refs(anchors, si).filter(|&a| a < n).collect();
|
||||
if !sub_anchors.is_empty() {
|
||||
for i in 0..seg_count {
|
||||
let next = (i + 1) % n;
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
//! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`,
|
||||
//! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in
|
||||
//! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and
|
||||
//! take the place of the working spaces in the active settings when assigned, and when the working
|
||||
//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay
|
||||
//! as Edit → Color Settings set them.
|
||||
//! take the place of the working spaces in the active settings while the document is in front
|
||||
//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the
|
||||
//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert,
|
||||
//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color
|
||||
//! Settings set them.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
@@ -181,7 +183,7 @@ fn touch_all(s: &mut Session) {
|
||||
/// Make the active settings the working settings with the profiles the front document is assigned
|
||||
/// in place of the working spaces (none, or no document open: the working spaces). The open
|
||||
/// documents redraw when the active settings change.
|
||||
fn use_front_profiles(s: &mut Session) {
|
||||
pub(crate) fn use_front_profiles(s: &mut Session) {
|
||||
let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default();
|
||||
if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) {
|
||||
touch_all(s);
|
||||
|
||||
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
|
||||
];
|
||||
|
||||
/// The object counts of `document.info` and their labels.
|
||||
const OBJECT_LABELS: [(&str, &str); 19] = [
|
||||
pub const OBJECT_LABELS: [(&str, &str); 19] = [
|
||||
("paths", "Paths"),
|
||||
("compoundPaths", "Compound Paths"),
|
||||
("groups", "Groups"),
|
||||
|
||||
@@ -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)"));
|
||||
}
|
||||
|
||||
@@ -116,8 +116,11 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
}
|
||||
let mut emptied = Beside::replacing(d, &[id]);
|
||||
let removed = remove_anchors_of(d, sel, &mut emptied, id, [(si, ai)], curvature)?;
|
||||
let removed = remove_anchors_of(d, sel, &mut emptied, id, vec![(si, ai)], curvature)?;
|
||||
emptied.finish(d)?;
|
||||
if removed {
|
||||
sel.remove(id);
|
||||
}
|
||||
Ok(removed)
|
||||
})?;
|
||||
Ok(json!({ "removedObject": removed }))
|
||||
@@ -136,14 +139,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
return Err(bad("path.removeAnchors", "direct-select anchor points of a path"));
|
||||
}
|
||||
let removed = s.edit("Remove Anchor Points", |d, sel| {
|
||||
let mut removed = 0;
|
||||
let mut gone = Vec::new();
|
||||
let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, anchors) in jobs {
|
||||
let shape: Vec<(usize, bool)> =
|
||||
d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default();
|
||||
let next = following_anchors(&shape, &anchors);
|
||||
if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? {
|
||||
removed += 1;
|
||||
gone.push(id);
|
||||
} else if !next.is_empty() {
|
||||
// The next anchor along is selected, so the next Remove Anchor Points goes on from
|
||||
// there without picking it first (#2241).
|
||||
@@ -151,7 +154,8 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
emptied.finish(d)?;
|
||||
Ok(removed)
|
||||
sel.remove_all(gone.iter().copied());
|
||||
Ok(gone.len())
|
||||
})?;
|
||||
Ok(json!({ "removedObjects": removed }))
|
||||
}
|
||||
@@ -160,19 +164,32 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// path whose subpaths have `shape` (anchor count, closed): in each subpath, the anchor after its
|
||||
/// last removed one, round the end of a closed subpath, or the one before it at an open subpath's
|
||||
/// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors.
|
||||
/// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads
|
||||
/// only its own pairs.
|
||||
fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
let mut next = BTreeSet::new();
|
||||
let mut kept = 0;
|
||||
let mut rest = removed;
|
||||
for (si, &(n, closed)) in shape.iter().enumerate() {
|
||||
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
|
||||
let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count());
|
||||
rest = after;
|
||||
let gone = &mine[..mine.partition_point(|&(_, a)| a < n)];
|
||||
if n - gone.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
if let Some(&last) = gone.last() {
|
||||
let wrap = if closed { 0..last } else { 0..0 };
|
||||
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
|
||||
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
|
||||
next.insert((kept, a - gone.range(..a).count()));
|
||||
if let Some(&(_, last)) = gone.last() {
|
||||
// Anchors past `last` are all left. Below it, the first one left (round a closed
|
||||
// subpath's end) is past the removed run from 0, and the last one left is below the
|
||||
// removed run down from `last`.
|
||||
let a = if last + 1 < n {
|
||||
Some(last + 1)
|
||||
} else if closed {
|
||||
Some(gone.iter().zip(0..).take_while(|&(&(_, g), k)| g == k).count())
|
||||
} else {
|
||||
last.checked_sub(gone.iter().rev().zip((0..=last).rev()).take_while(|&(&(_, g), k)| g == k).count())
|
||||
};
|
||||
if let Some(a) = a {
|
||||
next.insert((kept, a - gone.partition_point(|&(_, g)| g < a)));
|
||||
}
|
||||
}
|
||||
kept += 1;
|
||||
@@ -183,34 +200,37 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr
|
||||
/// Remove `anchors` (subpath, anchor) of path `id` without opening it, refitting the curve round
|
||||
/// each one, or with `curvature` re-curving it as the Curvature tool curves its points
|
||||
/// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed,
|
||||
/// and a path left with no subpath is removed through `emptied`. True when the path went.
|
||||
/// and a path left with no subpath is removed through `emptied`; the caller then takes it out of
|
||||
/// the selection. True when the path went.
|
||||
fn remove_anchors_of(
|
||||
d: &mut Document,
|
||||
sel: &mut Selection,
|
||||
emptied: &mut Beside,
|
||||
id: NodeId,
|
||||
anchors: impl IntoIterator<Item = (usize, usize)>,
|
||||
mut anchors: Vec<(usize, usize)>,
|
||||
curvature: bool,
|
||||
) -> Result<bool> {
|
||||
let mut anchors: Vec<(usize, usize)> = anchors.into_iter().collect();
|
||||
// The last first, so the indexes still to come stay valid.
|
||||
anchors.sort_unstable_by(|a, b| b.cmp(a));
|
||||
anchors.dedup();
|
||||
let path = path_mut(d, id)?;
|
||||
for (si, ai) in anchors {
|
||||
if let Some(sp) = path.subpaths.get_mut(si) {
|
||||
if curvature {
|
||||
let mut rest = &anchors[..];
|
||||
while let Some(&(si, _)) = rest.first() {
|
||||
let (mine, after) = rest.split_at(rest.iter().take_while(|&&(s, _)| s == si).count());
|
||||
rest = after;
|
||||
let Some(sp) = path.subpaths.get_mut(si) else { continue };
|
||||
if curvature {
|
||||
for &(_, ai) in mine {
|
||||
vectorcraft_tools::draw2::curvature_remove(sp, ai);
|
||||
} else {
|
||||
po::remove_anchor(sp, ai);
|
||||
}
|
||||
} else {
|
||||
po::remove_anchors(sp, &mine.iter().map(|&(_, ai)| ai).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
path.subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
let gone = path.is_empty();
|
||||
if gone {
|
||||
emptied.put(d, id, vec![])?;
|
||||
sel.remove(id);
|
||||
} else {
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
@@ -277,3 +297,47 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [`following_anchors`] by its definition: for each subpath, a search of the anchors after
|
||||
/// its last removed one, round a closed end, then before it.
|
||||
fn following_by_search(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
|
||||
let mut next = BTreeSet::new();
|
||||
let mut kept = 0;
|
||||
for (si, &(n, closed)) in shape.iter().enumerate() {
|
||||
let gone: BTreeSet<usize> = removed.iter().filter(|&&(s, a)| s == si && a < n).map(|&(_, a)| a).collect();
|
||||
if n - gone.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
if let Some(&last) = gone.last() {
|
||||
let wrap = if closed { 0..last } else { 0..0 };
|
||||
let after = (last + 1..n).chain(wrap).find(|a| !gone.contains(a));
|
||||
if let Some(a) = after.or_else(|| (0..last).rev().find(|a| !gone.contains(a))) {
|
||||
next.insert((kept, a - gone.range(..a).count()));
|
||||
}
|
||||
}
|
||||
kept += 1;
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn following_anchors_matches_a_search_along_each_subpath() {
|
||||
let mut seed = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let mut rnd = |m: u64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % m) as usize
|
||||
};
|
||||
for case in 0..2000 {
|
||||
let shape: Vec<(usize, bool)> = (0..rnd(5) + 1).map(|_| (rnd(9), rnd(2) == 0)).collect();
|
||||
let removed: BTreeSet<(usize, usize)> = (0..rnd(14)).map(|_| (rnd(shape.len() as u64 + 1), rnd(11))).collect();
|
||||
let removed: Vec<_> = removed.into_iter().collect();
|
||||
assert_eq!(following_anchors(&shape, &removed), following_by_search(&shape, &removed), "case {case}: {shape:?} removing {removed:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,wheel]…] (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. An airbrush pen's finger wheel 0..1 (clamped): the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; 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,wheel]…] (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. An airbrush pen's finger wheel 0..1 (clamped): the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; 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
|
||||
),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1096,7 +1096,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
subpaths.extend(super::path::without_segments(sp, &cuts));
|
||||
} else {
|
||||
// Picked anchors leave the path with their connections, as Clear removes them.
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect();
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::path::subpath_refs(refs, si)).collect();
|
||||
subpaths.extend(super::path::without_anchors(sp, &gone));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -41,6 +41,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
roll_back(s, start, &stash);
|
||||
s.notify_text_tool("batch.rollBack");
|
||||
s.active = active;
|
||||
s.sync_front_profiles();
|
||||
(s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved;
|
||||
s.pending_paint = None;
|
||||
return Err(e);
|
||||
@@ -78,8 +79,11 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
|
||||
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
|
||||
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
|
||||
/// several artboards selected, pastes on those. A step that resizes the active artboard
|
||||
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
|
||||
/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither
|
||||
/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the
|
||||
/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that
|
||||
/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor
|
||||
/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`.
|
||||
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
|
||||
fn run_steps(
|
||||
s: &mut Session,
|
||||
@@ -110,9 +114,22 @@ fn run_steps(
|
||||
// Artboard tool is chosen with several artboards selected, pastes on those.
|
||||
let names_artboards = id.starts_with("edit.pasteIn")
|
||||
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
|
||||
// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard
|
||||
// tool is chosen with several artboards selected, fits those, as the command does on its own.
|
||||
let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() {
|
||||
crate::cmd::edit::artboard_tool_picks(s)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if !fit_picks.is_empty()
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
o.insert("indices".into(), json!(fit_picks));
|
||||
}
|
||||
if let Some(a) = artboard
|
||||
&& let Some(key) = key
|
||||
&& params.get(key).is_none()
|
||||
&& !(id == "artboard.fitToArt" && params.get("indices").is_some())
|
||||
&& !names_artboards
|
||||
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
@@ -129,8 +146,9 @@ fn run_steps(
|
||||
}
|
||||
grouped.push(step_groups(s, start, &held));
|
||||
// The step's journal entry records what it took from the preferences or the clock (a
|
||||
// save's date, a new document's), as a command of its own would.
|
||||
if noted != params
|
||||
// save's date, a new document's), as a command of its own would, and the artboards a Fit to
|
||||
// Artwork Bounds step took from the Artboard tool.
|
||||
if (noted != params || !fit_picks.is_empty())
|
||||
&& let Some(c) = c.as_object_mut()
|
||||
{
|
||||
c.insert("params".into(), noted);
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditabilit
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch",
|
||||
[],
|
||||
None,
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
|
||||
has_doc,
|
||||
batch::batch
|
||||
),
|
||||
|
||||
@@ -629,6 +629,13 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
{
|
||||
return Ok(Encoded::one_with_notes(bytes, notes));
|
||||
}
|
||||
// So does a `.ai` file of the art's bounds (a legacy version 7 `.ai` file has none to leave out).
|
||||
if use_artboards == Some(false)
|
||||
&& f.id == "ai"
|
||||
&& let Some(enc) = super::save::encode_ai_art_page(C, f, doc, p)?
|
||||
{
|
||||
return Ok(enc);
|
||||
}
|
||||
if use_artboards == Some(false)
|
||||
&& let Some((art, q)) = art_page(C, doc, p)?
|
||||
{
|
||||
|
||||
@@ -868,9 +868,12 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// A TIFF with more strips or tiles than the decoder can count
|
||||
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw. JPEG XL images are
|
||||
/// 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 ([`exif_orientation`]) turns or flips it is
|
||||
/// 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) {
|
||||
@@ -909,7 +912,7 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let f = image_format(kind).ok_or_else(|| err(format!("{kind:?} images can't be opened (see document.formats)")))?;
|
||||
// A photo whose EXIF orientation turns or flips it (a camera held upright) is stored as it is
|
||||
// seen, so it places the way it was taken (#4284); the others keep their own bytes.
|
||||
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| exif_orientation(bytes)).flatten();
|
||||
let orientation = matches!(f.id, "png" | "jpg" | "gif" | "webp" | "tiff").then(|| vectorcraft_doc::cmyk::exif_orientation(bytes)).flatten();
|
||||
let turned = orientation.is_some();
|
||||
// The resolution describes the stored pixels; a quarter turn swaps its axes.
|
||||
let quarter = orientation.is_some_and(|o| o.to_exif() >= 5);
|
||||
@@ -933,47 +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)
|
||||
}
|
||||
|
||||
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
|
||||
/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with
|
||||
/// extra samples) has its Orientation tag read from its first image
|
||||
/// ([`vectorcraft_doc::cmyk::tiff_orientation`]).
|
||||
pub(crate) fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
use image::ImageDecoder as _;
|
||||
use image::metadata::Orientation;
|
||||
let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok();
|
||||
let tagged = || vectorcraft_doc::cmyk::tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?));
|
||||
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
|
||||
/// 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 {
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -685,6 +685,31 @@ struct AiEditingData {
|
||||
editing_data: Option<bool>,
|
||||
}
|
||||
|
||||
/// Why a `.ai` file of the art's bounds (`useArtboards: false`) carries no editing data.
|
||||
pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str =
|
||||
"Preserve editing was left out: an .ai file of the art's bounds would replace the document's artboards when reopened";
|
||||
|
||||
/// The error for a `.ai` file of the art's bounds without PDF content.
|
||||
pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false";
|
||||
|
||||
/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of
|
||||
/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor
|
||||
/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
|
||||
/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy
|
||||
/// version 7 `.ai` file.
|
||||
pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Option<Encoded>> {
|
||||
if super::encode::use_artboards(cmd, p)? != Some(false) || super::legacy_ai::wanted(cmd, f, p)? {
|
||||
return Ok(None);
|
||||
}
|
||||
if !bool_or(p, "pdfCompatible", true) {
|
||||
return Err(bad(cmd, ART_PAGE_NEEDS_PDF));
|
||||
}
|
||||
let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
|
||||
let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?;
|
||||
enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string());
|
||||
Ok(Some(enc))
|
||||
}
|
||||
|
||||
/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file):
|
||||
/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7
|
||||
/// `.ai` files (`aiVersion: "7"`).
|
||||
@@ -692,13 +717,23 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
|
||||
if super::legacy_ai::wanted(cmd, f, p)? {
|
||||
return super::legacy_ai::encode(cmd, f, doc, p);
|
||||
}
|
||||
encode_ai_pages(cmd, f, doc, p, true)
|
||||
}
|
||||
|
||||
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
|
||||
/// the editing copy for other apps when `editing` is true, and neither otherwise.
|
||||
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
|
||||
let mut params = if p.is_object() { p.clone() } else { json!({}) };
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.insert("preserveEditing".into(), json!(true));
|
||||
o.insert("preserveEditing".into(), json!(editing));
|
||||
// Keep upstream AI PDF layers, including hidden layers, unless a standard decides.
|
||||
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() {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -402,28 +402,75 @@ fn ai_export_validates_options_even_when_editing_data_is_omitted() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
|
||||
/// Two artboards, a visible 30 × 20 pt rectangle outside them at (180, 100) and a hidden one.
|
||||
fn art_outside_the_artboards() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 2})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 180, "y": 100, "width": 30, "height": 20})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 1000, "y": 1000, "width": 50, "height": 40})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Whether the `.ai` file `bytes` carries the editing copy of its art for other apps.
|
||||
fn carries_private_data(bytes: &[u8]) -> bool {
|
||||
let opts = LoadOptions { native: false, ..Default::default() };
|
||||
load::load_with("a.ai", bytes, &opts).unwrap().editing_data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_of_the_arts_bounds_carries_no_editing_data() {
|
||||
let mut s = art_outside_the_artboards();
|
||||
let before = comparable(&s.doc().unwrap().doc);
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "range": "2"})).unwrap();
|
||||
let bytes = b64(&r);
|
||||
let pages = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
assert_eq!(pages.artboards.len(), 1);
|
||||
assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0));
|
||||
let editing = vectorcraft_pdf::editing(&bytes).unwrap();
|
||||
let exported = vectorcraft_format::load(&editing.data).unwrap();
|
||||
assert_eq!(exported.artboards.len(), 1);
|
||||
assert_eq!(exported.artboards[0].rect, vectorcraft_geom::Rect::new(180.0, 100.0, 210.0, 120.0));
|
||||
assert_eq!(comparable(&s.doc().unwrap().doc), before);
|
||||
let left_out = |v: &Value| v["warnings"].as_array().unwrap().iter().any(|w| w == super::save::AI_EDITING_NEEDS_THE_ARTBOARDS);
|
||||
let path = tmp("art-bounds.ai");
|
||||
for extra in [json!({}), json!({"range": "2"}), json!({"editingData": false}), json!({"path": path})] {
|
||||
let mut params = json!({"format": "ai", "useArtboards": false});
|
||||
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
let r = s.execute("document.export", ¶ms).unwrap();
|
||||
let bytes = if params.get("path").is_some() { std::fs::read(&path).unwrap() } else { b64(&r) };
|
||||
// One page, the visible art's bounds, whatever range names.
|
||||
let pages = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
assert_eq!(pages.artboards.len(), 1, "{params}");
|
||||
assert_eq!((pages.artboards[0].rect.width(), pages.artboards[0].rect.height()), (30.0, 20.0), "{params}");
|
||||
assert!(vectorcraft_pdf::editing(&bytes).is_none(), "{params}");
|
||||
assert!(!carries_private_data(&bytes), "{params}");
|
||||
assert!(left_out(&r), "{params}: {r}");
|
||||
assert_eq!(comparable(&s.doc().unwrap().doc), before);
|
||||
}
|
||||
// The artboards keep both editing copies, without the warning.
|
||||
for params in [json!({"format": "ai"}), json!({"format": "ai", "useArtboards": true})] {
|
||||
let r = s.execute("document.export", ¶ms).unwrap();
|
||||
let bytes = b64(&r);
|
||||
let editing = vectorcraft_pdf::editing(&bytes).expect("editing data");
|
||||
assert_eq!(vectorcraft_format::load(&editing.data).unwrap().artboards.len(), 2, "{params}");
|
||||
assert!(carries_private_data(&bytes), "{params}");
|
||||
assert!(!left_out(&r), "{params}: {r}");
|
||||
}
|
||||
assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ai_of_the_arts_bounds_without_pdf_is_refused() {
|
||||
let mut s = art_outside_the_artboards();
|
||||
let before = comparable(&s.doc().unwrap().doc);
|
||||
for extra in [json!({}), json!({"editingData": false}), json!({"editingData": true})] {
|
||||
for command in ["document.export", "document.serialize"] {
|
||||
let mut params = json!({"format": "ai", "useArtboards": false, "pdfCompatible": false});
|
||||
params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
let e = s.execute(command, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains(super::save::ART_PAGE_NEEDS_PDF), "{command} {params}: {e}");
|
||||
assert_eq!(comparable(&s.doc().unwrap().doc), before);
|
||||
}
|
||||
}
|
||||
// A document with no visible art is still refused for that.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
|
||||
let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
}
|
||||
|
||||
/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document
|
||||
/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
|
||||
/// before that opens with the radius converted, drawing the same dots; one saved since opens as
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
|
||||
use super::findfiles::{self, Limits, Visitor};
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, checked_ids_param, cmd};
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, bool_or, cmd, ids_param};
|
||||
|
||||
/// The most linked files one search looks for.
|
||||
const MAX_LINKS: usize = 1_000;
|
||||
@@ -143,8 +143,14 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = match p.get("ids") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => {
|
||||
let ids = checked_ids_param(s, p, "ids", C)?;
|
||||
let linkable = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
|
||||
// Images and placed documents in opacity-mask art and in the art of symbols, graph
|
||||
// designs and patterns are named by their ids too (`links.list`).
|
||||
let ids = ids_param(p, "ids", C)?.unwrap_or_default();
|
||||
let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind);
|
||||
if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) {
|
||||
return Err(bad(C, format!("no such object id {value}")));
|
||||
}
|
||||
let linkable = |id: &NodeId| matches!(kind(id), Some(NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
|
||||
if let Some(id) = ids.iter().find(|id| !linkable(id)) {
|
||||
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
|
||||
}
|
||||
|
||||
+145
-73
@@ -30,6 +30,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions,
|
||||
StoredPlace, StoredRoot,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
|
||||
|
||||
@@ -43,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Check Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: every linked image and placed document)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
@@ -52,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -70,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Relink",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
@@ -79,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Links",
|
||||
[],
|
||||
None,
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -88,7 +89,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Go To Link",
|
||||
[],
|
||||
None,
|
||||
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1]}",
|
||||
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)",
|
||||
has_doc,
|
||||
go_to
|
||||
),
|
||||
@@ -156,7 +157,8 @@ impl Status {
|
||||
struct Group {
|
||||
link: LinkInfo,
|
||||
key: String,
|
||||
/// The objects in the layers (images in symbols and patterns share the content, not an id).
|
||||
/// The stored objects showing it: in the layers, in opacity-mask art and in the art of symbols,
|
||||
/// graph designs and patterns ([`Document::visit_stored`]), each once.
|
||||
ids: Vec<NodeId>,
|
||||
/// Placed documents: what they show.
|
||||
document: Option<Shown>,
|
||||
@@ -177,8 +179,9 @@ fn linked(n: &Node) -> Option<(&LinkInfo, &str, Option<Shown>)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every linked file of `d` with the ids of the objects showing it (for [`crate::link_watch`]): an
|
||||
/// image placed from a DCS file has its plate files of their own too, beside its file.
|
||||
/// Every linked file of `d` with the ids of the objects showing it, wherever they are stored (for
|
||||
/// [`crate::link_watch`]): an image placed from a DCS file has its plate files of their own too,
|
||||
/// beside its file.
|
||||
pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
|
||||
let mut out = vec![];
|
||||
for g in groups(d, None).into_iter().filter(|g| !g.ids.is_empty()) {
|
||||
@@ -190,8 +193,10 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The linked images and placed documents of `d` by file and content: those in the layers (only `ids` when
|
||||
/// given), then, without `ids`, the ones only symbols and patterns show.
|
||||
/// The linked images and placed documents of `d` by file and content, wherever they are stored
|
||||
/// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object
|
||||
/// visited before it has (art being edited on a layer and its definition) counts once, by its
|
||||
/// first place; without `ids` its content is still grouped.
|
||||
fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
|
||||
let mut out: Vec<Group> = vec![];
|
||||
let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new();
|
||||
@@ -210,24 +215,48 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
|
||||
g.ids.push(id);
|
||||
}
|
||||
};
|
||||
d.walk(|n| {
|
||||
if let Some((l, key, document)) = linked(n)
|
||||
&& wanted.as_ref().is_none_or(|ids| ids.contains(&n.id))
|
||||
{
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
d.visit_stored(|n, _| {
|
||||
let Some((l, key, document)) = linked(n) else { return };
|
||||
// Id 0 names no object.
|
||||
let first = n.id.0 != 0 && seen.insert(n.id);
|
||||
if first && wanted.as_ref().is_none_or(|ids| ids.contains(&n.id)) {
|
||||
add(l, key, document, Some(n.id));
|
||||
} else if ids.is_none() {
|
||||
add(l, key, document, None);
|
||||
}
|
||||
});
|
||||
if ids.is_none() {
|
||||
d.visit_images(|_, im| {
|
||||
if let Some(l) = &im.link {
|
||||
add(l, &im.key, None, None);
|
||||
}
|
||||
});
|
||||
d.visit_placed(|_, p| add(&p.link, &p.key, Some((p.bounding, p.page_box)), None));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Stored object `id` of `d` ([`Document::stored_node`]).
|
||||
fn stored(d: &Document, id: NodeId) -> Option<&Node> {
|
||||
d.stored_node(id).map(|(n, _)| &**n)
|
||||
}
|
||||
|
||||
/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none).
|
||||
fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
ids.iter().copied().filter(|id| d.node(*id).is_none()).collect()
|
||||
}
|
||||
|
||||
/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree
|
||||
/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`.
|
||||
fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> {
|
||||
if place.in_layers() {
|
||||
return None;
|
||||
}
|
||||
let mut owner = match place.root {
|
||||
StoredRoot::Layer(_) => json!({ "kind": "layers" }),
|
||||
StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }),
|
||||
StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }),
|
||||
StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }),
|
||||
};
|
||||
if let Some(m) = place.mask_of {
|
||||
owner["maskOf"] = json!(m.0);
|
||||
}
|
||||
Some(owner)
|
||||
}
|
||||
|
||||
/// A linked file where it was found.
|
||||
struct Found {
|
||||
path: String,
|
||||
@@ -493,8 +522,8 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
|
||||
}
|
||||
|
||||
/// The linked files of the open document `st` that `links.findFiles` looks for, each with the
|
||||
/// objects in the layers that show it: the files of objects `ids` whatever their status, else the
|
||||
/// files that can't be found.
|
||||
/// stored objects that show it: the files of objects `ids` whatever their status, else the files
|
||||
/// that can't be found.
|
||||
pub(crate) fn files_to_find(st: &crate::DocState, ids: Option<&[NodeId]>) -> Vec<(LinkInfo, Vec<NodeId>)> {
|
||||
groups(&st.doc, ids)
|
||||
.into_iter()
|
||||
@@ -708,7 +737,7 @@ fn clip_to(
|
||||
type Remake<'a> = dyn FnMut(&Node, Option<(&PathData, FillRule)>) -> (Node, ClipTo) + 'a;
|
||||
|
||||
/// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and
|
||||
/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for.
|
||||
/// opacity masks, where [`Document::node`] does not find them) that `pick` holds for.
|
||||
struct Nested<'a> {
|
||||
pick: &'a dyn Fn(&Node) -> bool,
|
||||
make: &'a mut Remake<'a>,
|
||||
@@ -854,10 +883,10 @@ impl Nested<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its
|
||||
/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also`
|
||||
/// (a file's path and the content shown), so do the placed documents outside the layer tree that
|
||||
/// show that content.
|
||||
/// Placed documents `ids` (in the layers or outside them) show `src`, read from the file `link`
|
||||
/// points at, each placed as its Placement Options say (`force`: as that Preserve choice says,
|
||||
/// whatever they say); with `also` (a file's path and the content shown), so do the placed
|
||||
/// documents outside the layer tree that show that content.
|
||||
fn install_document(
|
||||
d: &mut Document,
|
||||
ids: &[NodeId],
|
||||
@@ -872,8 +901,10 @@ fn install_document(
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement };
|
||||
placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o)
|
||||
};
|
||||
if let Some(also) = also {
|
||||
let pick = |n: &Node| shows(n, also, true);
|
||||
let nested = nested_ids(d, ids);
|
||||
if also.is_some() || !nested.is_empty() {
|
||||
let pick =
|
||||
|n: &Node| matches!(n.kind, NodeKind::PlacedDocument(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, true)));
|
||||
let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
@@ -1037,26 +1068,39 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement
|
||||
/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's
|
||||
/// path and the content shown), so do the images outside the layer tree that show that content.
|
||||
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
|
||||
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
|
||||
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
|
||||
/// show that content.
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
let new_pt = super::place::pt_per_px(img.ppi);
|
||||
let mut clips = vec![];
|
||||
if let Some(also) = also {
|
||||
// Every image picked shows content `also.1`, so one resolution serves them all.
|
||||
let old_pt = file_pt(d, also.1);
|
||||
let pick = |n: &Node| shows(n, also, false);
|
||||
// The clipping path the old content's DCS file drew it through.
|
||||
let old_clip = d.images.get(also.1).and_then(ImageBlob::separated_clip);
|
||||
let nested = nested_ids(d, ids);
|
||||
if also.is_some() || !nested.is_empty() {
|
||||
let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false)));
|
||||
// The resolution of each content the images picked show, and the clipping path its DCS file
|
||||
// drew it through, looked up once each.
|
||||
let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new();
|
||||
d.visit_stored(|n, _| {
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& pick(n)
|
||||
&& !old.contains_key(&im.key)
|
||||
{
|
||||
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip)));
|
||||
}
|
||||
});
|
||||
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = ClipTo::Keep;
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
let (old_pt, old_clip) = match old.get(&im.key) {
|
||||
Some((pt, clip)) => (*pt, clip.as_ref()),
|
||||
None => (super::place::pt_per_px(None), None),
|
||||
};
|
||||
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
|
||||
clip = clip_to(im.xf, old_clip.as_ref(), c, &img, xf, held);
|
||||
clip = clip_to(im.xf, old_clip, c, &img, xf, held);
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
}
|
||||
(n, clip)
|
||||
@@ -1267,7 +1311,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps
|
||||
}
|
||||
}
|
||||
// The objects in symbols, graph designs, patterns and opacity masks that show the same file and
|
||||
// content, which have no ids here, whatever else their links hold.
|
||||
// content, whatever else their links hold, those whose id an earlier object has included.
|
||||
if !moved.is_empty() {
|
||||
let mut by_path: BTreeMap<String, Vec<(String, bool, LinkInfo)>> = BTreeMap::new();
|
||||
for (path, key, document, new) in moved {
|
||||
@@ -1302,13 +1346,25 @@ fn link_mut(n: &mut Node) -> Option<&mut LinkInfo> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked image objects (or placed documents) `ids` link to `link`.
|
||||
/// Linked image objects (or placed documents) `ids`, in the layers or outside them, link to `link`.
|
||||
fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
|
||||
for id in ids {
|
||||
let nested = nested_ids(d, ids);
|
||||
for id in ids.iter().filter(|id| !nested.contains(id)) {
|
||||
if let Some(l) = d.node_mut(*id).and_then(link_mut) {
|
||||
*l = link.clone();
|
||||
}
|
||||
}
|
||||
if !nested.is_empty() {
|
||||
let pick = |n: &Node| nested.contains(&n.id) && linked(n).is_some();
|
||||
let mut make = |n: &Node, _: Option<(&PathData, FillRule)>| {
|
||||
let mut out = n.clone();
|
||||
if let Some(l) = link_mut(&mut out) {
|
||||
*l = link.clone();
|
||||
}
|
||||
(out, ClipTo::Keep)
|
||||
};
|
||||
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
|
||||
@@ -1331,14 +1387,17 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
|
||||
if targets.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Each document is updated as the active one, without switching tools.
|
||||
// Each document is updated as the active one, through its own profiles, without switching
|
||||
// tools.
|
||||
let back = s.active;
|
||||
for i in targets {
|
||||
s.active = Some(i);
|
||||
s.sync_front_profiles();
|
||||
// A file that can't be read leaves what its objects show: links.check reports it.
|
||||
let _ = update_where(s, None, Some(&path));
|
||||
}
|
||||
s.active = back;
|
||||
s.sync_front_profiles();
|
||||
}
|
||||
|
||||
// ---------- relative paths ----------
|
||||
@@ -1537,7 +1596,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Update Links in the active document of `s` for objects `ids` (default: the linked files that
|
||||
/// changed or show their preview), or with `path`, for the placed documents of the file at `path`
|
||||
/// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that
|
||||
/// show the same content are read again too, and have no ids to report.
|
||||
/// show the same content are read again too.
|
||||
fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let (mut reads, mut missing) = (vec![], vec![]);
|
||||
@@ -1603,7 +1662,7 @@ enum Scope {
|
||||
Each,
|
||||
/// The objects given or selected.
|
||||
Selected,
|
||||
/// Every object in the layers linked to the same file as one given or selected.
|
||||
/// Every stored object linked to the same file as one given or selected.
|
||||
All,
|
||||
/// The objects given or selected, then every other missing link whose file name is in the new
|
||||
/// file's folder.
|
||||
@@ -1687,7 +1746,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// An image or a placed document, with its link.
|
||||
let image = |id: &NodeId| {
|
||||
st.doc.node(*id).and_then(|n| match &n.kind {
|
||||
stored(&st.doc, *id).and_then(|n| match &n.kind {
|
||||
NodeKind::Image(im) => Some(im.link.as_ref()),
|
||||
NodeKind::PlacedDocument(p) => Some(Some(&p.link)),
|
||||
_ => None,
|
||||
@@ -1712,22 +1771,23 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the images to relink, or pass ids"));
|
||||
}
|
||||
// All Instances: the other objects in the layers linked to the same files.
|
||||
// All Instances: the other stored objects linked to the same files, each once.
|
||||
if scope == Scope::All {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
let given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut more = vec![];
|
||||
st.doc.walk(|n| {
|
||||
st.doc.visit_stored(|n, _| {
|
||||
if let Some((l, _, _)) = linked(n)
|
||||
&& paths.contains(l.path.as_str())
|
||||
&& !given.contains(&n.id)
|
||||
&& n.id.0 != 0
|
||||
&& given.insert(n.id)
|
||||
{
|
||||
more.push(n.id);
|
||||
}
|
||||
});
|
||||
ids.extend(more);
|
||||
}
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
return Err(bad(C, "copy takes images only: relink placed documents where their files are"));
|
||||
}
|
||||
// (ids, the file) per file to read.
|
||||
@@ -1763,7 +1823,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut images = vec![];
|
||||
let mut documents: Vec<((u32, bool, PageBox), Vec<NodeId>)> = vec![];
|
||||
for id in ids {
|
||||
match st.doc.node(id).map(|n| &n.kind) {
|
||||
match stored(&st.doc, id).map(|n| &n.kind) {
|
||||
Some(NodeKind::PlacedDocument(pl)) => {
|
||||
let k = (pl.page(), pl.bounding, pl.page_box);
|
||||
match documents.iter_mut().find(|(e, _)| *e == k) {
|
||||
@@ -1913,9 +1973,9 @@ fn copy_into_folder(_: &str, _: &[u8], _: &Path) -> Result<(String, bool)> {
|
||||
|
||||
// ---------- the Links panel ----------
|
||||
|
||||
/// Image object `id` of `d`.
|
||||
/// Image object `id` of `d`, wherever it is stored.
|
||||
fn image_of(d: &Document, id: NodeId) -> Option<&ImageObject> {
|
||||
match &d.node(id)?.kind {
|
||||
match &stored(d, id)?.kind {
|
||||
NodeKind::Image(im) => Some(im),
|
||||
_ => None,
|
||||
}
|
||||
@@ -1933,7 +1993,7 @@ fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
.ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match image_of(&st.doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None => Err(bad(cmd, format!("object {} is not an image", id.0))),
|
||||
}
|
||||
}
|
||||
@@ -1947,9 +2007,9 @@ fn placement_mut(n: &mut Node) -> Option<&mut PlacementOptions> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Placement Options of image or placed document `id` of `d`.
|
||||
/// The Placement Options of image or placed document `id` of `d`, wherever it is stored.
|
||||
fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
|
||||
match &d.node(id)?.kind {
|
||||
match &stored(d, id)?.kind {
|
||||
NodeKind::Image(im) => Some(im.placement),
|
||||
NodeKind::PlacedDocument(p) => Some(p.placement),
|
||||
_ => None,
|
||||
@@ -1962,12 +2022,12 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match placement_of(&st.doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Per linked image in the layers of `st`: its file's status, where it was found when away from
|
||||
/// Per linked image or placed document of `st`, wherever it is stored: its file's status, where it was found when away from
|
||||
/// its path, and whether the image shows its preview (each file probed once).
|
||||
pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
|
||||
let mut out = BTreeMap::new();
|
||||
@@ -2068,17 +2128,20 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() };
|
||||
let statuses = statuses(st);
|
||||
let mut objects = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) {
|
||||
objects.push(n);
|
||||
// The layer tree's objects, top first as the Layers panel lists them, then the others in the
|
||||
// order they are stored (opacity-mask art, symbols, graph designs, patterns), each once.
|
||||
let (mut objects, mut nested) = (vec![], vec![]);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
st.doc.visit_stored(|n, place| {
|
||||
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) {
|
||||
if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) }
|
||||
}
|
||||
});
|
||||
// Top first, as the Layers panel lists them.
|
||||
objects.reverse();
|
||||
objects.extend(nested);
|
||||
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
|
||||
let mut rows = vec![];
|
||||
for n in objects {
|
||||
for (n, place) in objects {
|
||||
let (status, found, preview) = match statuses.get(&n.id) {
|
||||
Some((s, f, p)) => (s.as_str(), f.as_deref(), *p),
|
||||
None => ("embedded", None, false),
|
||||
@@ -2121,6 +2184,9 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if preview {
|
||||
row["preview"] = json!(true);
|
||||
}
|
||||
if let Some(owner) = owner_json(&st.doc, place) {
|
||||
row["owner"] = owner;
|
||||
}
|
||||
if interactions.contains(&n.id) {
|
||||
row["dcsTransparency"] = json!(true);
|
||||
}
|
||||
@@ -2141,15 +2207,21 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let id = linked_param(st, p, "links.goTo")?;
|
||||
// An object in mask art or a definition has no place of its own on the canvas: the selection
|
||||
// is cleared, and the reply names what holds it.
|
||||
if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) {
|
||||
s.select(|_, sel| sel.set([]))?;
|
||||
return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner }));
|
||||
}
|
||||
let b = st.doc.node(id).and_then(Node::geometric_bounds).unwrap_or_default();
|
||||
s.select(|_, sel| sel.set([id]))?;
|
||||
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1] }))
|
||||
Ok(json!({ "id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1], "onCanvas": true }))
|
||||
}
|
||||
|
||||
fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.embed";
|
||||
let st = s.doc()?;
|
||||
let kind = |id: &NodeId| st.doc.node(*id).map(|n| &n.kind);
|
||||
let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind);
|
||||
let linked = |id: &NodeId| match kind(id) {
|
||||
Some(NodeKind::Image(im)) => im.link.is_some(),
|
||||
Some(NodeKind::PlacedDocument(_)) => true,
|
||||
@@ -2207,7 +2279,7 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
install(d, &ids, read, Some(Preserve::Bounds), None)?;
|
||||
}
|
||||
for id in &done {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) {
|
||||
im.link = None;
|
||||
}
|
||||
}
|
||||
@@ -2235,7 +2307,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let st = s.doc()?;
|
||||
let id = image_param(st, p, C)?;
|
||||
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
|
||||
if im.link.is_some() {
|
||||
return Err(bad(C, format!("image {} is linked already", id.0)));
|
||||
@@ -2321,7 +2393,7 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) {
|
||||
|
||||
/// Link Info of placed document `id`.
|
||||
fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
|
||||
let n = st.doc.node(id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
|
||||
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
|
||||
@@ -2401,7 +2473,7 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
s.edit("Placement Options", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(o) = d.node_mut(*id).and_then(placement_mut) {
|
||||
if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) {
|
||||
set(o);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 +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
|
||||
),
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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())) {
|
||||
|
||||
+216
-11
@@ -481,6 +481,12 @@ fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Anchors that [`merge_coincident`] moved to a lower index of their vector on this thread.
|
||||
static ANCHOR_MOVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which
|
||||
/// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many
|
||||
/// anchors went.
|
||||
@@ -501,23 +507,68 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
|
||||
join_point(sp, 0, smooth);
|
||||
}
|
||||
}
|
||||
// Back to front, so the indices `picked` knows stay true for the anchors still to visit.
|
||||
for i in (1..sp.anchors.len()).rev() {
|
||||
// Back to front, so the indices `picked` knows stay true for the anchors still to visit. A
|
||||
// merged anchor is only marked here; the marked anchors are removed in one pass at the end.
|
||||
let closed = sp.closed;
|
||||
let anchors = &mut sp.anchors;
|
||||
let len = anchors.len();
|
||||
let mut gone = vec![false; len];
|
||||
// The anchor after `i` that is still on the path, and the last one still on it.
|
||||
let mut next = None;
|
||||
let mut last = len.saturating_sub(1);
|
||||
for i in (1..len).rev() {
|
||||
if picked(i - 1)
|
||||
&& picked(i)
|
||||
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
|
||||
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
|
||||
&& same(a, b)
|
||||
{
|
||||
a.h_out = b.h_out;
|
||||
sp.anchors.remove(i);
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, i - 1, smooth);
|
||||
if let Some(slot) = gone.get_mut(i) {
|
||||
*slot = true;
|
||||
}
|
||||
if next.is_none() {
|
||||
last = i - 1;
|
||||
}
|
||||
if let Some(smooth) = join_kind {
|
||||
// The neighbors the anchor has on the path as it now stands, as `join_point` sees them.
|
||||
let prev = if i > 1 { Some(i - 2) } else { closed.then_some(last) };
|
||||
let after = next.or(closed.then_some(0));
|
||||
join_point_between(anchors, i - 1, prev, after, smooth);
|
||||
}
|
||||
} else {
|
||||
next = Some(i);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(first) = gone.iter().position(|&g| g) {
|
||||
// `retain` moves each anchor it keeps after the first one it drops.
|
||||
let dropped = gone.iter().filter(|&&g| g).count();
|
||||
ANCHOR_MOVES.set(ANCHOR_MOVES.get() + (len - first - dropped));
|
||||
}
|
||||
if gone.contains(&true) {
|
||||
let mut k = 0;
|
||||
anchors.retain(|_| {
|
||||
let keep = !gone.get(k).copied().unwrap_or(false);
|
||||
k += 1;
|
||||
keep
|
||||
});
|
||||
}
|
||||
before - sp.anchors.len()
|
||||
}
|
||||
|
||||
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
|
||||
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
|
||||
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
|
||||
let (prev, next) = (at(prev), at(next));
|
||||
if let Some(a) = anchors.get_mut(ai) {
|
||||
if smooth {
|
||||
a.smooth_between(prev, next);
|
||||
} else {
|
||||
a.retract();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Close subpath `si` of path `id`, merging coincident endpoints if present.
|
||||
fn close_subpath_in_node(d: &mut Document, id: NodeId, si: usize, join_kind: Option<bool>) -> Result<()> {
|
||||
let path = path_mut(d, id)?;
|
||||
@@ -751,8 +802,19 @@ pub(super) fn join(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut merged = vec![];
|
||||
for (id, picked) in &st.selection.anchors {
|
||||
let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue };
|
||||
let n: usize =
|
||||
path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum();
|
||||
// One flag per anchor; references past the end of a subpath or to a missing one pick nothing.
|
||||
let mut masks: Vec<Vec<bool>> = path.subpaths.iter().map(|sp| vec![false; sp.anchors.len()]).collect();
|
||||
for &(si, ai) in picked {
|
||||
if let Some(flag) = masks.get_mut(si).and_then(|m| m.get_mut(ai)) {
|
||||
*flag = true;
|
||||
}
|
||||
}
|
||||
let n: usize = path
|
||||
.subpaths
|
||||
.iter_mut()
|
||||
.zip(&masks)
|
||||
.map(|(sp, mask)| merge_coincident(sp, |ai| mask.get(ai).copied().unwrap_or(false), join_kind))
|
||||
.sum();
|
||||
if n > 0 {
|
||||
merged.push((*id, path));
|
||||
}
|
||||
@@ -1276,7 +1338,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(si, sp)| {
|
||||
let cuts = refs.iter().filter_map(|&(s, seg)| (s == si).then_some(seg)).collect();
|
||||
let cuts = subpath_refs(refs, si).collect();
|
||||
without_segments(sp, &cuts)
|
||||
})
|
||||
.filter(|s| s.anchors.len() >= 2)
|
||||
@@ -1288,7 +1350,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(si, sp)| {
|
||||
let gone = set.iter().filter_map(|&(s, ai)| (s == si).then_some(ai)).collect();
|
||||
let gone = subpath_refs(set, si).collect();
|
||||
without_anchors(sp, &gone)
|
||||
})
|
||||
.filter(|s| s.anchors.len() >= 2)
|
||||
@@ -1314,6 +1376,12 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The anchor or segment indexes in `refs` that belong to subpath `si`, in index order.
|
||||
/// `refs` is ordered by subpath first, so this reads only that subpath's entries.
|
||||
pub(super) fn subpath_refs(refs: &BTreeSet<(usize, usize)>, si: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
refs.range((si, 0)..=(si, usize::MAX)).map(|&(_, i)| i)
|
||||
}
|
||||
|
||||
/// Retain path `id` from `d` without copying its geometry before deletion takes its subpaths.
|
||||
/// The shared snapshot supplies the original path classification and, only if needed, gradient
|
||||
/// bounds after the working node's geometry has moved. Returns `NoNode` for a missing/non-path ID.
|
||||
@@ -1722,7 +1790,7 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { continue };
|
||||
let (mut subs, mut starts) = (vec![], vec![]);
|
||||
for (si, sp) in pd.subpaths.iter().enumerate() {
|
||||
let at: BTreeSet<usize> = set.iter().filter(|(s, _)| *s == si).map(|(_, a)| *a).collect();
|
||||
let at: BTreeSet<usize> = subpath_refs(set, si).collect();
|
||||
let pieces = sp.cut_at(&at);
|
||||
// The pieces that start at a cut: every piece of an opened closed subpath, all but the
|
||||
// first of an open one.
|
||||
@@ -1763,3 +1831,140 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(super::draw2::ids_json(&ids))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `merge_coincident` removing each merged anchor from the vector straight away, kept as the
|
||||
/// reference the one-pass version must match.
|
||||
fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize {
|
||||
let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6;
|
||||
let before = sp.anchors.len();
|
||||
if sp.closed
|
||||
&& before > 2
|
||||
&& picked(0)
|
||||
&& picked(before - 1)
|
||||
&& let [first, .., last] = sp.anchors.as_mut_slice()
|
||||
&& same(first, last)
|
||||
{
|
||||
first.h_in = last.h_in;
|
||||
sp.anchors.pop();
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, 0, smooth);
|
||||
}
|
||||
}
|
||||
for i in (1..sp.anchors.len()).rev() {
|
||||
if picked(i - 1)
|
||||
&& picked(i)
|
||||
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
|
||||
&& same(a, b)
|
||||
{
|
||||
a.h_out = b.h_out;
|
||||
sp.anchors.remove(i);
|
||||
if let Some(smooth) = join_kind {
|
||||
join_point(sp, i - 1, smooth);
|
||||
}
|
||||
}
|
||||
}
|
||||
before - sp.anchors.len()
|
||||
}
|
||||
|
||||
/// Every field of every anchor, bit for bit.
|
||||
fn bits(sp: &SubPath) -> (Vec<[u64; 6]>, Vec<AnchorKind>, bool) {
|
||||
let b = |p: Point| [p.x.to_bits(), p.y.to_bits()];
|
||||
let fields = sp.anchors.iter().map(|a| [b(a.p), b(a.h_in), b(a.h_out)].concat().try_into().unwrap()).collect();
|
||||
(fields, sp.anchors.iter().map(|a| a.kind).collect(), sp.closed)
|
||||
}
|
||||
|
||||
/// A small linear congruential generator, so the cases are the same on every run.
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) % n
|
||||
}
|
||||
}
|
||||
|
||||
fn same_as_removal(sp: &SubPath, picked: &dyn Fn(usize) -> bool, join_kind: Option<bool>) {
|
||||
let (mut ours, mut theirs) = (sp.clone(), sp.clone());
|
||||
let n = merge_coincident(&mut ours, picked, join_kind);
|
||||
let m = merge_coincident_by_removal(&mut theirs, picked, join_kind);
|
||||
assert_eq!(n, m, "{sp:?} {join_kind:?}");
|
||||
assert_eq!(bits(&ours), bits(&theirs), "{sp:?} {join_kind:?}");
|
||||
}
|
||||
|
||||
/// Short paths with points on, near and just past the merge distance, selections with stale
|
||||
/// indices, every anchor kind and every join kind give the same anchors, bit for bit, as
|
||||
/// removing each merged anchor straight away.
|
||||
#[test]
|
||||
fn merging_coincident_anchors_matches_removing_them_one_by_one() {
|
||||
let spots = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (5e-7, 0.0), (0.0, 1.5e-6), (10.0, 0.0), (5.0, 5.0), (10.0, 0.0)];
|
||||
let mut rng = Lcg(7);
|
||||
for _ in 0..30_000 {
|
||||
let n = rng.below(9) as usize;
|
||||
let anchors = (0..n)
|
||||
.map(|_| {
|
||||
let (x, y) = spots[rng.below(spots.len() as u64) as usize];
|
||||
let p = Point::new(x, y);
|
||||
let handle = |rng: &mut Lcg| match rng.below(3) {
|
||||
0 => p,
|
||||
_ => p + Vec2::new(rng.below(7) as f64 - 3.0, rng.below(7) as f64 - 3.0),
|
||||
};
|
||||
let (h_in, h_out) = (handle(&mut rng), handle(&mut rng));
|
||||
let kind = if rng.below(2) == 0 { AnchorKind::Corner } else { AnchorKind::Smooth };
|
||||
Anchor { p, h_in, h_out, kind }
|
||||
})
|
||||
.collect();
|
||||
let sp = SubPath::new(anchors, rng.below(2) == 0);
|
||||
let picks: Vec<bool> = (0..n + 2).map(|_| rng.below(4) != 0).collect();
|
||||
let join_kind = [None, Some(false), Some(true)][rng.below(3) as usize];
|
||||
same_as_removal(&sp, &|i| picks.get(i).copied().unwrap_or(false), join_kind);
|
||||
}
|
||||
}
|
||||
|
||||
/// A smooth join of three anchors on one another takes the outgoing handle the middle anchor
|
||||
/// was given when it joined the right one: an already smooth left anchor keeps that handle.
|
||||
#[test]
|
||||
fn a_smooth_join_of_three_anchors_keeps_the_handle_the_middle_one_got() {
|
||||
let o = Point::ZERO;
|
||||
let left = Anchor { p: o, h_in: Point::new(-2.0, 0.0), h_out: o, kind: AnchorKind::Smooth };
|
||||
let right = Anchor { p: o, h_in: o, h_out: Point::new(0.0, 5.0), kind: AnchorKind::Corner };
|
||||
let mut sp = SubPath::new(vec![left, Anchor::corner(o), right, Anchor::corner(Point::new(10.0, 0.0))], false);
|
||||
assert_eq!(merge_coincident(&mut sp, |i| i < 3, Some(true)), 2);
|
||||
let a = sp.anchors[0];
|
||||
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(-2.0, 0.0), Point::new(10.0 / 3.0, 0.0), AnchorKind::Smooth));
|
||||
assert_eq!(sp.anchors.len(), 2);
|
||||
}
|
||||
|
||||
/// One long run of selected anchors on one another, open or closed, becomes one anchor.
|
||||
#[test]
|
||||
fn a_long_run_of_anchors_on_one_another_becomes_one() {
|
||||
for closed in [false, true] {
|
||||
for join_kind in [None, Some(false), Some(true)] {
|
||||
let anchors = (0..50_000).map(|i| Anchor::smooth(Point::ZERO, Point::new(1.0, i as f64))).collect();
|
||||
let sp = SubPath::new(anchors, closed);
|
||||
same_as_removal(&sp, &|_| true, join_kind);
|
||||
let mut ours = sp.clone();
|
||||
assert_eq!(merge_coincident(&mut ours, |_| true, join_kind), 49_999);
|
||||
assert_eq!((ours.anchors.len(), ours.closed), (1, closed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A long selected run at the start of a path followed by as many anchors that stay: each
|
||||
/// anchor after the run moves once, not once per merged anchor.
|
||||
#[test]
|
||||
fn a_long_run_before_many_other_anchors_merges_in_one_pass() {
|
||||
let run = 300_000;
|
||||
let anchors = (0..run).map(|_| Anchor::corner(Point::ZERO)).chain((1..=run).map(|i| Anchor::corner(Point::new(i as f64, 1.0)))).collect();
|
||||
let mut sp = SubPath::new(anchors, false);
|
||||
ANCHOR_MOVES.set(0);
|
||||
assert_eq!(merge_coincident(&mut sp, |i| i < run, Some(false)), run - 1);
|
||||
assert_eq!(ANCHOR_MOVES.get(), run);
|
||||
assert_eq!(sp.anchors.len(), run + 1);
|
||||
assert_eq!(sp.anchors[0].p, Point::ZERO);
|
||||
assert_eq!(sp.anchors[1].p, Point::new(1.0, 1.0));
|
||||
assert_eq!(sp.anchors[run].p, Point::new(run as f64, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -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, ¶ms);
|
||||
@@ -944,7 +962,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, [id]) => *id,
|
||||
_ => return Err(bad(C, "select one image or pass id")),
|
||||
};
|
||||
let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
// An image in opacity-mask art or a definition's art is found by its id too (`links.list`).
|
||||
let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
|
||||
let [a, b, c, d, ..] = im.xf.as_coeffs();
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::unique_name;
|
||||
|
||||
@@ -118,11 +118,12 @@ impl Used {
|
||||
type Renames = BTreeMap<String, (Option<String>, bool)>;
|
||||
|
||||
/// Names in `dst` for the `used` definitions of `src` (`def`): the same name when `dst` has none
|
||||
/// (copied) or an equal one (shared), else a free variant (`taken`, copied).
|
||||
fn names<T: PartialEq>(
|
||||
/// (copied) or one that is the `same` (shared), else a free variant (`taken`, copied).
|
||||
fn names<T>(
|
||||
used: &[String],
|
||||
def: impl Fn(&str) -> Option<T>,
|
||||
existing: impl Fn(&str) -> Option<T>,
|
||||
same: impl Fn(&T, &T) -> bool,
|
||||
taken: impl Fn(&str) -> bool,
|
||||
) -> Renames {
|
||||
let mut out = Renames::new();
|
||||
@@ -130,7 +131,7 @@ fn names<T: PartialEq>(
|
||||
let Some(d) = def(name) else { continue };
|
||||
let entry = match existing(name) {
|
||||
None => (Some(name.clone()), true),
|
||||
Some(e) if e == d => (Some(name.clone()), false),
|
||||
Some(e) if same(&e, &d) => (Some(name.clone()), false),
|
||||
Some(_) => {
|
||||
(Some(unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || out.values().any(|(n, _)| n.as_deref() == Some(c)))), true)
|
||||
}
|
||||
@@ -140,6 +141,65 @@ fn names<T: PartialEq>(
|
||||
out
|
||||
}
|
||||
|
||||
/// `n` as `dst` would copy it in ([`Document::reid`]), with the ids a document of its own gives it:
|
||||
/// art copied in once, which differs from the file's only in its ids, compares equal to the file's.
|
||||
fn canon(dst: &Document, n: &Node) -> Node {
|
||||
let mut own = Document::new(0.0, 0.0);
|
||||
// Pixels the art carries take a key `dst` doesn't use for other pixels, as they do in `dst`.
|
||||
let mut keys = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind
|
||||
&& im.pixels.is_some()
|
||||
{
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
});
|
||||
for (k, blob) in &dst.images {
|
||||
if keys.iter().any(|key| k == key || k.strip_prefix(key.as_str()).is_some_and(|rest| rest.starts_with('-'))) {
|
||||
own.images.insert(k.clone(), blob.clone());
|
||||
}
|
||||
}
|
||||
own.reid(n)
|
||||
}
|
||||
|
||||
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
fn same_symbol(dst: &Document, a: &Symbol, b: &Symbol) -> bool {
|
||||
let own = |s: &Symbol| Symbol { art: Arc::new(canon(dst, &s.art)), ..s.clone() };
|
||||
own(a) == own(b)
|
||||
}
|
||||
|
||||
/// Do patterns `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
fn same_pattern(dst: &Document, a: &PatternDef, b: &PatternDef) -> bool {
|
||||
let bare = |p: &PatternDef| PatternDef { art: vec![], ..p.clone() };
|
||||
bare(a) == bare(b) && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| canon(dst, x) == canon(dst, y))
|
||||
}
|
||||
|
||||
/// Does art `a` use a resource that `m` (images, symbols, patterns, brushes, swatches) gives
|
||||
/// another name, or a swatch whose link `m` drops?
|
||||
fn uses_moved(a: &Node, m: [&Renames; 5]) -> bool {
|
||||
let moved = |map: &Renames, k: &str| map.get(k).is_some_and(|(new, _)| new.as_deref() != Some(k));
|
||||
let (mut a, mut any) = (a.clone(), false);
|
||||
refs(&mut a, &mut |r| {
|
||||
any |= match r {
|
||||
Ref::Image(k) => moved(m[0], k),
|
||||
Ref::Symbol(k) => moved(m[1], k),
|
||||
Ref::Pattern(k) => moved(m[2], k),
|
||||
Ref::Brush(k) => moved(m[3], k),
|
||||
Ref::Swatch(link) => link.as_deref().is_some_and(|k| moved(m[4], k)),
|
||||
}
|
||||
});
|
||||
any
|
||||
}
|
||||
|
||||
/// Copy each of `shared` in `map` under a free name, as [`names`] does for a definition `dst`
|
||||
/// holds differently.
|
||||
fn unshare(map: &mut Renames, shared: &[String], used: &[String], taken: impl Fn(&str) -> bool) {
|
||||
for name in shared {
|
||||
let free = unique_name(name, |c| taken(c) || used.iter().any(|u| u == c) || map.values().any(|(n, _)| n.as_deref() == Some(c)));
|
||||
map.insert(name.clone(), (Some(free), true));
|
||||
}
|
||||
}
|
||||
|
||||
/// The renamed resources whose definitions are copied: (name in `src`, name in `dst`).
|
||||
fn copies(m: &Renames) -> Vec<(&str, &str)> {
|
||||
m.iter().filter(|(_, (_, copy))| *copy).filter_map(|(old, (new, _))| Some((old.as_str(), new.as_deref()?))).collect()
|
||||
@@ -194,14 +254,17 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
}
|
||||
}
|
||||
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |c| dst.images.contains_key(c));
|
||||
let symbols = names(
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
|
||||
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
|
||||
// draws: placing the same file again shares what the first placement brought.
|
||||
let mut symbols = names(
|
||||
&used.symbols,
|
||||
|n| src.symbols.iter().find(|s| s.name == n),
|
||||
|n| dst.symbols.iter().find(|s| s.name == n),
|
||||
|a, b| same_symbol(dst, a, b),
|
||||
|c| dst.symbols.iter().any(|s| s.name == c),
|
||||
);
|
||||
let patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |c| dst.pattern(c).is_some());
|
||||
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
|
||||
// A swatch the document defines differently isn't renamed (that would add look-alike swatches):
|
||||
// the colours linked to it keep their look, unlinked.
|
||||
let swatches: Renames = used
|
||||
@@ -236,12 +299,33 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
any
|
||||
};
|
||||
let mut dst_brushes = vectorcraft_brush::library(dst);
|
||||
let brushes = names(
|
||||
let mut brushes = names(
|
||||
&used.brushes,
|
||||
|n| src_brushes.iter().find(|b| b.name == n).map(|b| (b, moves_art(b))),
|
||||
|n| dst_brushes.iter().find(|b| b.name == n).map(|b| (b, false)),
|
||||
|a, b| a == b,
|
||||
|c| dst_brushes.iter().any(|b| b.name == c),
|
||||
);
|
||||
// Likewise a symbol, pattern or brush whose art uses a resource that moves isn't the
|
||||
// document's of that name: it is copied under a free name, which can move what uses it in turn.
|
||||
loop {
|
||||
let maps = [&images, &symbols, &patterns, &brushes, &swatches];
|
||||
let shared = |map: &Renames| map.iter().filter(|(_, (_, copy))| !*copy).map(|(k, _)| k.clone()).collect::<Vec<_>>();
|
||||
let sym: Vec<String> =
|
||||
shared(&symbols).into_iter().filter(|n| src.symbols.iter().any(|s| s.name == *n && uses_moved(&s.art, maps))).collect();
|
||||
let pat: Vec<String> =
|
||||
shared(&patterns).into_iter().filter(|n| src.pattern(n).is_some_and(|p| p.art.iter().any(|a| uses_moved(a, maps)))).collect();
|
||||
let bru: Vec<String> = shared(&brushes)
|
||||
.into_iter()
|
||||
.filter(|n| src_brushes.iter().find(|b| b.name == *n).is_some_and(|b| brush_art(&mut b.clone()).into_iter().any(|a| uses_moved(a, maps))))
|
||||
.collect();
|
||||
if sym.is_empty() && pat.is_empty() && bru.is_empty() {
|
||||
break;
|
||||
}
|
||||
unshare(&mut symbols, &sym, &used.symbols, |c| dst.symbols.iter().any(|s| s.name == c));
|
||||
unshare(&mut patterns, &pat, &used.patterns, |c| dst.pattern(c).is_some());
|
||||
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
|
||||
}
|
||||
|
||||
let mut rename = |r: Ref| {
|
||||
let (map, k) = match r {
|
||||
@@ -272,6 +356,8 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
|
||||
def.name = new.to_string();
|
||||
refs(Arc::make_mut(&mut def.art), &mut rename);
|
||||
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
|
||||
def.art = Arc::new(dst.reid(&def.art));
|
||||
dst.symbols.push(def);
|
||||
}
|
||||
}
|
||||
@@ -280,6 +366,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
def.name = new.to_string();
|
||||
for a in &mut def.art {
|
||||
refs(Arc::make_mut(a), &mut rename);
|
||||
*a = Arc::new(dst.reid(a));
|
||||
}
|
||||
dst.patterns.push(def);
|
||||
}
|
||||
|
||||
@@ -378,8 +378,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
|
||||
/// Placed document `id` of `d` replaced by an editable copy of its art, as placing its file
|
||||
/// without Link gives (its resources joining `d`, renamed where `d` uses a name for something
|
||||
/// else), keeping the object's id, place, name and transparency: Break Link and Object › Expand.
|
||||
/// A placed document in opacity-mask art or in the art of a symbol, graph design or pattern is
|
||||
/// replaced where it is stored.
|
||||
pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let n = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let n = d.stored_node(id).map(|(n, _)| Node::clone(n)).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::PlacedDocument(p) = &n.kind else { return Err(bad(cmd, format!("object {} is not a placed document", id.0))) };
|
||||
let blob = d.images.get(&p.key).ok_or_else(|| bad(cmd, format!("object {} has lost its file's contents: relink it", id.0)))?;
|
||||
let bytes = vectorcraft_doc::placed_document::full_bytes(p, blob)
|
||||
@@ -395,6 +397,10 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let art = super::transformed(Node::new(d.alloc_id(), NodeKind::Group { children, clip: a.clip.is_some() }), m);
|
||||
let mut out = n.clone();
|
||||
out.kind = art.kind;
|
||||
if d.node(id).is_none() {
|
||||
*d.stored_node_mut(id).ok_or(EngineError::NoNode(id))? = out;
|
||||
return Ok(());
|
||||
}
|
||||
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
d.remove(id)?;
|
||||
d.insert(par, index, out)?;
|
||||
|
||||
@@ -413,6 +413,7 @@ pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
|
||||
st.interaction = None;
|
||||
}
|
||||
saved.restore(s);
|
||||
s.sync_front_profiles();
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -454,10 +454,10 @@ pub fn spec(key: &str) -> Option<&'static PrefSpec> {
|
||||
/// Preferences kept as one object with a command of their own instead of [`PREF_SPECS`] rows (they
|
||||
/// aren't in the Preferences dialog): the Eyedropper Options (`eyedropper.setOptions`), the
|
||||
/// Perspective Grid Options (`perspective.widget.options`), the Pathfinder Options
|
||||
/// (`object.pathfinder.options`) and the Snap to Glyph options (`view.snapToGlyph.options`).
|
||||
/// `prefs.get` and `prefs.set` take them by key (a partial object updates what it names) and
|
||||
/// `prefs.reset` without a category resets them.
|
||||
pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap"];
|
||||
/// (`object.pathfinder.options`), the Snap to Glyph options (`view.snapToGlyph.options`) and the
|
||||
/// Pixel Snapping Options (`view.snapToPixel.options`). `prefs.get` and `prefs.set` take them by key
|
||||
/// (a partial object updates what it names) and `prefs.reset` without a category resets them.
|
||||
pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder", "glyphSnap", "pixelSnap"];
|
||||
|
||||
/// Validate a value for preference group `key` against `current`.
|
||||
fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<Value, String> {
|
||||
@@ -477,6 +477,10 @@ fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<
|
||||
let cur: vectorcraft_tools::GlyphSnap = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
cur.merged(v).map(|o| json!(o))
|
||||
}
|
||||
"pixelSnap" => {
|
||||
let cur: vectorcraft_tools::PixelSnap = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
cur.merged(v).map(|o| json!(o))
|
||||
}
|
||||
"perspectiveWidget" => {
|
||||
let mut merged = current.clone();
|
||||
if let (Some(o), Some(p)) = (merged.as_object_mut(), v.as_object()) {
|
||||
@@ -788,7 +792,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Preferences",
|
||||
[],
|
||||
None,
|
||||
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder and glyphSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
|
||||
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
|
||||
always,
|
||||
export
|
||||
),
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! View → New View… / Edit Views…: saved views stored in the document; per-document view
|
||||
//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options.
|
||||
//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options; the Pixel
|
||||
//! Snapping Options.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_apischema::{Bound, Param, ParamSchema, Type, Writes};
|
||||
@@ -72,6 +73,18 @@ static GLYPH_SNAP: ParamSchema = ParamSchema::new(
|
||||
.returns("the options")
|
||||
.writes(Writes::Preferences);
|
||||
|
||||
static PIXEL_SNAP: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("drawing", Type::Boolean).optional(),
|
||||
Param::new("moving", Type::Boolean).optional(),
|
||||
Param::new("scaling", Type::Boolean).optional(),
|
||||
],
|
||||
"the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them",
|
||||
)
|
||||
.returns("the options")
|
||||
.writes(Writes::Preferences)
|
||||
.since(4);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -125,6 +138,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
glyph_snap_options,
|
||||
schema: &GLYPH_SNAP
|
||||
),
|
||||
cmd!(
|
||||
query "view.snapToPixel.options",
|
||||
"Pixel Snapping Options",
|
||||
[],
|
||||
None,
|
||||
"{drawing?: bool, moving?: bool, scaling?: bool} the Pixel Snapping Options, kept in the preferences (the pixelSnap group, all on by default): which edits View › Snap to Pixel lands on whole pixels: drawing (the points the drawing tools place, the rulers' origin and measured points), moving (the selection, its anchors and segments, artboards and ruler guides moved, and the Rotate, Reflect and Shear tools' drags) and scaling (the edges a bounding-box, Free Transform, artboard or slice handle drags, and the Scale tool's drag); an edit whose option is off snaps as it does with Snap to Pixel off; {} reads them → the options",
|
||||
always,
|
||||
pixel_snap_options,
|
||||
schema: &PIXEL_SNAP
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -133,6 +156,11 @@ fn glyph_snap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!(s.prefs.glyph_snap))
|
||||
}
|
||||
|
||||
fn pixel_snap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.prefs.pixel_snap = s.prefs.pixel_snap.merged(p).map_err(|e| bad("view.snapToPixel.options", e))?;
|
||||
Ok(json!(s.prefs.pixel_snap))
|
||||
}
|
||||
|
||||
fn caps_lock(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(on) = p.get("on") {
|
||||
s.caps_lock = on.as_bool().ok_or_else(|| bad("view.capsLock", "on must be true or false"))?;
|
||||
@@ -379,15 +407,17 @@ mod tests {
|
||||
("view.saved.list", json!({"all": true}), "`all`"),
|
||||
("view.transparencyGrid", json!({"on": 1}), "`on`"),
|
||||
("view.snapToGlyph.options", json!({"bounds": "off"}), "`bounds`"),
|
||||
("view.snapToPixel.options", json!({"moving": "off"}), "`moving`"),
|
||||
("view.snapToPixel.options", json!({"drawing": false, "rotating": false}), "`rotating`"),
|
||||
] {
|
||||
let st = s.doc().unwrap();
|
||||
let doc = (st.doc.views.clone(), st.history.undo.len(), st.is_dirty());
|
||||
let (grid, caps, snap) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap);
|
||||
let (grid, caps, snap, pixel) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap);
|
||||
let e = s.execute(id, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains(id) && e.contains(named), "{id} {params}: {e}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!((&st.doc.views, st.history.undo.len(), st.is_dirty()), (&doc.0, doc.1, doc.2), "{id} {params}");
|
||||
assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap), (grid, caps, snap), "{id} {params}");
|
||||
assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap, s.prefs.pixel_snap), (grid, caps, snap, pixel), "{id} {params}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,9 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
|
||||
/// The commands that resize the artboards the app passes (Object › Artboards): the app passes the
|
||||
/// selected artboards to Fit to Artwork Bounds as its `indices`, and the active artboard to Fit to
|
||||
/// Selected Art as its `index`. A `command.batch` given `artboard` passes it on, as `index`, to
|
||||
/// each of their steps that names none.
|
||||
/// each of their steps that names none; a Fit to Artwork Bounds step that names neither `index` nor
|
||||
/// `indices`, while the Artboard tool is chosen with several artboards selected, gets those as its
|
||||
/// `indices` instead.
|
||||
pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"];
|
||||
|
||||
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
|
||||
@@ -162,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
|
||||
|
||||
@@ -260,6 +260,9 @@ pub struct Prefs {
|
||||
/// Character panel › Show Snap to Glyph Options: which guides View › Snap to Glyph gives
|
||||
/// (`view.snapToGlyph.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]).
|
||||
pub glyph_snap: vectorcraft_tools::GlyphSnap,
|
||||
/// Pixel Snapping Options: whether View › Snap to Pixel snaps drawing, moving and scaling
|
||||
/// (`view.snapToPixel.options`; a preference group, see [`cmd::prefscmds::PREF_GROUPS`]).
|
||||
pub pixel_snap: vectorcraft_tools::PixelSnap,
|
||||
/// Edit → Transparency Flattener Presets: the user's presets (the built-in ones aren't stored).
|
||||
/// Not a `prefs.set` key or group (resetting the preferences keeps them): `flattener.presets.*`
|
||||
/// edit it.
|
||||
@@ -523,6 +526,7 @@ impl Default for Prefs {
|
||||
eyedropper: Default::default(),
|
||||
pathfinder: Default::default(),
|
||||
glyph_snap: Default::default(),
|
||||
pixel_snap: Default::default(),
|
||||
flattener_presets: vec![],
|
||||
trace_presets: vec![],
|
||||
gradient_presets: vec![],
|
||||
|
||||
@@ -26,10 +26,11 @@ use crate::cmd::{CommandSpec, bad, command_specs};
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// The API level of the commands' parameters.
|
||||
pub const API_VERSION: u32 = 3;
|
||||
pub const API_VERSION: u32 = 4;
|
||||
|
||||
/// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s.
|
||||
pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a)];
|
||||
pub const SCHEMA_HASHES: &[(u32, u64)] =
|
||||
&[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653), (3, 0xffe0_58a3_2f0c_aa2a), (4, 0x1be4_be72_fe16_54c4)];
|
||||
|
||||
/// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]).
|
||||
pub fn schema_hash() -> u64 {
|
||||
@@ -311,12 +312,17 @@ mod tests {
|
||||
("view.transparencyGrid", json!({"on": 1})),
|
||||
("view.snapToGlyph.options", json!({"bounds": false, "angular": true})),
|
||||
("view.snapToGlyph.options", json!({"bounds": null})),
|
||||
("view.snapToPixel.options", json!({"drawing": false, "scaling": true})),
|
||||
("view.snapToPixel.options", json!({"moving": null})),
|
||||
("view.snapToPixel.options", json!({"moving": "off"})),
|
||||
("view.snapToPixel.options", json!({"rotating": false})),
|
||||
("view.capsLock", json!(null)),
|
||||
("view.saved.new", json!(null)),
|
||||
("view.saved.edit", json!(null)),
|
||||
("view.saved.list", json!(null)),
|
||||
("view.transparencyGrid", json!(null)),
|
||||
("view.snapToGlyph.options", json!(null)),
|
||||
("view.snapToPixel.options", json!(null)),
|
||||
("view.capsLock", json!([])),
|
||||
("view.saved.new", json!(5)),
|
||||
("view.transparencyGrid", json!("on")),
|
||||
@@ -325,7 +331,7 @@ mod tests {
|
||||
("engine.apiReference", json!({"prefix": "view."})),
|
||||
("engine.apiReference", json!([])),
|
||||
];
|
||||
assert_eq!(schemas().len(), 7);
|
||||
assert_eq!(schemas().len(), 8);
|
||||
for (id, schema) in schemas() {
|
||||
let written = schema.to_json();
|
||||
check_schema(&written, id).unwrap_or_else(|e| panic!("{e}\n{written:#}"));
|
||||
@@ -423,6 +429,7 @@ mod tests {
|
||||
("view.saved.list", "nothing"),
|
||||
("view.transparencyGrid", "session"),
|
||||
("view.snapToGlyph.options", "preferences"),
|
||||
("view.snapToPixel.options", "preferences"),
|
||||
];
|
||||
for (id, writes) in expected {
|
||||
let got = listed.iter().find(|(c, _)| *c == id).map(|(_, w)| w.clone());
|
||||
|
||||
@@ -672,6 +672,7 @@ impl Savepoint {
|
||||
s.pending_paint = self.pending_paint;
|
||||
self.choices.put(s);
|
||||
s.journal.truncate(self.journal);
|
||||
s.sync_front_profiles();
|
||||
exact
|
||||
}
|
||||
}
|
||||
@@ -822,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
|
||||
@@ -1890,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(()) })
|
||||
@@ -2231,6 +2267,9 @@ fn failure_text(report: &Value) -> String {
|
||||
fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result::Result<Progress, RunError>, String> {
|
||||
let depth = std::mem::replace(&mut s.depth, 0);
|
||||
job.world.swap(s);
|
||||
// The run's front document draws and converts through its own profiles, and the interface's
|
||||
// again after the slice.
|
||||
s.sync_front_profiles();
|
||||
s.script_in_run = true;
|
||||
let cell = job.host.session.clone();
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
@@ -2253,6 +2292,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
s.script_in_run = false;
|
||||
job.world.swap(s);
|
||||
s.depth = depth;
|
||||
s.sync_front_profiles();
|
||||
r
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -221,6 +221,7 @@ impl Session {
|
||||
self.active = Some(index);
|
||||
if switched {
|
||||
self.sync_front_composite_fonts();
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
true
|
||||
} else {
|
||||
@@ -228,6 +229,15 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the profiles the document in front is assigned the ones colors are drawn and converted
|
||||
/// through, in place of the working spaces (with no document open, or none assigned: the working
|
||||
/// spaces), after a switch, an open, a close, a revert or a restored document brought another
|
||||
/// document or another assignment to the front. The open documents redraw when the active color
|
||||
/// settings change.
|
||||
pub(crate) fn sync_front_profiles(&mut self) {
|
||||
cmd::colormgmt::use_front_profiles(self);
|
||||
}
|
||||
|
||||
/// Register the composite fonts of the document now in front ([`cmd::compositefonts::sync`]),
|
||||
/// after a switch or a close brought it there. Its type set in a composite font that differs
|
||||
/// from the one of that name before (added, changed or removed) is measured again, and type not
|
||||
@@ -317,6 +327,7 @@ impl Session {
|
||||
let i = self.docs.len() - 1;
|
||||
self.active = Some(i);
|
||||
self.sync_opened_composite_fonts(i);
|
||||
self.sync_front_profiles();
|
||||
if self.depth == 0
|
||||
&& let Some(label) = self.explicit_undo_group.clone()
|
||||
{
|
||||
@@ -385,7 +396,10 @@ impl Session {
|
||||
}
|
||||
match back_names {
|
||||
Some(names) => self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() && !sets_in_any(t, &names)),
|
||||
None => self.sync_opened_composite_fonts(index),
|
||||
None => {
|
||||
self.sync_opened_composite_fonts(index);
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -404,6 +418,7 @@ impl Session {
|
||||
}
|
||||
self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) };
|
||||
self.sync_front_composite_fonts();
|
||||
self.sync_front_profiles();
|
||||
true
|
||||
}
|
||||
|
||||
|
||||
@@ -332,6 +332,8 @@ impl Session {
|
||||
self.paint = paint.clone();
|
||||
}
|
||||
self.pending_paint = None;
|
||||
// The previous preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params));
|
||||
let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p));
|
||||
// A selected object's converted appearance must not replace the current paints while
|
||||
@@ -457,6 +459,8 @@ impl Session {
|
||||
st.undo_interaction();
|
||||
// Guides locked and slices locked or hidden during the interaction stay deselected.
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// A canceled preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
|
||||
// the document has it again, not as a preview left it.
|
||||
self.inherit_new_art();
|
||||
|
||||
@@ -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;
|
||||
@@ -196,6 +197,10 @@ impl Session {
|
||||
let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs());
|
||||
let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::<Vec<_>>());
|
||||
let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) };
|
||||
// Colors are drawn and converted through the profiles of the document in front now, also
|
||||
// after an undone or redone Assign Profile, a failed or panicked command's documents put
|
||||
// back, and a batch step, before the next step converts through them.
|
||||
self.sync_front_profiles();
|
||||
if r.is_err() && self.depth == 0 {
|
||||
self.batch_paint_docs.clear();
|
||||
// A failed or panicked command's documents are put back: type is drawn in their
|
||||
|
||||
@@ -164,6 +164,10 @@ impl Session {
|
||||
if self.depth == 0 {
|
||||
self.trim_histories();
|
||||
}
|
||||
// A canceled group's Assign Profile is undone with it.
|
||||
if cancel {
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
}
|
||||
|
||||
/// When journal entry `n` is a `command.batch` with `steps` noted in canceled undo groups and
|
||||
@@ -280,5 +284,7 @@ impl Session {
|
||||
g.journal.retain(|&(n, _)| n < scope.journal);
|
||||
g.steps.retain(|&(n, _)| n < scope.journal);
|
||||
}
|
||||
// A canceled scope's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
}
|
||||
@@ -4033,6 +4033,38 @@ fn snap_to_pixel_rounds_drawing_and_moves() {
|
||||
assert_eq!((b.x0, b.y0), (17.0, 16.0));
|
||||
}
|
||||
|
||||
/// Pixel Snapping Options (`view.snapToPixel.options`): with While Drawing off a rectangle drawn
|
||||
/// with Snap to Pixel on keeps its fractional corners while a move still lands on whole pixels, and
|
||||
/// with While Moving off a move keeps its fractional offset while drawing snaps again.
|
||||
#[test]
|
||||
fn pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo { snap_to_pixel: true, smart_guides: false, snap_to_point: false, ..Default::default() };
|
||||
let drag = |s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)| {
|
||||
s.select_tool(tool, v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, from.0, from.1), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, to.0, to.1), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, to.0, to.1), v).unwrap();
|
||||
};
|
||||
let bounds = |s: &Session, id| {
|
||||
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
(b.x0, b.y0, b.x1, b.y1)
|
||||
};
|
||||
s.execute("view.snapToPixel.options", &json!({"drawing": false})).unwrap();
|
||||
drag(&mut s, "rectangle", (10.25, 10.5), (60.5, 40.25));
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(bounds(&s, id), (10.25, 10.5, 60.5, 40.25), "drawing does not snap");
|
||||
drag(&mut s, "selection", (30.0, 30.0), (37.5, 34.75));
|
||||
assert_eq!(bounds(&s, id).0, 18.0, "moving still snaps the left edge");
|
||||
assert_eq!(bounds(&s, id).1, 15.0, "moving still snaps the top edge");
|
||||
s.execute("view.snapToPixel.options", &json!({"drawing": true, "moving": false})).unwrap();
|
||||
drag(&mut s, "selection", (40.0, 30.0), (45.25, 33.5));
|
||||
assert_eq!((bounds(&s, id).0, bounds(&s, id).1), (23.25, 18.5), "moving does not snap");
|
||||
drag(&mut s, "rectangle", (100.25, 100.5), (140.5, 130.75));
|
||||
let drawn = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(bounds(&s, drawn), (100.0, 101.0, 141.0, 131.0), "drawing snaps again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_turns_rough_strokes_into_live_shapes_and_scribbles_punch_fills() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -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 [
|
||||
|
||||
@@ -3788,6 +3788,103 @@ fn a_trace_run_needs_the_library_colours_it_traced_with() {
|
||||
assert!(!run.current(&s), "{name} changed");
|
||||
}
|
||||
|
||||
/// `image_doc`'s image with its disc 20 px to the left: the same size, other pixels.
|
||||
fn moved_disc_png() -> Vec<u8> {
|
||||
vectorcraft_trace::Raster::from_fn(100, 100, |x, y| {
|
||||
let (dx, dy) = (x as f64 + 0.5 - 30.0, y as f64 + 0.5 - 50.0);
|
||||
if dx * dx + dy * dy <= 900.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }
|
||||
})
|
||||
.encode_png()
|
||||
}
|
||||
|
||||
/// Puts `bytes` under the image key `key`, or takes the key's image data away (`None`).
|
||||
fn set_image_data(s: &mut Session, key: &str, bytes: Option<Vec<u8>>) {
|
||||
s.edit("image data", |d, _| {
|
||||
match bytes {
|
||||
Some(b) => d.images.insert(key.into(), ImageBlob::new("image/png", b)),
|
||||
None => d.images.remove(key),
|
||||
};
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The middle of the first traced path of the Image Trace object the reply `r` names, in x.
|
||||
fn traced_center_x(s: &Session, r: &Value) -> f64 {
|
||||
outline(&traced_paths(&node(s, NodeId(r["id"].as_u64().unwrap())))[0]).0.bounds().unwrap().center().x
|
||||
}
|
||||
|
||||
/// A trace made away from its command no longer applies once the pixels under its image's key
|
||||
/// change, though the object, its image record and the settings stay as they were; both commands
|
||||
/// then trace the pixels there now. The same bytes in another allocation still apply.
|
||||
#[test]
|
||||
fn a_trace_run_needs_the_pixels_it_traced() {
|
||||
let p = json!({"params": {"ignoreWhite": true}});
|
||||
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
|
||||
let mut s = session();
|
||||
image_doc(&mut s);
|
||||
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
|
||||
let traced = run.run(&|_, _| true).unwrap();
|
||||
// The same bytes, allocated anew: still current.
|
||||
let same = s.doc().unwrap().doc.images["img1"].bytes.to_vec();
|
||||
set_image_data(&mut s, "img1", Some(same));
|
||||
assert!(run.current(&s), "{command}: equal bytes");
|
||||
// Other pixels under the same key: no longer current, and the hand-off is dropped.
|
||||
set_image_data(&mut s, "img1", Some(moved_disc_png()));
|
||||
assert!(!run.current(&s), "{command}: other pixels");
|
||||
traced.hand_in(&mut s);
|
||||
let r = s.execute(command, run.params()).unwrap();
|
||||
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
|
||||
// The disc is now at image x 30, which the ×2 placement at 50 puts at 110.
|
||||
let x = traced_center_x(&s, &r);
|
||||
assert!((x - 110.0).abs() < 1.5, "{command}: traced the pixels there now, at {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Image data that is missing or empty: a run made before it went no longer applies, the run's
|
||||
/// command gives the error it gives without a run, and nothing panics.
|
||||
#[test]
|
||||
fn a_trace_run_of_missing_or_empty_image_data() {
|
||||
let p = json!({"params": {"ignoreWhite": true}});
|
||||
let mut s = session();
|
||||
image_doc(&mut s);
|
||||
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
|
||||
let traced = run.run(&|_, _| true).unwrap();
|
||||
set_image_data(&mut s, "img1", None);
|
||||
assert!(!run.current(&s), "missing");
|
||||
traced.hand_in(&mut s);
|
||||
let e = s.execute(run.command(), run.params()).unwrap_err().to_string();
|
||||
assert!(e.contains("image data `img1` is missing"), "{e}");
|
||||
set_image_data(&mut s, "img1", Some(vec![]));
|
||||
assert!(!run.current(&s), "empty");
|
||||
let empty = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
|
||||
assert!(empty.current(&s), "two empty blobs are equal");
|
||||
assert!(matches!(empty.run(&|_, _| true), Err(EngineError::Other(_))));
|
||||
assert!(matches!(s.execute(run.command(), run.params()), Err(EngineError::Other(_))));
|
||||
}
|
||||
|
||||
/// Tracing an Image Trace object again follows the same rule: once the pixels of the image it
|
||||
/// holds change, a run made before no longer applies, and the command traces the pixels there now.
|
||||
#[test]
|
||||
fn a_trace_run_of_an_image_trace_object_needs_its_pixels() {
|
||||
let p = json!({"params": {"ignoreWhite": true}});
|
||||
let mut s = session();
|
||||
image_doc(&mut s);
|
||||
let g = s.execute("imageTrace.make", &p).unwrap()["id"].as_u64().unwrap();
|
||||
let again = json!({"id": g, "params": {"ignoreWhite": true}});
|
||||
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &again).unwrap();
|
||||
assert_eq!(run.target(), NodeId(g));
|
||||
let traced = run.run(&|_, _| true).unwrap();
|
||||
assert!(run.current(&s));
|
||||
set_image_data(&mut s, "img1", Some(moved_disc_png()));
|
||||
assert!(!run.current(&s));
|
||||
traced.hand_in(&mut s);
|
||||
let r = s.execute(run.command(), run.params()).unwrap();
|
||||
assert!(s.trace_hand_off.is_none(), "dropped");
|
||||
let x = traced_center_x(&s, &r);
|
||||
assert!((x - 110.0).abs() < 1.5, "traced the pixels there now, at {x}");
|
||||
}
|
||||
|
||||
/// Shapes: the disc of the test image comes out as a live ellipse where the image lies, the same
|
||||
/// circle as its traced path; without the option it is a plain path.
|
||||
#[test]
|
||||
|
||||
@@ -326,6 +326,31 @@ fn update_link_takes_the_files_clipping_path_into_symbols_too() {
|
||||
assert_eq!(symbol_clip_width(&s, "Pic"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_and_relink_by_id_keep_the_clipping_path_of_a_dcs_image_in_a_symbol() {
|
||||
let dir = temp_dir("symbol-clip-by-id");
|
||||
let path = write(&dir, "pic.eps", &two_plates());
|
||||
let mut s = session();
|
||||
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
|
||||
s.execute("symbol.new", &json!({ "name": "Pic", "ids": [r["ids"][0]] })).unwrap();
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image is listed");
|
||||
let id = row["id"].as_u64().unwrap();
|
||||
assert_eq!(row["format"], "DCS", "{list}");
|
||||
let before = symbol_clip_width(&s, "Pic").expect("the file's clipping path");
|
||||
// The composite now drawn through the left quarter of the page (same length).
|
||||
let text = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1);
|
||||
std::fs::write(&path, text.as_bytes()).unwrap();
|
||||
assert_eq!(s.execute("links.update", &json!({ "ids": [id] })).unwrap()["updated"], json!([id]));
|
||||
let after = symbol_clip_width(&s, "Pic").expect("still clipped");
|
||||
assert!((after - before / 2.0).abs() < 1e-6, "the symbol's clipping path follows the file: {before} → {after}");
|
||||
// Relinked by its id to a plain image: the DCS file's clipping path goes.
|
||||
let png = dir.join("plain.png");
|
||||
image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9])).save(&png).unwrap();
|
||||
s.execute("links.relink", &json!({ "ids": [id], "path": png.to_string_lossy() })).unwrap();
|
||||
assert_eq!(symbol_clip_width(&s, "Pic"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_lost_its_clipping_path_unclips_the_image() {
|
||||
let dir = temp_dir("update-lost-clip");
|
||||
|
||||
@@ -1367,6 +1367,37 @@ fn smooth_tool_reduces_jagged_path() {
|
||||
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0));
|
||||
}
|
||||
|
||||
/// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and
|
||||
/// a line: every anchor between the path's ends turns by at most 1°.
|
||||
#[test]
|
||||
fn smooth_tool_leaves_no_corner_where_a_curve_meets_a_line() {
|
||||
let mut s = session();
|
||||
let mut seed = 7u64;
|
||||
let anchors: Vec<_> = (0..=60)
|
||||
.map(|i| {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0;
|
||||
json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise})
|
||||
})
|
||||
.collect();
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let drag_points: Vec<(f64, f64)> = (0..=64).map(|i| (90.0 + f64::from(i) * 5.0, 200.0)).collect();
|
||||
drag(&mut s, "smooth", &drag_points, Mods::default());
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.anchors.len() < 61, "the path is smoothed: {}", sp.anchors.len());
|
||||
let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord);
|
||||
for i in 1..sp.segment_count() {
|
||||
let (prev, next) = (sp.segment(i - 1), sp.segment(i));
|
||||
let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0);
|
||||
let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0);
|
||||
let turn = arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees();
|
||||
let kinds = (sp.segment_is_line(i - 1), sp.segment_is_line(i));
|
||||
assert!(turn <= 1.0, "anchor {i} turns {turn}° (lines before and after: {kinds:?}): {:?}", sp.anchors[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no
|
||||
/// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag
|
||||
/// does not reach keeps its anchors selected, and undo brings the old selection back.
|
||||
@@ -2718,6 +2749,49 @@ fn remove_anchor_points_selects_one_next_anchor_per_subpath_and_per_path() {
|
||||
assert_eq!(selected_anchors(&s, other), [(0, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_anchor_points_on_many_paths_and_subpaths_matches_removing_one_at_a_time() {
|
||||
// Many anchors over many subpaths and paths, curved and straight, open and closed: each
|
||||
// subpath ends as removing its anchors one at a time, the last first, leaves it. Paths left
|
||||
// with nothing go, the rest stay selected in order, and one undo step brings all back.
|
||||
let mut s = session();
|
||||
let curvy = "M0 0 C10 20 30 20 40 0 C50 -20 70 -20 80 0 C90 20 110 20 120 0 C130 -20 150 -20 160 0 Z \
|
||||
M0 100 L40 120 C60 140 80 80 100 100 L140 90 L180 110 L220 100";
|
||||
let ids: Vec<NodeId> = (0..4).map(|i| path_from(&mut s, if i == 2 { "M0 0 L10 0 L20 5" } else { curvy })).collect();
|
||||
let picks: [&[(usize, usize)]; 4] =
|
||||
[&[(0, 0), (0, 2), (0, 3), (1, 1), (1, 2), (1, 5)], &[(0, 1), (1, 0), (1, 6)], &[(0, 0), (0, 1)], &[(0, 3), (1, 3), (1, 4)]];
|
||||
for (k, (&id, &anchors)) in ids.iter().zip(&picks).enumerate() {
|
||||
let mode = if k == 0 { "set" } else { "add" };
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap();
|
||||
}
|
||||
let before: Vec<PathData> = ids.iter().map(|&id| path(&s, id)).collect();
|
||||
assert_eq!(s.execute("path.removeAnchors", &json!({})).unwrap()["removedObjects"], 1);
|
||||
for (k, &id) in ids.iter().enumerate() {
|
||||
let mut want = before[k].clone();
|
||||
let mut order = picks[k].to_vec();
|
||||
order.sort_unstable_by(|a, b| b.cmp(a));
|
||||
for (si, ai) in order {
|
||||
vectorcraft_pathops::remove_anchor(&mut want.subpaths[si], ai);
|
||||
}
|
||||
want.subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
if want.subpaths.is_empty() {
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none(), "path {k} goes");
|
||||
} else {
|
||||
assert_eq!(path(&s, id).subpaths, want.subpaths, "path {k}");
|
||||
}
|
||||
}
|
||||
let kept = [ids[0], ids[1], ids[3]];
|
||||
assert_eq!(s.doc().unwrap().selection.objects, kept);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
for (k, &id) in ids.iter().enumerate() {
|
||||
assert_eq!(path(&s, id), before[k]);
|
||||
assert_eq!(selected_anchors(&s, id), picks[k]);
|
||||
}
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(ids[2]).is_none());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, kept);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_anchor_point_tool_and_delete_still_select_the_remainder_whole() {
|
||||
// Only Remove Anchor Points moves the selection on. The Delete Anchor Point tool leaves the
|
||||
@@ -4643,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;
|
||||
@@ -4650,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()
|
||||
}
|
||||
|
||||
@@ -4662,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
|
||||
@@ -4684,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]
|
||||
|
||||
@@ -192,6 +192,87 @@ fn fit_steps_take_the_batchs_artboard_and_actions_leave_out_their_index() {
|
||||
assert_eq!(action, [fit("artboard.fitToArt"), fit("artboard.fitToArt"), fit("artboard.fitToSelection")]);
|
||||
}
|
||||
|
||||
/// A document of three artboards with art of its own on each → its artboards before any fit.
|
||||
fn three_artboards_with_art(s: &mut Session) -> Vec<vectorcraft_geom::Rect> {
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3, "created": null})).unwrap();
|
||||
for (x, h) in [(10, 30), (130, 20), (250, 40)] {
|
||||
s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap();
|
||||
}
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect()
|
||||
}
|
||||
|
||||
/// The artboards of [`three_artboards_with_art`], each fitted to its art.
|
||||
fn three_fitted_artboards() -> [vectorcraft_geom::Rect; 3] {
|
||||
let rect = vectorcraft_geom::Rect::new;
|
||||
[rect(10.0, 10.0, 30.0, 40.0), rect(130.0, 10.0, 150.0, 30.0), rect(250.0, 10.0, 270.0, 50.0)]
|
||||
}
|
||||
|
||||
/// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard tool
|
||||
/// is chosen with several artboards selected, fits each of those (not the batch's artboard), as the
|
||||
/// command does on its own; a step's own `index` or `indices` wins, and with one artboard or none
|
||||
/// selected the step takes the batch's artboard.
|
||||
#[test]
|
||||
fn a_batch_fit_step_uses_the_artboard_tool_selection() {
|
||||
let fitted = three_fitted_artboards();
|
||||
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let fit = |params: Value| json!({"artboard": 1, "commands": [{"command": "artboard.fitToArt", "params": params}]});
|
||||
let session = |picks: &Value| {
|
||||
let mut s = Session::new();
|
||||
let was = three_artboards_with_art(&mut s);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", picks);
|
||||
(s, was)
|
||||
};
|
||||
let (mut s, was) = session(&json!([2, 0]));
|
||||
s.execute("command.batch", &fit(json!({}))).unwrap();
|
||||
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "artboards 1 and 3, the selected ones, and not the batch's artboard 2");
|
||||
let (mut s, was) = session(&json!([2, 0]));
|
||||
s.execute("command.batch", &fit(json!({"index": 1}))).unwrap();
|
||||
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "a step's own index");
|
||||
let (mut s, was) = session(&json!([2, 0]));
|
||||
s.execute("command.batch", &fit(json!({"indices": [1, 2]}))).unwrap();
|
||||
assert_eq!(boards(&s), [was[0], fitted[1], fitted[2]], "a step's own indices");
|
||||
for picks in [json!([2]), json!([])] {
|
||||
let (mut s, was) = session(&picks);
|
||||
s.execute("command.batch", &fit(json!({}))).unwrap();
|
||||
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard with {picks} selected");
|
||||
}
|
||||
}
|
||||
|
||||
/// The journal records the artboards a batch's Fit to Artwork Bounds step took from the Artboard
|
||||
/// tool, so a replay in a new session fits the same ones; an action leaves them out and fits the
|
||||
/// artboards selected when it plays.
|
||||
#[test]
|
||||
fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() {
|
||||
let fitted = three_fitted_artboards();
|
||||
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
let mut s = Session::new();
|
||||
let was = three_artboards_with_art(&mut s);
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([0, 2]));
|
||||
let start = s.journal.len();
|
||||
let steps = json!([{"command": "artboard.fitToArt", "params": {}}]);
|
||||
s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap();
|
||||
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]]);
|
||||
let (id, p) = s.journal.last().unwrap().clone();
|
||||
assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({"indices": [0, 2]})));
|
||||
let r = replayed(&s);
|
||||
assert_ne!(r.tool_id(), "artboard", "the new session's tool selects no artboards");
|
||||
assert_eq!(boards(&r), boards(&s), "the replay fits the recorded artboards");
|
||||
let action = s.journal_for_action(start);
|
||||
assert_eq!(action, [("command.batch".to_string(), json!({"commands": steps}))]);
|
||||
// Played on a fresh copy of the document with other artboards selected.
|
||||
let mut a = Session::new();
|
||||
three_artboards_with_art(&mut a);
|
||||
a.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
a.set_tool_option("selected", &json!([1, 2]));
|
||||
a.execute("command.batch", &json!({"artboard": 0, "commands": action[0].1["commands"]})).unwrap();
|
||||
assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_records_its_date_and_replays_it() {
|
||||
let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned();
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind};
|
||||
use vectorcraft_doc::{Document, ImageObject, LinkInfo, NodeKind, StoredRoot};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::*;
|
||||
@@ -446,8 +446,8 @@ fn links_outside_the_layers_find_their_files_after_the_folder_moves() {
|
||||
}
|
||||
|
||||
/// With Update Links: Automatically, a file in a symbol and in the layers that changed and moved
|
||||
/// with the document is read again for the layers' image and for the symbol's, and both links take
|
||||
/// its new path, size and hash.
|
||||
/// with the document is read again for the layers' image and for the symbol's, both are listed by
|
||||
/// their ids, and both links take its new path, size and hash.
|
||||
#[test]
|
||||
fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() {
|
||||
let a = Folder::new("nested-modified-a");
|
||||
@@ -458,13 +458,14 @@ fn a_symbols_link_to_a_moved_and_modified_file_takes_its_new_path() {
|
||||
s.execute("prefs.set", &json!({"key": "updateLinks", "value": "automatically"})).unwrap();
|
||||
let id = place(&mut s, &pic);
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
|
||||
let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0));
|
||||
let id = place(&mut s, &pic);
|
||||
save(&mut s, &a.file("poster.vectorcraft"));
|
||||
write(&pic, &png(30, 30, BLUE));
|
||||
std::fs::remove_dir_all(&b.0).unwrap();
|
||||
std::fs::rename(&a.0, &b.0).unwrap();
|
||||
let r = open(&mut s, &b.file("poster.vectorcraft"));
|
||||
assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0])), "{r}");
|
||||
assert_eq!((r["modifiedLinks"].clone(), r["updatedLinks"][0]["ids"].clone()), (json!([]), json!([id.0, in_symbol.0])), "{r}");
|
||||
let moved = PathBuf::from(b.file("art/photo.png"));
|
||||
let blue = png(30, 30, BLUE);
|
||||
let mut images = vec![];
|
||||
@@ -521,7 +522,8 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
|
||||
|
||||
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
|
||||
/// masks too: those showing the same content as an image in the layers, and those no object in the
|
||||
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step.
|
||||
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
|
||||
/// and the reply lists each by its id.
|
||||
#[test]
|
||||
fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
|
||||
let dir = Folder::new("nested-update");
|
||||
@@ -533,11 +535,13 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
|
||||
let id = place(&mut s, &photo);
|
||||
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
|
||||
let in_symbol = stored_image_in(&s, StoredRoot::Symbol(0));
|
||||
let id = place(&mut s, &photo);
|
||||
// logo.png only in a pattern and in an opacity mask.
|
||||
let p = place(&mut s, &logo);
|
||||
s.execute("object.pattern.make", &json!({"ids": [p.0], "edit": false})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [p.0]})).unwrap();
|
||||
let p = stored_image_in(&s, StoredRoot::Pattern { pattern: 0, art: 0 });
|
||||
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
|
||||
let mask = place(&mut s, &logo);
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
|
||||
@@ -546,7 +550,8 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
|
||||
write(&photo, &blue);
|
||||
write(&logo, &green);
|
||||
let u = s.execute("links.update", &json!({})).unwrap();
|
||||
assert_eq!(u, json!({"updated": [id.0], "missing": []}));
|
||||
// By file: photo.png in the layers and the symbol, then logo.png in the mask and the pattern.
|
||||
assert_eq!(u, json!({"updated": [id.0, in_symbol.0, mask.0, p.0], "missing": []}));
|
||||
// (name, size, hash, pixel size) of each image, which shows its file's pixels.
|
||||
let images = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
@@ -576,6 +581,193 @@ fn update_links_reads_files_again_inside_symbols_patterns_and_masks() {
|
||||
assert!(images(&s).iter().all(|(_, _, _, size)| *size == (20, 10)), "{:?}", images(&s));
|
||||
}
|
||||
|
||||
/// The files only art outside the layers shows: one in a symbol, a graph design, a pattern and an
|
||||
/// opacity mask each, no object in the layers linked to any of them.
|
||||
const NESTED: [&str; 4] = ["symbol.png", "design.png", "pattern.png", "mask.png"];
|
||||
|
||||
/// A document whose only links are [`NESTED`]'s files in `dir`.
|
||||
fn nested_links(dir: &Folder) -> Session {
|
||||
for (i, name) in (0u8..).zip(NESTED) {
|
||||
write(&dir.file(name), &png(20, 10, [20 + 50 * i, 90, 160]));
|
||||
}
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &dir.file("symbol.png"));
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [s.doc().unwrap().selection.objects[0].0]})).unwrap();
|
||||
let id = place(&mut s, &dir.file("design.png"));
|
||||
s.execute("graph.design", &json!({"new": "Bar"})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
let id = place(&mut s, &dir.file("pattern.png"));
|
||||
s.execute("object.pattern.make", &json!({"ids": [id.0], "edit": false})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0);
|
||||
let mask = place(&mut s, &dir.file("mask.png"));
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The id of the `links.list` row of file `name`.
|
||||
fn row_id(s: &mut Session, name: &str) -> u64 {
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name).unwrap_or_else(|| panic!("{name} in {list}"));
|
||||
row["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// The link of stored object `id`.
|
||||
fn stored_link(s: &Session, id: u64) -> Option<LinkInfo> {
|
||||
match &s.doc().unwrap().doc.stored_node(NodeId(id)).unwrap().0.kind {
|
||||
NodeKind::Image(im) => im.link.clone(),
|
||||
k => panic!("not an image: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of the first image stored in the art of `root`.
|
||||
fn stored_image_in(s: &Session, root: StoredRoot) -> NodeId {
|
||||
let mut found = None;
|
||||
s.doc().unwrap().doc.visit_stored(|n, place| {
|
||||
if found.is_none() && place.root == root && matches!(n.kind, NodeKind::Image(_)) {
|
||||
found = Some(n.id);
|
||||
}
|
||||
});
|
||||
found.unwrap_or_else(|| panic!("no image in {root:?}"))
|
||||
}
|
||||
|
||||
/// Images in symbols, graph designs, patterns and opacity masks are listed and checked with ids of
|
||||
/// their own, one row each with what holds it, and the missing filter counts them.
|
||||
#[test]
|
||||
fn links_outside_the_layers_are_listed_and_checked_with_ids() {
|
||||
let dir = Folder::new("nested-ids");
|
||||
let mut s = nested_links(&dir);
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let rows = list["links"].as_array().unwrap();
|
||||
let owners: Vec<(&str, &str)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), r["owner"]["kind"].as_str().unwrap_or("-"))).collect();
|
||||
assert_eq!(owners, [("mask.png", "layers"), ("symbol.png", "symbol"), ("design.png", "graphDesign"), ("pattern.png", "pattern")], "{list}");
|
||||
assert_eq!(rows[1]["owner"]["name"], "Mark");
|
||||
let masked = s.doc().unwrap().doc.layers[0].children().unwrap().iter().find(|n| n.extras().mask.is_some()).unwrap().id;
|
||||
assert_eq!(rows[0]["owner"]["maskOf"], json!(masked.0));
|
||||
let ids: std::collections::BTreeSet<u64> = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect();
|
||||
assert_eq!(ids.len(), 4, "{list}");
|
||||
assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}");
|
||||
let check = s.execute("links.check", &json!({})).unwrap();
|
||||
let checked: Vec<(&str, &Value)> = check["links"].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap(), &l["ids"])).collect();
|
||||
assert_eq!(checked.len(), 4, "{check}");
|
||||
for (name, ids) in checked {
|
||||
assert_eq!(*ids, json!([row_id(&mut s, name)]), "{check}");
|
||||
}
|
||||
std::fs::remove_file(dir.file("design.png")).unwrap();
|
||||
let check = s.execute("links.check", &json!({})).unwrap();
|
||||
assert_eq!((check["missing"].as_u64(), check["modified"].as_u64()), (Some(1), Some(0)), "{check}");
|
||||
let design = row_id(&mut s, "design.png");
|
||||
let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap();
|
||||
assert_eq!((missing["missing"].as_u64(), &missing["links"][0]["id"]), (Some(1), &json!(design)), "{missing}");
|
||||
let one = s.execute("links.check", &json!({"ids": [design]})).unwrap();
|
||||
assert_eq!(one["links"][0]["status"], "missing", "{one}");
|
||||
}
|
||||
|
||||
/// Every links command takes the id of an image outside the layers and acts on that object: Link
|
||||
/// Info, Go To (which clears the selection and names the symbol), Placement Options, Relink, Update and
|
||||
/// Embed.
|
||||
#[test]
|
||||
fn links_commands_act_on_images_outside_the_layers_by_id() {
|
||||
let dir = Folder::new("nested-act");
|
||||
let mut s = nested_links(&dir);
|
||||
let symbol = row_id(&mut s, "symbol.png");
|
||||
let info = s.execute("links.info", &json!({"id": symbol})).unwrap();
|
||||
assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("symbol.png"), Some("ok"), Some(symbol)), "{info}");
|
||||
let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0);
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
let go = s.execute("links.goTo", &json!({"id": symbol})).unwrap();
|
||||
assert_eq!(
|
||||
(go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()),
|
||||
(json!(false), json!("symbol"), json!("Mark")),
|
||||
"{go}"
|
||||
);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected");
|
||||
s.execute("links.placementOptions", &json!({"ids": [symbol], "preserve": "fit"})).unwrap();
|
||||
let placement = s.execute("links.placementOptions", &json!({"ids": [symbol]})).unwrap();
|
||||
assert_eq!(placement["placement"]["preserve"], "fit");
|
||||
// Relink: the symbol's image shows the new file.
|
||||
let other = dir.file("other.png");
|
||||
write(&other, &png(40, 20, BLUE));
|
||||
let r = s.execute("links.relink", &json!({"ids": [symbol], "path": other})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([symbol]), "{r}");
|
||||
assert_eq!(stored_link(&s, symbol).unwrap().path, other);
|
||||
// Update: a changed pattern file is read again for the pattern's image.
|
||||
let pattern = row_id(&mut s, "pattern.png");
|
||||
let changed = png(30, 30, RED);
|
||||
write(&dir.file("pattern.png"), &changed);
|
||||
let r = s.execute("links.update", &json!({"ids": [pattern]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([pattern]), "{r}");
|
||||
assert_eq!(stored_link(&s, pattern).unwrap().size, Some(changed.len() as u64));
|
||||
// Embed: the design's image keeps its pixels and no longer links.
|
||||
let design = row_id(&mut s, "design.png");
|
||||
let r = s.execute("links.embed", &json!({"ids": [design]})).unwrap();
|
||||
assert_eq!(r["embedded"], json!([design]), "{r}");
|
||||
assert!(stored_link(&s, design).is_none());
|
||||
let row = s.execute("links.list", &json!({"show": "embedded"})).unwrap();
|
||||
assert_eq!(row["links"][0]["id"], json!(design), "{row}");
|
||||
// Relink All Instances takes the other stored objects linked to the same file.
|
||||
let mask = row_id(&mut s, "mask.png");
|
||||
let r = s.execute("links.relink", &json!({"ids": [symbol], "path": dir.file("mask.png"), "scope": "all"})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([symbol]), "{r}");
|
||||
let r = s.execute("links.relink", &json!({"ids": [mask], "path": other, "scope": "all"})).unwrap();
|
||||
let mut relinked: Vec<u64> = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
relinked.sort();
|
||||
let mut both = vec![symbol, mask];
|
||||
both.sort();
|
||||
assert_eq!(relinked, both, "{r}");
|
||||
}
|
||||
|
||||
/// Opening a document reports missing and modified files that only art outside the layers shows,
|
||||
/// by their objects' ids, and those ids stay the same after the document is saved and opened again.
|
||||
#[test]
|
||||
fn open_reports_links_outside_the_layers_by_id() {
|
||||
let dir = Folder::new("nested-open");
|
||||
let mut s = nested_links(&dir);
|
||||
let path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &path);
|
||||
let ids: Vec<u64> = NESTED.iter().map(|name| row_id(&mut s, name)).collect();
|
||||
std::fs::remove_file(dir.file("symbol.png")).unwrap();
|
||||
write(&dir.file("pattern.png"), &png(30, 30, RED));
|
||||
let r = open(&mut s, &path);
|
||||
let names = |k: &str| r[k].as_array().unwrap().iter().map(|l| (l["name"].as_str().unwrap().to_string(), l["ids"].clone())).collect::<Vec<_>>();
|
||||
assert_eq!(names("missingLinks"), [("symbol.png".to_string(), json!([ids[0]]))], "{r}");
|
||||
assert_eq!(names("modifiedLinks"), [("pattern.png".to_string(), json!([ids[2]]))], "{r}");
|
||||
let again: Vec<u64> = NESTED.iter().map(|name| row_id(&mut s, name)).collect();
|
||||
assert_eq!(again, ids, "the ids are saved");
|
||||
}
|
||||
|
||||
/// A document whose symbol and mask art repeat the ids of objects in the layers (or have none)
|
||||
/// opens with ids of their own there, the layer tree's kept; the links commands then tell them apart.
|
||||
#[test]
|
||||
fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() {
|
||||
let dir = Folder::new("nested-repeat");
|
||||
let mut s = nested_links(&dir);
|
||||
let layer_image = place(&mut s, &dir.file("symbol.png"));
|
||||
let path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &path);
|
||||
// The symbol's image takes the id of the image in the layers, the mask's image none.
|
||||
let mut saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
saved["document"]["symbols"][0]["art"]["id"] = json!(layer_image.0);
|
||||
let layer = &mut saved["document"]["layers"][0]["kind"]["children"];
|
||||
let masked = layer.as_array_mut().unwrap().iter_mut().find(|n| n.get("mask").is_some() || n["extras"].get("mask").is_some()).unwrap();
|
||||
let mask = if masked.get("mask").is_some() { &mut masked["mask"] } else { &mut masked["extras"]["mask"] };
|
||||
mask["art"]["id"] = json!(0);
|
||||
std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap();
|
||||
open(&mut s, &path);
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let ids: Vec<u64> = list["links"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect();
|
||||
let unique: std::collections::BTreeSet<u64> = ids.iter().copied().collect();
|
||||
assert_eq!((ids.len(), unique.len()), (5, 5), "{list}");
|
||||
assert!(!ids.contains(&0), "{list}");
|
||||
assert_eq!(list["links"][0]["id"], json!(layer_image.0), "the layer tree keeps its ids: {list}");
|
||||
let symbol = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("links.embed", &json!({"ids": [symbol]})).unwrap();
|
||||
assert!(stored_link(&s, symbol).is_none());
|
||||
assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked");
|
||||
}
|
||||
|
||||
/// An image that Placement Options clip, alone in a group the user made, goes into a new clip group
|
||||
/// inside that group when its file grows, in the layers and in a symbol's art; the user's group
|
||||
/// stays a plain group.
|
||||
|
||||
@@ -213,7 +213,7 @@ fn go_to_selects_the_image() {
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
|
||||
assert_ne!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
let r = run(&mut s, "links.goTo", json!({"id": id.0}));
|
||||
assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0]}));
|
||||
assert_eq!(r, json!({"id": id.0, "bounds": [-100.0, 0.0, 500.0, 300.0], "onCanvas": true}));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
let rect = s.doc().unwrap().doc.layers[0].children().unwrap()[1].id;
|
||||
assert!(s.execute("links.goTo", &json!({"id": rect.0})).is_err(), "not an image");
|
||||
|
||||
@@ -47,6 +47,30 @@ fn update_changed_reads_changed_files_again_once() {
|
||||
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 1);
|
||||
}
|
||||
|
||||
/// A file only a symbol's art shows is watched too, and read again by the id of the symbol's image.
|
||||
#[test]
|
||||
fn update_changed_reads_a_file_only_a_symbol_shows() {
|
||||
let dir = Folder::new("watch-symbol");
|
||||
let path = dir.file("art.png");
|
||||
std::fs::write(&path, png(40, 40, RED)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [id.0]})).unwrap();
|
||||
let instance = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("edit.clear", &json!({"ids": [instance.0]})).unwrap();
|
||||
let mut in_symbol = None;
|
||||
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)) {
|
||||
in_symbol = Some(n.id.0);
|
||||
}
|
||||
});
|
||||
let in_symbol = in_symbol.expect("the symbol's image");
|
||||
assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([]));
|
||||
save(&path, &png(40, 40, BLUE));
|
||||
assert_eq!(s.execute("links.updateChanged", &json!({})).unwrap()["updated"], json!([in_symbol]));
|
||||
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_look_follows_update_links() {
|
||||
for (mode, key) in [("automatically", "updated"), ("askWhenModified", "ask"), ("manually", "modified")] {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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 [
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -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]
|
||||
@@ -662,6 +751,101 @@ fn placed_art_brings_its_symbols_and_swatches_renaming_on_conflict() {
|
||||
assert!(linked, "still linked to the swatch it brought");
|
||||
}
|
||||
|
||||
/// The symbol and pattern art placed art brings takes ids of the document's own: the file's ids
|
||||
/// already name other objects there, and the Links panel names linked art in symbols by its id.
|
||||
#[test]
|
||||
fn placed_art_brings_its_symbols_and_patterns_with_ids_of_the_documents_own() {
|
||||
let mut src = session();
|
||||
src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
src.execute("symbol.new", &json!({"name": "Star"})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
|
||||
let tile = src.doc().unwrap().selection.objects[0];
|
||||
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
|
||||
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
|
||||
let bytes = serialize(&mut src, "vectorcraft");
|
||||
// The document's objects take the same ids the file's do.
|
||||
let mut s = session();
|
||||
for x in [0, 20, 40, 60] {
|
||||
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap();
|
||||
}
|
||||
s.execute("symbol.new", &json!({"name": "Box"})).unwrap();
|
||||
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(doc.symbols.iter().any(|x| x.name == "Star") && doc.pattern("Dots").is_some());
|
||||
let mut ids = vec![];
|
||||
doc.visit_stored(|n, _| ids.push(n.id.0));
|
||||
let unique: std::collections::BTreeSet<u64> = ids.iter().copied().collect();
|
||||
assert_eq!(unique.len(), ids.len(), "{ids:?}");
|
||||
}
|
||||
|
||||
/// Placing the same file again shares the symbols and patterns the first placement brought: their
|
||||
/// art differs from the file's only in its ids, so no `Star 2` or `Dots 2` joins the document.
|
||||
#[test]
|
||||
fn placing_the_same_art_again_shares_its_symbols_and_patterns() {
|
||||
let mut src = session();
|
||||
src.execute("shape.ellipse", &json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
src.execute("symbol.new", &json!({"name": "Star"})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
|
||||
let tile = src.doc().unwrap().selection.objects[0];
|
||||
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
|
||||
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
|
||||
let bytes = serialize(&mut src, "vectorcraft");
|
||||
let mut s = session();
|
||||
let counts = |s: &Session| {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
(doc.symbols.len(), doc.patterns.len())
|
||||
};
|
||||
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
let once = counts(&s);
|
||||
for _ in 0..2 {
|
||||
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
}
|
||||
assert_eq!(counts(&s), once);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(!doc.symbols.iter().any(|x| x.name == "Star 2") && doc.pattern("Dots 2").is_none());
|
||||
}
|
||||
|
||||
/// A symbol whose art matches the document's own but uses a pattern the document defines
|
||||
/// differently is not shared: it comes in under a free name, using the pattern it brings.
|
||||
#[test]
|
||||
fn placed_art_does_not_share_a_symbol_whose_pattern_moves() {
|
||||
let mut src = session();
|
||||
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap();
|
||||
let tile = src.doc().unwrap().selection.objects[0];
|
||||
src.execute("object.pattern.make", &json!({"ids": [tile.0], "edit": false, "name": "Dots"})).unwrap();
|
||||
src.execute("paint.setFill", &json!({"ids": [tile.0], "swatch": "Dots"})).unwrap();
|
||||
src.execute("symbol.new", &json!({"name": "Star", "ids": [tile.0]})).unwrap();
|
||||
let bytes = serialize(&mut src, "vectorcraft");
|
||||
let mut s = session();
|
||||
place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
// The document's "Dots" changes; its "Star" still matches the file's.
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = Arc::make_mut(&mut st.doc);
|
||||
let dots = d.pattern_mut("Dots").unwrap();
|
||||
dots.tile = Rect::new(0.0, 0.0, 50.0, 50.0);
|
||||
let r = place(&mut s, "logo.vectorcraft", &bytes, json!({}));
|
||||
let mut symbol = None;
|
||||
node(&s, &r["ids"][0]).walk(&mut |n| {
|
||||
if let NodeKind::SymbolInstance { symbol: name, .. } = &n.kind {
|
||||
symbol = Some(name.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(symbol.as_deref(), Some("Star 2"));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let star2 = doc.symbols.iter().find(|x| x.name == "Star 2").unwrap();
|
||||
let mut fills = vec![];
|
||||
star2.art.walk(&mut |n| {
|
||||
fills.extend(n.appearance.items.iter().filter_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => match &f.paint {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}))
|
||||
});
|
||||
assert_eq!(fills, ["Dots 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_art_brings_its_brushes_renaming_on_conflict() {
|
||||
// The file: a path with its own brush, and one with a brush the defaults hold.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -753,6 +753,9 @@ fn precise_cursors_replace_every_pen_state() {
|
||||
Cursor::ShapeBuilderErase,
|
||||
Cursor::AnchorPoint,
|
||||
Cursor::Curvature,
|
||||
Cursor::LivePaintBucket,
|
||||
Cursor::LivePaintBucketFace,
|
||||
Cursor::LivePaintBucketEdge,
|
||||
] {
|
||||
assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}");
|
||||
}
|
||||
@@ -2795,3 +2798,33 @@ fn snap_to_glyph_options_read_set_and_reset() {
|
||||
s.execute("prefs.reset", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
|
||||
}
|
||||
|
||||
/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving
|
||||
/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and
|
||||
/// values change nothing, preferences saved without the group read it as all on, and resetting the
|
||||
/// preferences turns them all back on.
|
||||
#[test]
|
||||
fn pixel_snapping_options_read_set_and_reset() {
|
||||
let mut s = Session::new();
|
||||
let all = json!({"drawing": true, "moving": true, "scaling": true});
|
||||
assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all);
|
||||
let set = json!({"drawing": true, "moving": false, "scaling": true});
|
||||
assert_eq!(s.execute("view.snapToPixel.options", &json!({"moving": false})).unwrap(), set);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pixelSnap"})).unwrap(), set);
|
||||
assert!(!s.prefs.pixel_snap.moving && s.prefs.pixel_snap.drawing && s.prefs.pixel_snap.scaling);
|
||||
for bad in [json!({"moving": 1}), json!({"rotating": false})] {
|
||||
assert!(s.execute("view.snapToPixel.options", &bad).is_err(), "{bad}");
|
||||
assert!(s.execute("prefs.set", &json!({"key": "pixelSnap", "value": bad})).is_err(), "{bad}");
|
||||
assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), set, "{bad}");
|
||||
}
|
||||
s.execute("prefs.set", &json!({"key": "pixelSnap", "value": {"scaling": false}})).unwrap();
|
||||
let both = json!({"drawing": true, "moving": false, "scaling": false});
|
||||
assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), both);
|
||||
// Preferences written before the group existed, and a group that names only some options.
|
||||
let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap();
|
||||
assert_eq!(older.pixel_snap, vectorcraft_tools::PixelSnap::default());
|
||||
let partial: Prefs = serde_json::from_value(json!({"pixelSnap": {"drawing": false}})).unwrap();
|
||||
assert_eq!(partial.pixel_snap, vectorcraft_tools::PixelSnap { drawing: false, moving: true, scaling: true });
|
||||
s.execute("prefs.reset", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("view.snapToPixel.options", &json!({})).unwrap(), all);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -25,7 +25,8 @@ pub struct ViewInfo {
|
||||
/// View → Pixel Preview: while it is on, the tools use no Smart Guides.
|
||||
pub pixel_preview: bool,
|
||||
pub show_bbox: bool,
|
||||
/// View → Snap to Pixel: drawing and moving land on whole pixels (points at 72 ppi).
|
||||
/// View → Snap to Pixel: drawing, moving and scaling land on whole pixels (points at 72 ppi),
|
||||
/// each while its Pixel Snapping option (`view.snapToPixel.options`) is on.
|
||||
pub snap_to_pixel: bool,
|
||||
/// View → Snap to Point: picked points (a transform's reference point) land on anchors.
|
||||
pub snap_to_point: bool,
|
||||
@@ -368,6 +369,7 @@ impl Session {
|
||||
// Snap to Grid and Snap to Pixel are exclusive, as in Illustrator; left both on, the grid
|
||||
// wins instead of pixels quietly rounding every drag to whole points (#1816).
|
||||
snap_to_pixel: view.snap_to_pixel && !view.snap_to_grid,
|
||||
pixel_snap: self.prefs.pixel_snap,
|
||||
snap_to_point: view.snap_to_point,
|
||||
snap_tangent: self.prefs.snap_tangent,
|
||||
snap_perpendicular: self.prefs.snap_perpendicular,
|
||||
|
||||
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user