mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Merge main into chore/craft-libs-pin-138ce99
This commit is contained in:
commit
f0031ebe25
70 files changed
+2620
-192
No files matched your search
Generated
+2
@@ -8863,6 +8863,7 @@ name = "vectorcraft-doc"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-i18n",
|
||||
"craft-image-codecs",
|
||||
"craft-stream-codecs",
|
||||
"flate2",
|
||||
@@ -9093,6 +9094,7 @@ dependencies = [
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-effects",
|
||||
"vectorcraft-geom 0.25.1",
|
||||
"vectorcraft-pathops 0.25.1",
|
||||
"vectorcraft-text",
|
||||
]
|
||||
|
||||
|
||||
@@ -29,6 +29,8 @@ craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "138ce9929e
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "138ce9929ea48d055c797f61c042a3c407427d97", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "138ce9929ea48d055c797f61c042a3c407427d97" }
|
||||
# Digits typed in any script in numeric fields (`vectorcraft_doc::units`).
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "138ce9929ea48d055c797f61c042a3c407427d97" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "138ce9929ea48d055c797f61c042a3c407427d97" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
|
||||
@@ -80,7 +80,54 @@ fn a_dialog_is_marked_while_it_shows_and_not_after() {
|
||||
/// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere.
|
||||
fn reveal(path: &str) -> Result<(), String> {
|
||||
explorer_safe(path)?;
|
||||
reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}"))
|
||||
spawn_detached(&mut reveal_command(path)).map(drop).map_err(|e| format!("can't show {path}: {e}"))
|
||||
}
|
||||
|
||||
/// The thread that waits for a process [`spawn_detached`] started; it returns the exit status.
|
||||
pub(crate) type Reaper = std::thread::JoinHandle<std::io::Result<std::process::ExitStatus>>;
|
||||
|
||||
/// Starts `c` without the caller waiting for it. On Windows dropping the `Child` closes its handle,
|
||||
/// so there is no reaper. Elsewhere a thread waits for the process, so it is reaped when it ends
|
||||
/// instead of staying a zombie until the app exits. The thread starts first, so a process is never
|
||||
/// started without a waiter.
|
||||
pub(crate) fn spawn_detached(c: &mut std::process::Command) -> std::io::Result<Option<Reaper>> {
|
||||
#[cfg(windows)]
|
||||
let started = c.spawn().map(|_| None);
|
||||
#[cfg(not(windows))]
|
||||
let started = {
|
||||
let (send, receive) = std::sync::mpsc::channel::<std::process::Child>();
|
||||
let reaper = std::thread::Builder::new().name("process reaper".into()).spawn(move || match receive.recv() {
|
||||
Ok(mut child) => child.wait(),
|
||||
Err(_) => Err(std::io::Error::other("the process did not start")),
|
||||
})?;
|
||||
let child = c.spawn()?;
|
||||
// The reaper holds the receiver until it gets the child, so this send always arrives.
|
||||
let _ = send.send(child);
|
||||
Ok(Some(reaper))
|
||||
};
|
||||
started
|
||||
}
|
||||
|
||||
/// Linux keeps `/proc/<pid>` in state `Z` for a process that ended until its parent waits for it.
|
||||
/// A pid the kernel has given to a new process since is not in state `Z`.
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
#[test]
|
||||
fn a_started_process_is_reaped_once_it_ends() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pid_file = dir.path().join("pid");
|
||||
let mut c = std::process::Command::new("sh");
|
||||
c.arg("-c").arg("echo $$ > \"$1\"; exit 3").arg("sh").arg(&pid_file);
|
||||
let reaper = spawn_detached(&mut c).unwrap().expect("a reaper on Linux");
|
||||
let status = reaper.join().unwrap().unwrap();
|
||||
let pid = std::fs::read_to_string(&pid_file).unwrap();
|
||||
let pid = pid.trim().to_string();
|
||||
assert!(!pid.is_empty(), "the process wrote its pid");
|
||||
// `/proc/<pid>/stat` is `pid (comm) state ...`; a missing file means the pid is free.
|
||||
let state = std::fs::read_to_string(format!("/proc/{pid}/stat"))
|
||||
.ok()
|
||||
.and_then(|s| s.rsplit_once(") ").and_then(|(_, rest)| rest.split(' ').next().map(str::to_string)));
|
||||
assert_ne!(state.as_deref(), Some("Z"), "process {pid} is still a zombie");
|
||||
assert_eq!(status.code(), Some(3), "the reaper reads the process's own exit");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -114,14 +161,14 @@ fn open_file_url(url: &str) -> Result<(), String> {
|
||||
webbrowser::open(url).map_err(|e| format!("can't open {url}: {e}"))
|
||||
}
|
||||
|
||||
/// Opens a link with the system's handler, without waiting for it:
|
||||
/// Opens a link with the system's handler, without the caller waiting for it:
|
||||
/// `craft::platform::open::open_external` on macOS and Windows, xdg-open elsewhere ([`link_command`]).
|
||||
pub(crate) fn open_link(url: &str) -> Result<(), String> {
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
let mut c = link_command(url)?;
|
||||
c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
|
||||
c.spawn().map(|_| ()).map_err(|e| format!("can't open {url}: {e}"))
|
||||
spawn_detached(&mut c).map(drop).map_err(|e| format!("can't open {url}: {e}"))
|
||||
}
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
{
|
||||
@@ -265,7 +312,7 @@ fn open_file(path: &str) -> Result<(), String> {
|
||||
let mut c = std::process::Command::new("xdg-open");
|
||||
#[cfg(not(windows))]
|
||||
c.arg(path);
|
||||
c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}"))
|
||||
spawn_detached(&mut c).map(drop).map_err(|e| format!("can't open {path}: {e}"))
|
||||
}
|
||||
|
||||
/// Edit Original with Preferences › File Handling › Use System Defaults for Edit Original off
|
||||
@@ -340,7 +387,7 @@ fn launch_application(app: &std::path::Path, path: &str) -> Result<bool, String>
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
c.spawn().map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display()))
|
||||
spawn_detached(&mut c).map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display()))
|
||||
}
|
||||
|
||||
/// PhotoCraft where it is installed: the first of [`photocraft_candidates`] that is an application.
|
||||
|
||||
@@ -459,21 +459,82 @@ mod system {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = printer;
|
||||
Command::new("open")
|
||||
.arg("x-apple.systempreferences:com.apple.Print-Scan-Settings.extension")
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|e| e.to_string())
|
||||
let mut open = Command::new("open");
|
||||
open.arg("x-apple.systempreferences:com.apple.Print-Scan-Settings.extension");
|
||||
start_first([open]).map(drop).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
{
|
||||
if Command::new("system-config-printer").spawn().is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
let url = printer.map_or_else(|| "http://localhost:631/printers/".to_string(), |p| format!("http://localhost:631/printers/{p}"));
|
||||
Command::new("xdg-open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string())
|
||||
start_first(setup_commands(printer)).map(drop).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands [`setup`] tries in order on Linux and the BSDs: the printer settings app, then the
|
||||
/// CUPS web page for `printer` (or the printer list) in the browser.
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
pub(super) fn setup_commands(printer: Option<&str>) -> [Command; 2] {
|
||||
let url = printer.map_or_else(|| "http://localhost:631/printers/".to_string(), |p| format!("http://localhost:631/printers/{p}"));
|
||||
let mut open = Command::new("xdg-open");
|
||||
open.arg(url);
|
||||
[Command::new("system-config-printer"), open]
|
||||
}
|
||||
|
||||
/// Starts the first of `commands` that starts, through [`crate::host_services::spawn_detached`], so
|
||||
/// it is reaped when it ends. Returns the last error when none starts.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn start_first(commands: impl IntoIterator<Item = Command>) -> std::io::Result<Option<crate::host_services::Reaper>> {
|
||||
let mut last = std::io::Error::other("no command to start");
|
||||
for mut c in commands {
|
||||
match crate::host_services::spawn_detached(&mut c) {
|
||||
Ok(reaper) => return Ok(reaper),
|
||||
Err(e) => last = e,
|
||||
}
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux keeps `/proc/<pid>` in state `Z` for a process that ended until its parent waits for it.
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
mod setup_tests {
|
||||
use super::system::{setup_commands, start_first};
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn printer_setup_tries_the_settings_app_then_the_cups_page() {
|
||||
let [app, page] = setup_commands(Some("Office Laser"));
|
||||
assert_eq!(app.get_program(), "system-config-printer");
|
||||
assert_eq!(app.get_args().count(), 0);
|
||||
assert_eq!(page.get_program(), "xdg-open");
|
||||
assert_eq!(page.get_args().collect::<Vec<_>>(), ["http://localhost:631/printers/Office Laser"]);
|
||||
let [_, list] = setup_commands(None);
|
||||
assert_eq!(list.get_args().collect::<Vec<_>>(), ["http://localhost:631/printers/"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_settings_fallback_is_reaped_once_it_ends() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pid_file = dir.path().join("pid");
|
||||
let mut fallback = Command::new("sh");
|
||||
fallback.arg("-c").arg("echo $$ > \"$1\"; exit 3").arg("sh").arg(&pid_file);
|
||||
let reaper = start_first([Command::new("vectorcraft-no-such-program"), fallback]).unwrap().expect("a reaper on Linux");
|
||||
let status = reaper.join().unwrap().unwrap();
|
||||
assert_eq!(status.code(), Some(3), "the fallback ran after the missing program");
|
||||
let pid = std::fs::read_to_string(&pid_file).unwrap();
|
||||
let pid = pid.trim();
|
||||
assert!(!pid.is_empty(), "the process wrote its pid");
|
||||
let state = std::fs::read_to_string(format!("/proc/{pid}/stat"))
|
||||
.ok()
|
||||
.and_then(|s| s.rsplit_once(") ").and_then(|(_, rest)| rest.split(' ').next().map(str::to_string)));
|
||||
assert_ne!(state.as_deref(), Some("Z"), "process {pid} is still a zombie");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_no_command_starting_the_last_error_is_returned() {
|
||||
// A missing program fails with NotFound; a directory fails with PermissionDenied.
|
||||
let err = start_first([Command::new("vectorcraft-no-such-program"), Command::new("/")]).unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
|
||||
@@ -34,6 +34,8 @@ serde_json = { workspace = true }
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
thiserror = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# Field text in Devanagari, Gujarati and other Unicode digits (`units`).
|
||||
craft-i18n = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
flate2 = { workspace = true }
|
||||
|
||||
@@ -180,7 +180,7 @@ 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, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number};
|
||||
pub use units::{ColorMode, Unit, arithmetic_signs, ascii_digits, ascii_digits_one_number, decimal_point, finite_in_every_unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
|
||||
+96
-5
@@ -25,6 +25,16 @@ fn ends(segs: &[PathSeg]) -> Option<[(Point, Vec2); 2]> {
|
||||
Some([(first.start(), -tangent(first, 0.0)), (last.end(), tangent(last, 1.0))])
|
||||
}
|
||||
|
||||
/// `out` grown to take in the corners of the projecting caps, reaching `side` past each end of the
|
||||
/// open subpath `segs`.
|
||||
fn square_corners(mut out: Rect, segs: &[PathSeg], side: f64) -> Rect {
|
||||
for (at, dir) in ends(segs).into_iter().flatten() {
|
||||
let n = Vec2::new(-dir.y, dir.x) * side;
|
||||
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The joints between consecutive segments (and, `closed`, where the subpath closes): the point
|
||||
/// and the unit tangents in and out.
|
||||
fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator<Item = (Point, Vec2, Vec2)> + '_ {
|
||||
@@ -263,6 +273,9 @@ impl StrokeLayer {
|
||||
// box needed.
|
||||
let even_only = !subs.iter().any(|s| self.stops_at_corners(s.1));
|
||||
let mut even = even_only.then_some(bounds);
|
||||
// Tip-aligned arrowheads shorten the line, and its caps sit on the shortened ends.
|
||||
let pieces = crate::arrow::stroke_pieces(bp, self);
|
||||
let shortened = matches!(pieces.line, std::borrow::Cow::Owned(_));
|
||||
for (r, closed) in subs {
|
||||
let side = self.side_reach(closed);
|
||||
let butt = self.cap == LineCap::Butt && !closed;
|
||||
@@ -309,14 +322,40 @@ impl StrokeLayer {
|
||||
} else if !even_only {
|
||||
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
|
||||
}
|
||||
if square {
|
||||
for (at, dir) in ends(&segs).into_iter().flatten() {
|
||||
let n = Vec2::new(-dir.y, dir.x) * side;
|
||||
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
|
||||
if square && !shortened {
|
||||
out = square_corners(out, &segs, side);
|
||||
}
|
||||
}
|
||||
if shortened && self.cap == LineCap::Square {
|
||||
let line = pieces.line.elements();
|
||||
// The renderer aligns the stroke along every subpath by whether the path ends closed.
|
||||
let side = self.side_reach(matches!(bp.elements().last(), Some(vectorcraft_geom::PathEl::ClosePath)));
|
||||
for (r, closed) in subpaths(&pieces.line) {
|
||||
if side <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
if closed {
|
||||
// A closed subpath with no length, a lone anchor included, paints the dot at the
|
||||
// whole path's reach when the stroke draws dots.
|
||||
if !self.draws_dots() || vectorcraft_geom::kurbo::segments(line[r.clone()].iter().copied()).any(|s| has_length(&s)) {
|
||||
continue;
|
||||
}
|
||||
let lone = line[r.start].end_point().map(|p| Rect::from_points(p, p));
|
||||
let dot = segments(&line[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone);
|
||||
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
|
||||
continue;
|
||||
}
|
||||
let segs = drawn(&line[r.clone()]);
|
||||
if segs.is_empty() {
|
||||
// A trim that leaves no length still paints the caps' dot.
|
||||
let dot = segments(&line[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
|
||||
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
|
||||
} else {
|
||||
out = square_corners(out, &segs, side);
|
||||
}
|
||||
}
|
||||
}
|
||||
for head in crate::arrow::stroke_pieces(bp, self).heads {
|
||||
for head in pieces.heads {
|
||||
if !head.outline.elements().is_empty() {
|
||||
out = out.union(head.outline.bounding_box());
|
||||
}
|
||||
@@ -710,6 +749,58 @@ mod tests {
|
||||
assert_eq!(bounds.x1, b.x1, "the end has no head and a butt cap");
|
||||
}
|
||||
|
||||
/// A Tip-aligned arrowhead shortens the line, and the projecting cap sits on the shortened end:
|
||||
/// the box takes in that cap's corners, and not the corners a cap on the path's own end would have.
|
||||
#[test]
|
||||
fn projecting_caps_under_tip_aligned_arrowheads_sit_on_the_shortened_ends() {
|
||||
let l = line();
|
||||
let b = l.bounding_box();
|
||||
let st = stroke(10.0, |s| {
|
||||
s.cap = LineCap::Square;
|
||||
s.join = LineJoin::Bevel;
|
||||
s.end_arrow = Some(Arrowhead::Triangle);
|
||||
s.arrow_align = ArrowAlign::Tip;
|
||||
});
|
||||
let pieces = crate::arrow::stroke_pieces(&l, &st);
|
||||
let segs = drawn(pieces.line.elements());
|
||||
let [_, (at, dir)] = ends(&segs).unwrap_or_else(|| panic!("the arrowhead covers the whole line"));
|
||||
assert!(at.x < 95.0 && (dir.x - 1.0).abs() < 1e-9, "{at:?} {dir:?}");
|
||||
let bounds = st.bounds_on(&l, b);
|
||||
let n = Vec2::new(-dir.y, dir.x) * 5.0;
|
||||
for corner in [at + dir * 5.0 + n, at + dir * 5.0 - n] {
|
||||
assert!(bounds.inflate(1e-9, 1e-9).contains(corner), "{corner:?} outside {bounds:?}");
|
||||
}
|
||||
// Nothing is painted right of the head's tip at x = 100; a cap on the path's own end would
|
||||
// reach to x = 105.
|
||||
let head = pieces.heads.iter().map(|h| h.outline.bounding_box()).reduce(|a, h| a.union(h));
|
||||
assert_eq!(head.map(|h| h.x1), Some(100.0));
|
||||
assert_eq!(bounds.x1, 100.0, "{bounds:?}");
|
||||
// The start has no head, and its cap projects 5 in front of it.
|
||||
assert_eq!(bounds.x0, -5.0, "{bounds:?}");
|
||||
}
|
||||
|
||||
/// A closed lone anchor in a path that ends open is painted as a dot at the whole path's reach,
|
||||
/// so the box takes it in when a Tip-aligned arrowhead moves the start cap off that anchor.
|
||||
#[test]
|
||||
fn closed_lone_anchors_keep_their_dot_under_tip_aligned_arrowheads() {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
p.line_to((100.0, 0.0));
|
||||
p.move_to((0.0, 0.0));
|
||||
p.close_path();
|
||||
p.move_to((110.0, 0.0));
|
||||
p.line_to((120.0, 0.0));
|
||||
let st = stroke(10.0, |s| {
|
||||
s.cap = LineCap::Square;
|
||||
s.join = LineJoin::Bevel;
|
||||
s.align = StrokeAlign::Inside;
|
||||
s.start_arrow = Some(Arrowhead::Triangle);
|
||||
s.arrow_align = ArrowAlign::Tip;
|
||||
});
|
||||
let bounds = st.bounds_on(&p, p.bounding_box());
|
||||
assert_eq!(bounds.x0, -5.0, "the lone anchor's square dot reaches 5 left of it: {bounds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangles_keep_exact_bounds_and_sharp_corners_spike_up_to_the_limit() {
|
||||
let sq = square();
|
||||
|
||||
@@ -303,3 +303,43 @@ fn format_area_formats_and_trims_cleanly() {
|
||||
assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²");
|
||||
}
|
||||
|
||||
/// Typed in Devanagari or Gujarati digits, a field value reads as its ASCII spelling does:
|
||||
/// plain numbers, units, picas, arithmetic, percentages and a decimal comma.
|
||||
#[test]
|
||||
fn hindi_and_gujarati_digits_read_as_ascii_digits_do() {
|
||||
let ascii = ["12", "12.5 mm", "-3in", "2p6", "45*2", "10x2 mm", "100pt+25%", "1080/2 px", "13q"];
|
||||
let hindi = ["१२", "१२.५ mm", "-३in", "२p६", "४५*२", "१०x२ mm", "१००pt+२५%", "१०८०/२ px", "१३q"];
|
||||
let gujarati = ["૧૨", "૧૨.૫ mm", "-૩in", "૨p૬", "૪૫*૨", "૧૦x૨ mm", "૧૦૦pt+૨૫%", "૧૦૮૦/૨ px", "૧૩q"];
|
||||
for ((a, h), g) in ascii.iter().zip(hindi).zip(gujarati) {
|
||||
let want = Unit::Millimeters.parse(a);
|
||||
assert!(want.is_some(), "`{a}` should read");
|
||||
assert_eq!(Unit::Millimeters.parse(h), want, "`{h}` vs `{a}`");
|
||||
assert_eq!(Unit::Millimeters.parse(g), want, "`{g}` vs `{a}`");
|
||||
}
|
||||
assert_eq!(crate::parse_number("४५*२"), crate::parse_number("45*2"));
|
||||
assert_eq!(crate::parse_number("૪૫x૨"), crate::parse_number("45x2"));
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("०,५ mm"), Unit::Millimeters.parse("0.5 mm"));
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("૦,૫"), Unit::Millimeters.parse("0.5"));
|
||||
}
|
||||
|
||||
/// A grouped thousand is refused in any digits, as `1,000` is, rather than read as 1.
|
||||
#[test]
|
||||
fn a_native_digit_thousand_is_refused_like_an_ascii_one() {
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("1,000 mm"), None);
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("१,००० mm"), None);
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("૧,૦૦૦"), None);
|
||||
assert_eq!(crate::decimal_point("१,०००"), crate::decimal_point("1,000"));
|
||||
}
|
||||
|
||||
/// One number mixing digit sets is refused, as craft-i18n's `parse_number` refuses it; separate
|
||||
/// numbers of a sum may each use their own.
|
||||
#[test]
|
||||
fn a_number_mixing_digit_sets_reads_as_nothing() {
|
||||
for text in ["1२", "૧२", "१.5", "૧२.૫ mm", "1,२"] {
|
||||
assert_eq!(Unit::Points.parse(text), None, "`{text}`");
|
||||
assert_eq!(Unit::Points.parse_with_decimal_comma(text), None, "`{text}`");
|
||||
assert_eq!(crate::parse_number(text), None, "`{text}`");
|
||||
}
|
||||
assert_eq!(Unit::Points.parse("१२+3"), Unit::Points.parse("12+3"));
|
||||
}
|
||||
+32
-8
@@ -1,3 +1,5 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
/// Measurement units (display only; the model is always in points).
|
||||
@@ -203,20 +205,24 @@ impl Unit {
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs ([`arithmetic_signs`], a multiplication sign counted
|
||||
/// as `*`) reads as nothing.
|
||||
///
|
||||
/// Digits may be any Unicode 16 decimal digits ([`ascii_digits`]): `१२ mm` is `12 mm`, `૪૫*૨` is `45*2`.
|
||||
pub fn parse(self, s: &str) -> Option<f64> {
|
||||
if arithmetic_signs(s) > MAX_MEASURE_OPERATORS {
|
||||
return None;
|
||||
}
|
||||
parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
let s = ascii_digits(s)?;
|
||||
parse_measure(×_as_asterisks(&s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
|
||||
/// number that looks like a grouped integer, even when it is part of an expression.
|
||||
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
|
||||
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
|
||||
let text = ascii_digits(text)?;
|
||||
if text.contains(',') && times_as_asterisks(&text).split(['+', '-', '*', '/']).any(thousands_operand) {
|
||||
return None;
|
||||
}
|
||||
self.parse(&decimal_point(text))
|
||||
self.parse(&decimal_point(&text))
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
@@ -414,9 +420,26 @@ fn percent(s: &str) -> Option<f64> {
|
||||
/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed
|
||||
/// after the value the field shows) is 100 mm (#5684). A number written with both separators has
|
||||
/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a
|
||||
/// number that reads as thousands ([`thousands`]).
|
||||
pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
|
||||
/// number that reads as thousands ([`thousands`]). Digits in other scripts come back as ASCII
|
||||
/// ([`ascii_digits`]), so `१,०००` is refused as `1,000` is; text mixing digit sets in one number
|
||||
/// comes back as it is, for the parser to refuse.
|
||||
pub fn decimal_point(text: &str) -> Cow<'_, str> {
|
||||
let Some(text) = ascii_digits(text) else { return text.into() };
|
||||
if text.contains(',') && !thousands(&text) { text.replace(',', ".").into() } else { text }
|
||||
}
|
||||
|
||||
/// `text` with every Unicode 16 decimal digit (Devanagari `०-९`, Gujarati `૦-૯`, Bengali,
|
||||
/// Arabic-Indic, full-width, …) written as its ASCII digit, so `१२.५ mm` reads as `12.5 mm`. A
|
||||
/// number here is a run of digits, `.` and `,`, and must use one digit set: `1२` and `૧२` are
|
||||
/// `None`. Operators, unit suffixes and other characters are left as they are.
|
||||
pub fn ascii_digits(text: &str) -> Option<Cow<'_, str>> {
|
||||
craft_i18n::ascii_digits(text, |c| matches!(c, '.' | ',')).ok()
|
||||
}
|
||||
|
||||
/// [`ascii_digits`] for text that holds a single number, exponent and unit included: every digit
|
||||
/// must come from one set, so `१e२` is `1e2` and `१e2` is `None`.
|
||||
pub fn ascii_digits_one_number(text: &str) -> Option<Cow<'_, str>> {
|
||||
craft_i18n::ascii_digits(text, |_| true).ok()
|
||||
}
|
||||
|
||||
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
|
||||
@@ -455,9 +478,10 @@ pub fn finite_in_every_unit(pt: f64) -> bool {
|
||||
}
|
||||
|
||||
/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as
|
||||
/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as
|
||||
/// nothing.
|
||||
/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`, `४५*२`); text other than digits, `.` and operators
|
||||
/// reads as nothing.
|
||||
pub fn parse_number(s: &str) -> Option<f64> {
|
||||
let s = ascii_digits(s)?;
|
||||
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -717,7 +717,6 @@ impl PixelFx {
|
||||
PixelFx::Charcoal { thickness, detail, .. } => Some(sketch_ink::charcoal_reach(thickness, detail)),
|
||||
PixelFx::Photocopy { detail, .. } => Some(sketch_ink::copy_reach(detail)),
|
||||
PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)),
|
||||
PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)),
|
||||
// The cells around the pixel's, and the cells around theirs.
|
||||
// (Without a usable grid there are no dots: see `pixelate::color_halftone`.)
|
||||
PixelFx::ColorHalftone { max_radius, .. } => {
|
||||
@@ -740,8 +739,9 @@ impl PixelFx {
|
||||
PixelFx::WaterPaper { fiber_length, .. } => {
|
||||
Some(sketch::water_paper_shift(fiber_length) + 3.0 * (0.06 * fiber_length.clamp(3.0, 50.0)).max(0.35))
|
||||
}
|
||||
// Cutout's palette and Torn Edges' peak-normalised edges come from the whole object.
|
||||
PixelFx::Cutout { .. } | PixelFx::TornEdges { .. } => None,
|
||||
// Cutout's palette and the peak-normalized edges of Torn Edges and Glowing Edges come
|
||||
// from the whole object.
|
||||
PixelFx::Cutout { .. } | PixelFx::TornEdges { .. } | PixelFx::GlowingEdges { .. } => None,
|
||||
// The softened tones around the pixel.
|
||||
PixelFx::NeonGlow { size, .. } => Some(3.0 * artistic::glow_spread(size)),
|
||||
PixelFx::PlasticWrap { smoothness, .. } => Some(artistic::plastic_reach(smoothness)),
|
||||
|
||||
@@ -184,6 +184,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
BuiltinBrushLibrary { id: "impact-bursts", name: "Impact Bursts", make: impact_bursts },
|
||||
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
|
||||
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
|
||||
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
|
||||
@@ -1216,6 +1217,70 @@ pub(crate) fn dry_media() -> BrushLibrary {
|
||||
built("Dry Media", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// Impact Bursts: art brushes for hit sparks, shocks and crack strokes (original game VFX art).
|
||||
fn impact_bursts() -> BrushLibrary {
|
||||
let star = group(vec![
|
||||
black(polygon(&[(0.0, 0.0), (100.0, -8.0), (88.0, 0.0), (100.0, 8.0)])),
|
||||
black(polygon(&[(12.0, 0.0), (70.0, -14.0), (62.0, 0.0), (70.0, 14.0)])),
|
||||
black(polygon(&[(20.0, 0.0), (48.0, -18.0), (42.0, 0.0), (48.0, 18.0)])),
|
||||
black(polygon(&[(28.0, 0.0), (40.0, -10.0), (36.0, 0.0), (40.0, 10.0)])),
|
||||
]);
|
||||
let ring_shock =
|
||||
group(vec![ring(Point::new(50.0, 0.0), 18.0, 14.0), ring(Point::new(50.0, 0.0), 28.0, 25.0), ring(Point::new(50.0, 0.0), 38.0, 36.0)]);
|
||||
let slash = {
|
||||
let n = 40;
|
||||
let half = |x: f64| {
|
||||
let t = x / 100.0;
|
||||
let arch = 10.0 * (t * std::f64::consts::PI).sin();
|
||||
1.4 + 2.2 * (1.0 - (t - 0.5).abs() * 2.0).max(0.0) + arch * 0.05
|
||||
};
|
||||
let mid = |x: f64| 8.0 * ((x / 100.0) * std::f64::consts::PI).sin() - 4.0;
|
||||
let xs = |i: usize| 100.0 * i as f64 / n as f64;
|
||||
let mut pts: Vec<Point> = (0..=n).map(xs).map(|x| Point::new(x, mid(x) - half(x))).collect();
|
||||
pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, mid(x) + half(x))));
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
};
|
||||
let spark_fan = group(vec![
|
||||
black(polygon(&[(0.0, 0.0), (55.0, -16.0), (48.0, -12.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (70.0, -6.0), (62.0, -2.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (100.0, 0.0), (90.0, 2.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (70.0, 6.0), (62.0, 2.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (55.0, 16.0), (48.0, 12.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (35.0, -10.0), (30.0, -6.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (35.0, 10.0), (30.0, 6.0)])),
|
||||
]);
|
||||
let debris = group(vec![
|
||||
black(shapes::rectangle(Rect::new(4.0, -3.0, 12.0, 1.0))),
|
||||
black(polygon(&[(18.0, 2.0), (28.0, -2.0), (30.0, 4.0)])),
|
||||
black(shapes::rectangle(Rect::new(36.0, -4.0, 44.0, -1.0))),
|
||||
black(polygon(&[(50.0, 1.0), (58.0, 5.0), (62.0, -2.0)])),
|
||||
black(shapes::rectangle(Rect::new(68.0, -2.0, 78.0, 2.0))),
|
||||
black(polygon(&[(82.0, -4.0), (90.0, -1.0), (88.0, 3.0)])),
|
||||
black(shapes::rectangle(Rect::new(92.0, 0.0, 100.0, 3.0))),
|
||||
]);
|
||||
let crack = band(100.0, 1.4, 48, |x| {
|
||||
let t = (x / 8.0).floor();
|
||||
let local = (x / 8.0) - t;
|
||||
let amp = if (t as i32) % 3 == 0 {
|
||||
5.0
|
||||
} else if (t as i32) % 3 == 1 {
|
||||
-3.5
|
||||
} else {
|
||||
2.0
|
||||
};
|
||||
if (t as i32) % 2 == 0 { amp * local } else { amp * (1.0 - local) }
|
||||
});
|
||||
let brushes = vec![
|
||||
art("Star Burst", star, Colorization::Tints),
|
||||
art("Ring Shock", ring_shock, Colorization::Tints),
|
||||
art("Slash Arc", black(slash), Colorization::Tints),
|
||||
art("Spark Fan", spark_fan, Colorization::Tints),
|
||||
art("Debris Spray", debris, Colorization::Tints),
|
||||
art("Crack Line", black(crack), Colorization::Tints),
|
||||
];
|
||||
built("Impact Bursts", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
|
||||
|
||||
@@ -835,6 +835,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
@@ -873,6 +874,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
|
||||
@@ -573,6 +573,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
|
||||
| "dwg"
|
||||
| "emf"
|
||||
| "wmf"
|
||||
| "pict"
|
||||
| "hpgl"
|
||||
| "ai"
|
||||
)
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), 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)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|pict|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), 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)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -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|cmx|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: of the layers the file draws, 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, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), 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, units, 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 art it plots, without placed images, unpainted paths and art at 0% opacity), 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), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chos
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|pict|hpgl|tiff|bmp|tga|psd|cmx|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: of the layers the file draws, 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, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), 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, units, 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), …pict writes a QuickDraw version 2 picture (.pct) of the artboard as emf and wmf do (up to 16 device units a point; at most 32,767 points on a side; fills as polygons, strokes as their filled outlines and images over white; what it 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 art it plots, without placed images, unpainted paths and art at 0% opacity), 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 alik
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), 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), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|pict|hpgl|cmx|vectorcraft|template (default: from the extension, else png), 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), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
|
||||
@@ -1094,7 +1094,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
|
||||
// themselves: SVG only when it outlines or embeds fonts).
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx"))
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "pict" | "hpgl" | "cmx"))
|
||||
&& let Some(w) = crate::cmd::fonts::substitution_warning(doc)
|
||||
{
|
||||
enc.warnings.push(w);
|
||||
@@ -1136,7 +1136,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards =
|
||||
if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "pict" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -1181,6 +1181,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"eps" => return super::eps::encode(doc, p),
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
"wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf),
|
||||
"pict" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Pict),
|
||||
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
|
||||
"cmx" => return super::cmx::encode(doc, f, p, use_artboards),
|
||||
"ai" => return super::save::encode_ai(C, f, doc, p),
|
||||
|
||||
@@ -575,8 +575,18 @@ pub const FORMATS: &[Format] = &[
|
||||
// `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for
|
||||
// each chosen artboard, with the art's fills and strokes in their colors.
|
||||
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images,
|
||||
// and written by `vectorcraft_metafile::export` as version 2 pictures (`.pct`).
|
||||
Format {
|
||||
id: "pict",
|
||||
label: "PICT",
|
||||
extensions: &["pct", "pic", "pict"],
|
||||
mime: "image/x-pict",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: metafile::OPTIONS,
|
||||
},
|
||||
// Binary Computer Graphics Metafiles, read by `vectorcraft_metafile::import_cgm` into paths,
|
||||
// type and images. Behind the `cgm` feature until craft-libs#5410 merges.
|
||||
#[cfg(feature = "cgm")]
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per
|
||||
//! artboard with Use Artboards; raster effects as images, rendered at the document's raster
|
||||
//! effects resolution), `document.open` and File → Place (one artboard, the picture's frame).
|
||||
//! QuickDraw pictures (PICT) and binary Computer Graphics Metafiles (CGM) open and place the same
|
||||
//! way; they are never written.
|
||||
//! QuickDraw pictures (PICT) are written (`format: pict`) and open and place the same way. Binary
|
||||
//! Computer Graphics Metafiles (CGM) open and place the same way; they are never written.
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -14,7 +14,7 @@ use super::{ArtboardPick, Encoded, FormatOption};
|
||||
|
||||
const C: &str = "document.export";
|
||||
|
||||
/// The options `document.formats` lists for EMF and WMF.
|
||||
/// The options `document.formats` lists for EMF, WMF and PICT.
|
||||
pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS];
|
||||
|
||||
/// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one
|
||||
@@ -46,7 +46,7 @@ pub(super) fn encode_flattening(
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?;
|
||||
vectorcraft_metafile::check_regions_for(&rects, kind).map_err(|e| bad(C, e))?;
|
||||
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
|
||||
let flat = flatten(doc);
|
||||
let src = flat.as_ref().unwrap_or(doc);
|
||||
|
||||
@@ -46,9 +46,10 @@ impl ScreenSize {
|
||||
/// `2x` (or `2`), `100w`, `100h` or `72ppi`, in any case; positive numbers only.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
let s = s.trim().to_ascii_lowercase();
|
||||
// Digits and `.` only: `str::parse` would also take `+2`, `1e2`, `inf` and `nan`.
|
||||
// Digits and `.` only: `str::parse` would also take `+2`, `1e2`, `inf` and `nan`. Digits of
|
||||
// other scripts read as ASCII digits do (`"२x"` is `2x`), as number fields read them.
|
||||
let num = |t: &str| {
|
||||
let t = t.trim();
|
||||
let t = vectorcraft_doc::ascii_digits(t.trim())?;
|
||||
if !t.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
|
||||
return None;
|
||||
}
|
||||
@@ -196,7 +197,7 @@ pub(super) fn name_without_device(name: &str) -> String {
|
||||
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
|
||||
|
||||
/// The writable formats a format row can't name.
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 8] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg"];
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 9] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg", "pict"];
|
||||
|
||||
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
|
||||
struct Row {
|
||||
|
||||
@@ -535,6 +535,7 @@ fn export_extensions_name_every_writable_format() {
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx",
|
||||
"pct",
|
||||
"dwg"
|
||||
]
|
||||
);
|
||||
@@ -573,6 +574,7 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx",
|
||||
"pict",
|
||||
"dwg"
|
||||
]
|
||||
);
|
||||
|
||||
@@ -322,9 +322,9 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
#[test]
|
||||
fn pict_and_pagemaker_say_what_to_use_instead() {
|
||||
let mut s = two_boards();
|
||||
// PICT opens; it isn't written.
|
||||
let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string();
|
||||
assert!(e.contains("PICT files can be opened but not written"), "{e}");
|
||||
// PCX opens; it isn't written.
|
||||
let e = s.execute("document.export", &json!({"format": "pcx"})).unwrap_err().to_string();
|
||||
assert!(e.contains("PCX files can be opened but not written"), "{e}");
|
||||
let e = s
|
||||
.execute("document.open", &json!({"name": "old.pct", "dataBase64": vectorcraft_format::base64_encode(&[0u8; 600])}))
|
||||
.unwrap_err()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! PICT pictures through the commands: `document.open` by extension or by content, File › Place as
|
||||
//! one group clipped to the picture's frame, the dialogs' filters and the format list, and files
|
||||
//! that aren't pictures, or a PICT export, refused with a message.
|
||||
//! one group clipped to the picture's frame, `document.export` of one artboard or each, the dialogs'
|
||||
//! filters and the format list, and files that aren't pictures refused with a message.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
@@ -83,8 +83,47 @@ fn files_that_are_not_pictures_are_refused() {
|
||||
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
png.extend(&picture()[8..]);
|
||||
assert!(detect("x.png", &png).is_none_or(|f| f.id != "pict"));
|
||||
let e = s.execute("document.export", &json!({"format": "pict"})).expect_err("refused").to_string();
|
||||
assert!(e.contains("PICT files can be opened but not written"), "{e}");
|
||||
}
|
||||
|
||||
fn data(r: &serde_json::Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_export_writes_a_picture_that_opens_again() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 5, "width": 20, "height": 10})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "pict"})).unwrap();
|
||||
assert_eq!((r["format"].as_str(), &r["warnings"]), (Some("pict"), &json!([])), "{r}");
|
||||
let bytes = data(&r);
|
||||
assert_eq!(detect("x.bin", &bytes).map(|f| f.id), Some("pict"));
|
||||
assert_eq!(writable_format(None, Some("x/logo.pct")).unwrap().id, "pict");
|
||||
// The first artboard: its red rectangle, in place.
|
||||
let mut back = Session::new();
|
||||
back.execute("document.open", &json!({"name": "logo.pct", "dataBase64": b64(&bytes)})).unwrap();
|
||||
let doc = &back.doc().unwrap().doc;
|
||||
assert_eq!(doc.artboards[0].rect.size(), (100.0, 100.0).into());
|
||||
let mut paths = vec![];
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
paths.push(n.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1);
|
||||
let b = paths[0].geometric_bounds().unwrap();
|
||||
let want = vectorcraft_geom::Rect::new(10.0, 20.0, 40.0, 60.0);
|
||||
assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 0.07), "{b:?}");
|
||||
assert_eq!(paths[0].appearance.fill().and_then(|f| f.paint.color()).map(|c| c.to_rgba8(1.0)), Some([255, 0, 0, 255]));
|
||||
// Use Artboards: one picture each.
|
||||
let r = s.execute("document.export", &json!({"format": "pict", "useArtboards": true})).unwrap();
|
||||
let files = r["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 2);
|
||||
assert!(files[1]["name"].as_str().unwrap().ends_with("-Artboard-2.pct"), "{files:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -98,7 +137,6 @@ fn the_dialogs_and_the_format_list_name_pict() {
|
||||
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
|
||||
let r = Session::new().execute("document.formats", &json!({})).unwrap();
|
||||
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pict").unwrap().clone();
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}");
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(true), Some(false)), "{f}");
|
||||
assert_eq!(f["mime"], "image/x-pict");
|
||||
assert!(writable_format(None, Some("x/logo.pct")).is_err());
|
||||
}
|
||||
@@ -72,6 +72,17 @@ fn sizes_parse_as_factor_width_height_or_resolution() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_read_digits_of_other_scripts() {
|
||||
assert_eq!(ScreenSize::parse("२x"), Some(ScreenSize::Scale(2.0)));
|
||||
assert_eq!(ScreenSize::parse("૧૦૦W"), Some(ScreenSize::Width(100.0)));
|
||||
assert_eq!(ScreenSize::parse("१४४ppi"), Some(ScreenSize::Ppi(144.0)));
|
||||
// One digit set per number, and the same grammar as ASCII digits.
|
||||
for bad in ["1२x", "१.5x", "-२x", "०w"] {
|
||||
assert_eq!(ScreenSize::parse(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_width_or_height_row_gives_that_many_pixels() {
|
||||
let mut s = session(1);
|
||||
|
||||
@@ -461,6 +461,7 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
crate::cmd::distortcmds::finish_edit_text(st, inner);
|
||||
st.isolation = Some(layer);
|
||||
st.selection.set([left]);
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
st.revision += 1;
|
||||
return ok();
|
||||
}
|
||||
@@ -498,6 +499,7 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
crate::cmd::distortcmds::finish_edit_text(st, i);
|
||||
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
|
||||
st.selection.set([target]);
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
// A guide path isolated while Lock Guides is on isn't selected (#1534).
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// The art on a locked artboard can't be selected.
|
||||
|
||||
@@ -71,7 +71,11 @@ fn resolution(v: &Value) -> Result<f64> {
|
||||
"screen" => 72.0,
|
||||
"medium" => 150.0,
|
||||
"high" => 300.0,
|
||||
other => other.trim_end_matches("ppi").trim().parse::<f64>().map_err(|_| bad(C, format!("unknown resolution `{v}`")))?,
|
||||
// Digits of other scripts read as ASCII digits do (`"३००"` is 300), as number fields read them,
|
||||
// with one digit set for the whole value, exponent included (`"१e2"` is refused).
|
||||
other => vectorcraft_doc::ascii_digits_one_number(other.trim_end_matches("ppi").trim())
|
||||
.and_then(|n| n.parse::<f64>().ok())
|
||||
.ok_or_else(|| bad(C, format!("unknown resolution `{v}`")))?,
|
||||
},
|
||||
v => v.as_f64().ok_or_else(|| bad(C, "resolution must be a number or screen|medium|high"))?,
|
||||
};
|
||||
|
||||
@@ -51,6 +51,9 @@ pub struct DocState {
|
||||
/// Increments on every change (also selection and view-only changes); UIs re-render when it
|
||||
/// moves. Not a dirty flag: see [`DocState::is_dirty`].
|
||||
pub revision: u64,
|
||||
/// Increments each time the selection is set through [`crate::Session::select`] and the other
|
||||
/// selection entries, even when it ends as it was. Not saved, not undoable.
|
||||
pub selections: u64,
|
||||
/// The document as last saved (or opened). Structural sharing makes "unchanged" a pointer
|
||||
/// comparison, and undoing back to the saved state counts as clean.
|
||||
pub(crate) saved_doc: Arc<Document>,
|
||||
@@ -544,6 +547,7 @@ impl DocState {
|
||||
history: History { limit: 500, ..Default::default() },
|
||||
path,
|
||||
revision: 1,
|
||||
selections: 0,
|
||||
active_layer,
|
||||
layer_rows: vec![],
|
||||
layers_reveal: None,
|
||||
|
||||
@@ -108,6 +108,8 @@ pub struct Session {
|
||||
/// ([`Session::painting_tool`]); None for a stop of the selection's paint. A pick armed for
|
||||
/// such a stop samples only into a stop selected on that gradient, and otherwise ends.
|
||||
pub(crate) stop_pick: Option<cmd::gradient::StopOwner>,
|
||||
/// The point and document revision the Eyedropper was armed for.
|
||||
freeform_point_pick: Option<tooling::FreeformPointPick>,
|
||||
/// Pointer and key input that came while the tool computed an edit on another thread, each with
|
||||
/// its number and view, made in order once the edit is applied.
|
||||
held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>,
|
||||
|
||||
@@ -64,6 +64,7 @@ impl Session {
|
||||
lender: None,
|
||||
back_to_painter: None,
|
||||
stop_pick: None,
|
||||
freeform_point_pick: None,
|
||||
held_input: Default::default(),
|
||||
input_count: 0,
|
||||
edit_started_by: None,
|
||||
|
||||
@@ -252,8 +252,64 @@ impl Session {
|
||||
|
||||
fn select_unwatched(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
|
||||
self.active_appearance_item = None;
|
||||
let uid = self.doc()?.uid;
|
||||
self.select_document_unwatched(uid, f)
|
||||
}
|
||||
|
||||
/// Change the selection in an open document without switching the active document.
|
||||
pub fn select_in_document(&mut self, uid: u64, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
|
||||
if self.active().is_some_and(|st| st.uid == uid) {
|
||||
return self.select(f);
|
||||
}
|
||||
self.select_document_unwatched(uid, f)
|
||||
}
|
||||
|
||||
/// Give document `uid` back a selection it had, new art included, through the selection
|
||||
/// filters as they are now: guides locked since, hidden or locked slices and art on a locked
|
||||
/// artboard that is not new art are left out. In the active document, outside a command and an
|
||||
/// interaction, the journal records the selection that comes back, with the current layer kept,
|
||||
/// in the open undo groups too, and the paints for new art load from it as `select.set` loads
|
||||
/// them (with New Art Has Basic Appearance on, a symbol part or an Objects on Path member does
|
||||
/// not load its paints, as `symbol.instance.selectPart` and
|
||||
/// `object.objectsOnPath.selectMember` do not), so a recorded action replays as it ran.
|
||||
pub fn restore_selection(&mut self, uid: u64, selection: Selection) -> Result<()> {
|
||||
let active = self.active().is_some_and(|st| st.uid == uid && st.interaction.is_none()) && self.depth == 0;
|
||||
let st = self.document_mut(uid).ok_or(EngineError::NoDocument)?;
|
||||
let (made, layer) = (st.selection.clone(), st.active_layer);
|
||||
st.selection_record = None;
|
||||
st.selection = selection;
|
||||
self.select_in_document(uid, |_, _| {})?;
|
||||
if !active {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(st) = self.document_mut(uid) else { return Ok(()) };
|
||||
if st.selection == made {
|
||||
return Ok(());
|
||||
}
|
||||
let steps = selection_steps(&st.selection, &made, &st.doc, layer, &st.highlighted_rows());
|
||||
// Only the selection commands load paints on replay: a symbol part comes back through
|
||||
// `symbol.instance.selectPart` and an Objects on Path member through
|
||||
// `object.objectsOnPath.selectMember`, which load none.
|
||||
let loads = steps.iter().any(|(id, _)| id.starts_with("select.") || id == "layer.target");
|
||||
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
|
||||
for step in steps {
|
||||
self.journal.push(step);
|
||||
}
|
||||
self.journal_in_undo_groups(Some(uid), &grouped, from);
|
||||
// As `Session::execute` does after a selection command, which starts without the marker
|
||||
// of a defaults-only paint that ran before it.
|
||||
self.defaults_only_ran = None;
|
||||
self.inherit_new_art();
|
||||
if loads {
|
||||
self.load_selection_paints();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply the selection filters and update the editing state of document `uid`.
|
||||
fn select_document_unwatched(&mut self, uid: u64, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
|
||||
let menu = self.menu.clone();
|
||||
let st = self.doc_mut()?;
|
||||
let st = self.document_mut(uid).ok_or(EngineError::NoDocument)?;
|
||||
let before = st.selection.objects.clone();
|
||||
let new_art = st.selection.new_art.clone();
|
||||
let record = if st.selection_record().is_some() { st.selection_record.take() } else { None };
|
||||
@@ -294,6 +350,7 @@ impl Session {
|
||||
st.layer_rows.clear();
|
||||
}
|
||||
st.revision += 1;
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
// Puppet Warp pins belong to the art they were placed on: another selection starts afresh.
|
||||
if st.doc.puppet.as_ref().is_some_and(|p| p.ids != st.selection.objects) {
|
||||
cmd::distortcmds::drop_puppet_pins(st);
|
||||
|
||||
@@ -24,6 +24,16 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
|
||||
r
|
||||
}
|
||||
|
||||
/// What [`Session::execute`] compares to tell that a command changed the selection: the counts of
|
||||
/// what is selected and the first and last object, guide and slice, read in constant time.
|
||||
type SelectionSummary = ([usize; 5], [Option<NodeId>; 6], bool);
|
||||
|
||||
fn selection_summary(s: &Selection) -> SelectionSummary {
|
||||
let counts = [s.objects.len(), s.anchors.len(), s.segments.len(), s.guides.len(), s.slices.len()];
|
||||
let ends = [s.objects.first(), s.objects.last(), s.guides.first(), s.guides.last(), s.slices.first(), s.slices.last()].map(|id| id.copied());
|
||||
(counts, ends, s.symbol_part.is_some())
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run a command callback and keep warnings from every preview it settles or restores.
|
||||
pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
@@ -72,7 +82,19 @@ impl Session {
|
||||
if self.plugins_loading() && crate::waits_for_plugin_loads(id) {
|
||||
self.finish_plugin_loads();
|
||||
}
|
||||
self.revealing(|s| s.execute_unwatched(id, params))
|
||||
// A command, a step of a batch included, that leaves the active document with another
|
||||
// selection counts as a selection change ([`crate::DocState::selections`]), whichever way
|
||||
// it wrote the selection. The selections are compared by a summary that takes constant time.
|
||||
let before = self.active().map(|st| (st.uid, st.selections, selection_summary(&st.selection)));
|
||||
let r = self.revealing(|s| s.execute_unwatched(id, params));
|
||||
if let Some((uid, selections, summary)) = before
|
||||
&& let Some(st) = self.document_mut(uid)
|
||||
&& st.selections == selections
|
||||
&& selection_summary(&st.selection) != summary
|
||||
{
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Run `f`, a top-level entry that changes the active document's rows, current layer or
|
||||
@@ -230,7 +252,7 @@ impl Session {
|
||||
params.get("ids").filter(|v| !v.is_null()).cloned().or_else(|| given.map(|ids| ids.iter().map(|i| i.0).collect::<Vec<_>>().into()))
|
||||
})
|
||||
.flatten();
|
||||
let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer));
|
||||
let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer, d.selections));
|
||||
// Only a selection command that changes the selection loads its paints for new art: other
|
||||
// commands, and clicking what is already selected, keep a sampled paint in the proxies.
|
||||
let selection_was = (id.starts_with("select.") || id == "layer.target").then(|| self.active().map(|d| d.selection.clone())).flatten();
|
||||
@@ -240,11 +262,12 @@ impl Session {
|
||||
}
|
||||
let r = cmd::run_spec(s, spec, run_params);
|
||||
if r.is_err()
|
||||
&& let Some((uid, selection, layer)) = selected_before
|
||||
&& let Some((uid, selection, layer, selections)) = selected_before
|
||||
&& let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid)
|
||||
{
|
||||
st.selection = selection;
|
||||
st.active_layer = layer;
|
||||
st.selections = selections;
|
||||
st.revision += 1;
|
||||
}
|
||||
r
|
||||
|
||||
@@ -118,6 +118,7 @@ impl Session {
|
||||
}
|
||||
let undone = std::mem::replace(&mut st.doc, e.doc);
|
||||
st.selection = Arc::unwrap_or_clone(e.selection);
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
deselect_hidden(&self.menu, &st.doc, &mut st.selection);
|
||||
st.restore_isolation(g.isolation, &undone);
|
||||
st.sync_new_art();
|
||||
@@ -276,6 +277,7 @@ impl Session {
|
||||
}
|
||||
let undone = std::mem::replace(&mut st.doc, doc);
|
||||
st.selection = selection;
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
st.restore_isolation(scope.isolation, &undone);
|
||||
cmd::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
|
||||
@@ -121,6 +121,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"game-trails",
|
||||
"energy-beams",
|
||||
"dry-media",
|
||||
"impact-bursts",
|
||||
"tech-circuit",
|
||||
"engraving",
|
||||
"arrows",
|
||||
@@ -171,6 +172,12 @@ fn the_builtin_libraries_list_their_brush_names_and_counts() {
|
||||
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
|
||||
);
|
||||
assert_eq!((entry("dry-media")["name"].as_str(), entry("dry-media")["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
let impact = run(&mut s, "brush.library", json!({"library": "impact-bursts"}));
|
||||
assert_eq!(
|
||||
impact["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
["Star Burst", "Ring Shock", "Slash Arc", "Spark Fan", "Debris Spray", "Crack Line"]
|
||||
);
|
||||
assert_eq!((libs[14]["name"].as_str(), libs[14]["count"].as_u64()), (Some("Impact Bursts"), Some(6)));
|
||||
let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"}));
|
||||
assert_eq!(
|
||||
arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
|
||||
@@ -204,6 +211,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
|
||||
("game-trails", "art"),
|
||||
("energy-beams", "art"),
|
||||
("dry-media", "art"),
|
||||
("impact-bursts", "art"),
|
||||
("arrows", "art"),
|
||||
("image-brush", "scatter"),
|
||||
("artistic", "art"),
|
||||
|
||||
@@ -875,3 +875,30 @@ fn objects_moved_out_together_in_the_layers_panel_all_leave_the_path() {
|
||||
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");
|
||||
}
|
||||
|
||||
/// A restored Objects on Path member keeps the paints for new art as they are, as the journal
|
||||
/// entry that records it (`object.objectsOnPath.selectMember`) does when it is replayed.
|
||||
#[test]
|
||||
fn a_restored_member_leaves_the_same_paints_live_and_on_replay() {
|
||||
let mut s = session();
|
||||
let (g, [a, b, c], _) = three_on_a_line(&mut s);
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0, b.0, c.0, g.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("object.objectsOnPath.selectMember", &json!({"member": b.0})).unwrap();
|
||||
let saved = s.doc().unwrap().selection.clone();
|
||||
let blue = rect(&mut s, 400.0, 0.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [blue.0], "color": "#0000ff"})).unwrap();
|
||||
select(&mut s, &[blue]);
|
||||
let before = s.paint.clone();
|
||||
let (uid, from) = (s.doc().unwrap().uid, s.journal.len());
|
||||
s.restore_selection(uid, saved.clone()).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection, saved);
|
||||
assert_eq!(s.paint, before, "selecting a member keeps the paints for new art");
|
||||
let steps = s.journal.since(from).to_vec();
|
||||
assert_eq!(steps.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>(), ["object.objectsOnPath.selectMember"]);
|
||||
select(&mut s, &[blue]);
|
||||
for (cmd, p) in steps {
|
||||
s.execute(&cmd, &p).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().selection, saved);
|
||||
assert_eq!(s.paint, before, "the replay leaves the same paints");
|
||||
}
|
||||
@@ -91,6 +91,21 @@ fn settings_report_change_in_one_step_and_reject_junk() {
|
||||
assert_eq!(s.execute(C, &json!({"colorModel": "cmyk"})).unwrap()["colorModel"], "cmyk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolution_given_as_text_reads_digits_of_other_scripts() {
|
||||
let mut s = session();
|
||||
let r = s.execute(C, &json!({"resolution": "३०० ppi"})).unwrap();
|
||||
assert_eq!(r["resolution"].as_f64(), Some(300.0));
|
||||
assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0);
|
||||
// One digit set per number, exponent included, and the same 1 to 2400 ppi range as ASCII digits.
|
||||
for bad in ["1५0", "५०००", "१e2", "1e२", "१e+2"] {
|
||||
assert!(s.execute(C, &json!({"resolution": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
|
||||
let r = s.execute(C, &json!({"resolution": "१e२"})).unwrap();
|
||||
assert_eq!(r["resolution"].as_f64(), Some(100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_white_background_makes_effect_images_opaque() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -10,6 +10,11 @@ use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind
|
||||
|
||||
use crate::{EngineError, Prefs, Result, Session};
|
||||
|
||||
pub(crate) struct FreeformPointPick {
|
||||
document: (u64, u64, u64),
|
||||
index: usize,
|
||||
}
|
||||
|
||||
/// What a hover's lend decision holds for ([`Session::hover_tool_at`]).
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub(crate) struct HoverKey {
|
||||
@@ -229,6 +234,7 @@ impl Session {
|
||||
self.tool = self.make_tool(id);
|
||||
// A pick is armed for a stop after its tool is chosen (`note_stop_pick`).
|
||||
self.stop_pick = None;
|
||||
self.freeform_point_pick = None;
|
||||
if let Some(selection) = text_selection {
|
||||
self.tool.set_option("textSelection", &selection);
|
||||
}
|
||||
@@ -633,7 +639,7 @@ impl Session {
|
||||
appearance_item: self.appearance_item(),
|
||||
constrain_angle: self.prefs.constrain_angle,
|
||||
keyboard_increment: self.prefs.keyboard_increment,
|
||||
freeform_point: self.selected_freeform_point(),
|
||||
freeform_point: if self.tool.id() == "eyedropper" { self.pick_freeform_point() } else { self.selected_freeform_point() },
|
||||
raster_sample: self.prefs.eyedropper.sample_size,
|
||||
preview_bounds: self.prefs.use_preview_bounds,
|
||||
scale_strokes: self.prefs.scale_strokes,
|
||||
@@ -1637,6 +1643,9 @@ impl Session {
|
||||
let sets_pressed = self.press_taken_by(self.tool.id());
|
||||
self.tool.set_option(key, v);
|
||||
self.note_stop_pick(key, self.tool.id() == "eyedropper");
|
||||
if key == "freeformPoint" && self.tool.id() == "eyedropper" {
|
||||
self.note_freeform_point_pick(v);
|
||||
}
|
||||
self.tool_set_since_reset = true;
|
||||
self.keep_tool_settings();
|
||||
self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed);
|
||||
@@ -1733,9 +1742,14 @@ impl Session {
|
||||
};
|
||||
self.keep_press_set(before_press, |k| values.contains_key(k) && (sets_pressed || shared.contains(&k)), sets_pressed);
|
||||
// The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one.
|
||||
if (active || lender) && values.contains_key("stop") {
|
||||
if active || lender {
|
||||
let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper";
|
||||
self.note_stop_pick("stop", eyedropper);
|
||||
if values.contains_key("stop") {
|
||||
self.note_stop_pick("stop", eyedropper);
|
||||
}
|
||||
if eyedropper && let Some(v) = values.get("freeformPoint") {
|
||||
self.note_freeform_point_pick(v);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1761,6 +1775,24 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn note_freeform_point_pick(&mut self, option: &Value) {
|
||||
self.freeform_point_pick = None;
|
||||
if option.is_string()
|
||||
&& let Some(doc) = self.active()
|
||||
&& let Some(index) = self.selected_freeform_point()
|
||||
&& self.proxy_freeform(!self.fill_active).is_some_and(|(f, _)| index < f.points.len())
|
||||
{
|
||||
self.freeform_point_pick = Some(FreeformPointPick { document: (doc.uid, doc.revision, doc.reverts), index });
|
||||
}
|
||||
}
|
||||
|
||||
/// An index can outlive its point after a deletion or another paint is applied.
|
||||
fn pick_freeform_point(&self) -> Option<usize> {
|
||||
let pick = self.freeform_point_pick.as_ref()?;
|
||||
let doc = self.active()?;
|
||||
self.selected_freeform_point().filter(|&index| index == pick.index && pick.document == (doc.uid, doc.revision, doc.reverts))
|
||||
}
|
||||
|
||||
/// The tool that took the press under way: the active tool, or the tool that lent a selection
|
||||
/// tool for it (a Cmd-drag), which the dropped press gives its options back to.
|
||||
fn pressed_tool(&self) -> Option<&dyn Tool> {
|
||||
|
||||
@@ -181,7 +181,7 @@
|
||||
//! (gradients that dither are written without dither's noise, Perceptual gradients and gradients
|
||||
//! mixed around the hue wheel as the stops on their curve in process colors, at most 256, and
|
||||
//! gradient stops linked to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
|
||||
//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut
|
||||
//! the tile or is painted with patterns, and pattern fills in large-canvas symbols, as their tiles cut
|
||||
//! to the shape, clipping groups and clipping layers whose clipping object isn't a path,
|
||||
//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its
|
||||
//! stroke not; an image in a clipping group of the region it is cut to), images that can't be
|
||||
@@ -225,7 +225,7 @@ use vectorcraft_pdf::PrivateData;
|
||||
use crate::ps;
|
||||
|
||||
mod writer;
|
||||
pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode};
|
||||
pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, PATTERN_SPACE_KEY, hex_decode};
|
||||
|
||||
use writer::Writer;
|
||||
|
||||
|
||||
@@ -6682,12 +6682,12 @@ fn instances_the_data_cant_hold_are_written_as_their_art() {
|
||||
}
|
||||
|
||||
/// Symbols whose art paints with a pattern, directly, through a nested symbol, in an opacity mask
|
||||
/// and through an inline graphic: their definitions hold the pattern fills as tiles cut to the shape (the reader keeps no
|
||||
/// symbol whose art paints with a pattern), and their instances are written as their art, whose
|
||||
/// and through an inline graphic: their definitions retain native pattern resources, and their
|
||||
/// instances are written as their art, whose
|
||||
/// pattern fills keep the document's placement as the canvas draws them, each with a warning. An
|
||||
/// instance of a symbol without pattern paint stays an instance.
|
||||
#[test]
|
||||
fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
|
||||
fn symbols_with_pattern_fills_keep_resources_and_place_as_art() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
// Tiles that cover the shape, so its tiles cut to it draw its box.
|
||||
let dot = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 8.0, 8.0), Color::BLACK));
|
||||
@@ -6722,12 +6722,17 @@ fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
|
||||
let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(150.0, 10.0, 182.0, 42.0)), fill());
|
||||
doc.insert(Some(layer), usize::MAX, filled).unwrap();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART) && out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings);
|
||||
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings);
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::PATTERNS), "grid resources must not become tiles: {:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
let names: Vec<&str> = back.symbols.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["Patch", "Outer", "Masked", "Plain", "Typed"]);
|
||||
let patch = &back.symbols[0].art;
|
||||
assert!(matches!(patch.kind, NodeKind::Group { .. }), "the symbol's art is its tiles: {:?}", patch.kind);
|
||||
assert!(
|
||||
matches!(patch.kind, NodeKind::Path { .. }) && vectorcraft_doc::pattern::uses_pattern(patch, Some("Dots")),
|
||||
"the symbol must retain its original pattern-filled path: {:?}",
|
||||
patch.kind
|
||||
);
|
||||
assert_eq!(instances(&back.symbols[1].art), 0, "the nested instance is its art");
|
||||
let kids = back.layers[0].children().unwrap();
|
||||
let kinds: Vec<bool> = kids.iter().map(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).collect();
|
||||
@@ -6757,8 +6762,164 @@ fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
|
||||
same_lines(&boxes(&back), &boxes(&doc));
|
||||
}
|
||||
|
||||
/// Original ruled tile shared by symbol art and an ordinary canvas object. The symbol's pattern
|
||||
/// and geometry are scaled together, as editing its art with Transform Pattern Tiles does.
|
||||
fn ruled_pattern_symbol(strokes: bool, tile_type: vectorcraft_doc::TileType, extent: f64) -> Document {
|
||||
let mut doc = Document::new(240.0, 140.0);
|
||||
let line =
|
||||
Node::path(doc.alloc_id(), shapes::line((1.0, 5.0).into(), (9.0, 5.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 2.0));
|
||||
let mut tile = vectorcraft_doc::PatternDef::new("Rules", vec![Arc::new(line)]);
|
||||
tile.tile = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
tile.tile_type = tile_type;
|
||||
doc.patterns.push(tile);
|
||||
let fill = || Appearance::basic(Paint::Pattern { pattern: "Rules".into(), xf: Affine::IDENTITY }, Paint::None, 0.0);
|
||||
let mut art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, extent, extent)), fill());
|
||||
art.transform(Affine::scale(0.2), vectorcraft_doc::Scaling { strokes, patterns: true, ..Default::default() });
|
||||
doc.symbols.push(Symbol { name: "Scaled".into(), art: Arc::new(art), dynamic: false });
|
||||
let layer = doc.layers[0].id;
|
||||
let one = instance(&mut doc, "Scaled", Affine::translate((20.0, 20.0)));
|
||||
doc.insert(Some(layer), usize::MAX, one).unwrap();
|
||||
let shared = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(125.0, 5.0, 225.0, 105.0)), fill());
|
||||
doc.insert(Some(layer), usize::MAX, shared).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scaled_pattern_symbol_keeps_native_pattern_resources_in_editing_data() {
|
||||
let small = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
|
||||
let large = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 200.0);
|
||||
let (a, b) = (program(&small), program(&large));
|
||||
eprintln!("pattern symbol editing bytes: {} -> {} for four times the tile area", a.len(), b.len());
|
||||
let back = read_back(&small);
|
||||
let art = &back.symbols.iter().find(|s| s.name == "Scaled").unwrap().art;
|
||||
assert!(vectorcraft_doc::pattern::uses_pattern(art, Some("Rules")), "the symbol must retain pattern paint rather than one object per tile");
|
||||
assert_eq!(a.matches("%AI3_BeginPattern: (Rules)").count(), 1);
|
||||
assert!(b.len() < a.len() * 2, "editing data must not grow with every covered tile: {} -> {}", a.len(), b.len());
|
||||
let tile = back.pattern("Rules").unwrap();
|
||||
assert_eq!(tile.tile, small.patterns[0].tile);
|
||||
assert_eq!(tile.art[0].geometric_bounds().unwrap().width(), 8.0);
|
||||
let strokes: Vec<_> =
|
||||
tile.art[0].appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(stroke) = i { Some(stroke.width) } else { None }).collect();
|
||||
assert_eq!(strokes, [2.0], "the shared tile keeps its original stroke");
|
||||
}
|
||||
|
||||
// Four editing-stream round trips and native raster probes cover the flag and fallback cases.
|
||||
#[test]
|
||||
fn scaled_pattern_symbol_new_instances_match_native_tile_stroke_weight() {
|
||||
for strokes in [true, false] {
|
||||
for tile_type in [vectorcraft_doc::TileType::Grid, vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }] {
|
||||
let doc = ruled_pattern_symbol(strokes, tile_type, 100.0);
|
||||
// Native rendering scales a 2pt pattern stroke to 0.4pt with its pattern affine,
|
||||
// under either flag. The flag controls the selected object's own stroke separately.
|
||||
let native = vectorcraft_testkit::raster::render_region(&doc, Rect::new(20.0, 20.0, 22.0, 22.0), 20.0);
|
||||
let native_weight = (0..native.height).filter(|y| native.pixel(20, *y)[0] < 64).count();
|
||||
assert!((6..=10).contains(&native_weight), "native weight={native_weight}, strokes={strokes}, {tile_type:?}");
|
||||
let mut back = read_back(&doc);
|
||||
// Place afresh from the editing stream's symbol definition, rather than measuring
|
||||
// the already-expanded canvas instance or the file's native payload.
|
||||
back.layers.clear();
|
||||
let layer = back.add_layer(Some("New instance"));
|
||||
let one = instance(&mut back, "Scaled", Affine::translate((20.0, 20.0)));
|
||||
back.insert(Some(layer), usize::MAX, one).unwrap();
|
||||
let placed = vectorcraft_testkit::raster::render_region(&back, Rect::new(20.0, 20.0, 22.0, 22.0), 20.0);
|
||||
let weight = (0..placed.height).filter(|y| placed.pixel(20, *y)[0] < 64).count();
|
||||
assert!((6..=10).contains(&weight), "editing symbol weight={weight}, native={native_weight}, strokes={strokes}, {tile_type:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each case goes through the real editing stream and renderer: the mask stroke has to be
|
||||
// transformed as geometry even when writing its dictionary temporarily clears the tile clip.
|
||||
#[test]
|
||||
fn pattern_tile_fallback_preserves_affine_mask_stroke_weight() {
|
||||
for matrix in
|
||||
[Affine::scale(0.2), Affine::scale_non_uniform(0.2, 0.4), Affine::new([0.2, 0.0, 0.1, 0.2, 0.0, 0.0]), Affine::scale_non_uniform(-0.2, 0.2)]
|
||||
{
|
||||
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, 100.0);
|
||||
let white_line =
|
||||
Node::path(doc.alloc_id(), shapes::line((1.0, 5.0).into(), (9.0, 5.0).into()), Appearance::basic(Paint::None, solid(Color::WHITE), 2.0));
|
||||
let mut tile = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::BLACK);
|
||||
tile.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(white_line), clip: true, invert: false, disabled: false, linked: true }));
|
||||
doc.patterns[0].art = vec![Arc::new(tile)];
|
||||
Arc::make_mut(&mut doc.symbols[0].art)
|
||||
.transform(matrix * Affine::scale(5.0), vectorcraft_doc::Scaling { patterns: true, ..Default::default() });
|
||||
// This fallback bakes the unsupported brick phase. Place on whole super-tile periods
|
||||
// so the probe isolates stroke geometry, rather than that existing placement limitation.
|
||||
doc.layers.clear();
|
||||
let native_layer = doc.add_layer(Some("Native instance"));
|
||||
let native_one = instance(&mut doc, "Scaled", Affine::translate((60.0, 40.0)));
|
||||
doc.insert(Some(native_layer), usize::MAX, native_one).unwrap();
|
||||
let bounds = doc.symbols[0].art.geometric_bounds().unwrap() + vectorcraft_geom::Vec2::new(60.0, 40.0);
|
||||
let period_y = 10.0 * matrix.as_coeffs()[3].abs();
|
||||
let region = Rect::new(bounds.x0, bounds.y0, bounds.x0 + 2.0, bounds.y0 + period_y);
|
||||
let native = vectorcraft_testkit::raster::render_region(&doc, region, 20.0);
|
||||
// Brick rows shift the line horizontally; select a visible native column and compare
|
||||
// that same column after the editing-stream round trip.
|
||||
let (column, native_weight) = (0..native.width)
|
||||
.map(|x| (x, (0..native.height).filter(|y| native.pixel(x, *y)[0] < 64).count()))
|
||||
.max_by_key(|(_, weight)| *weight)
|
||||
.unwrap();
|
||||
assert!(native_weight > 0 && native_weight < native.height as usize, "native mask stroke: {matrix:?}, {native_weight}");
|
||||
let mut back = read_back(&doc);
|
||||
back.layers.clear();
|
||||
let layer = back.add_layer(Some("New instance"));
|
||||
let one = instance(&mut back, "Scaled", Affine::translate((60.0, 40.0)));
|
||||
back.insert(Some(layer), usize::MAX, one).unwrap();
|
||||
let placed = vectorcraft_testkit::raster::render_region(&back, region, 20.0);
|
||||
let weight = (0..placed.height).filter(|y| placed.pixel(column, *y)[0] < 64).count();
|
||||
assert!(weight.abs_diff(native_weight) <= 2, "mask stroke {matrix:?}: editing={weight}, native={native_weight}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_definition_dictionary_is_scoped_away_from_its_symbol() {
|
||||
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
|
||||
// Definitions can hold freshly generated id-less art. Its dictionary must not consume the
|
||||
// surrounding symbol's root entries just because these independent art scopes share id 0.
|
||||
Arc::make_mut(&mut doc.patterns[0].art[0]).id = vectorcraft_doc::NodeId(0);
|
||||
let art = (*doc.symbols[0].art).clone();
|
||||
let other = square(&mut doc, Rect::new(25.0, 0.0, 30.0, 5.0), Color::BLACK);
|
||||
let mut root = group(&mut doc, vec![art, other], false);
|
||||
root.id = vectorcraft_doc::NodeId(0);
|
||||
doc.symbols[0].art = Arc::new(root);
|
||||
let back = read_back(&doc);
|
||||
let symbol = back.symbols.iter().find(|s| s.name == "Scaled").expect("pattern art must not steal its symbol's declaration");
|
||||
let mut uses = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut |n| uses |= vectorcraft_doc::pattern::uses_pattern(n, Some("Rules")));
|
||||
assert!(uses);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_pattern_matrices_stay_readable_or_use_the_bounded_fallback() {
|
||||
for scale in [0.00001, 0.0, 1e-9] {
|
||||
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
|
||||
let art = Arc::make_mut(&mut doc.symbols[0].art);
|
||||
for item in art.appearance.items.iter_mut() {
|
||||
if let Paint::Pattern { xf, .. } = item.paint_mut() {
|
||||
*xf = Affine::scale(scale);
|
||||
}
|
||||
}
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
let back = read_back(&doc);
|
||||
let symbol = back.symbols.iter().find(|s| s.name == "Scaled").expect("a bad paint matrix must not discard its symbol");
|
||||
let mut paints = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut |n| {
|
||||
for item in &n.appearance.items {
|
||||
if let Paint::Pattern { xf, .. } = item.paint() {
|
||||
paints.push(*xf);
|
||||
}
|
||||
}
|
||||
});
|
||||
if scale == 0.00001 {
|
||||
assert_eq!(paints, [Affine::scale(scale)], "a small invertible affine must survive serialization");
|
||||
} else {
|
||||
assert!(paints.is_empty() && out.warnings.iter().any(|w| w == writer::PATTERN_PLACEMENT), "{:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol whose art paints with a pattern only through a brushed stroke, whose brush's art is
|
||||
/// filled with a pattern: the definition holds the tiles, and its instance is written as its art.
|
||||
/// filled with a pattern: the definition keeps that resource, and its instance is written as art.
|
||||
#[test]
|
||||
fn symbols_painting_patterns_through_brush_art_are_placed_as_art() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
@@ -6786,9 +6947,13 @@ fn symbols_painting_patterns_through_brush_art_are_placed_as_art() {
|
||||
doc.insert(Some(layer), usize::MAX, one).unwrap();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings);
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
assert_eq!(back.symbols.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Brushed"]);
|
||||
assert_eq!(instances(&back.layers[0]), 0, "the instance is its art");
|
||||
let mut pattern = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(&back.symbols[0].art, &mut |n| pattern |= vectorcraft_doc::pattern::uses_pattern(n, Some("Dots")));
|
||||
assert!(pattern, "indirect brush paint retains its pattern resource in the definition");
|
||||
}
|
||||
|
||||
/// A symbol first defined from the drawn look of a group with a style, through a member's scatter
|
||||
|
||||
@@ -48,7 +48,7 @@ pub(super) use paints::{
|
||||
GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS,
|
||||
SWATCH_PLACEMENT, free_gradient_name,
|
||||
};
|
||||
pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode};
|
||||
pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, PATTERN_SPACE_KEY, hex_decode};
|
||||
#[cfg(test)]
|
||||
pub(super) use symbols::{MISSING_SYMBOL, OVERRIDE_SERIALIZATIONS, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS};
|
||||
#[cfg(test)]
|
||||
@@ -62,8 +62,10 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES};
|
||||
pub(super) const MAX_NEST: u32 = 8;
|
||||
|
||||
pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type whose text wrap cannot be preserved from the saved objects, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps";
|
||||
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
|
||||
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a large canvas's symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
|
||||
pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps";
|
||||
pub(super) const PATTERN_PLACEMENT: &str =
|
||||
"pattern fills and strokes whose placement cannot be read are written gray in the editing data for other apps";
|
||||
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
|
||||
@@ -270,10 +272,10 @@ pub(super) struct Writer<'a> {
|
||||
/// ([`Self::symbol_paints_pattern`]).
|
||||
patterned_symbols: HashMap<String, bool>,
|
||||
symbol_omissions: HashMap<*const Node, symbols::OmissionFacts>,
|
||||
/// Pattern tiles were written in the art being written ([`Self::define_symbol`] starts it over
|
||||
/// Pattern references or tiles were written in the art ([`Self::define_symbol`] starts it over
|
||||
/// for each symbol's art).
|
||||
wrote_pattern: bool,
|
||||
/// The symbols whose definitions hold pattern tiles: a brushed stroke's brush art or a live
|
||||
/// The symbols whose definitions write pattern paint: a brushed stroke's brush art or a live
|
||||
/// object's art can paint with a pattern that the symbol's own objects don't name.
|
||||
pattern_written: HashSet<String>,
|
||||
/// Art that draws as it should only where it is was written in the art being written
|
||||
@@ -1034,6 +1036,7 @@ impl<'a> Writer<'a> {
|
||||
mask = None;
|
||||
mask_written = false;
|
||||
}
|
||||
let symbol_root = self.root_entries.as_ref().is_some_and(|(id, _)| *id == n.id);
|
||||
let entries = match &self.root_entries {
|
||||
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
@@ -1084,6 +1087,10 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
mask_written = false;
|
||||
}
|
||||
// A pattern may first be written by the root's mask, so declare its space afterwards.
|
||||
if symbol_root && self.in_symbol && self.symbols_live && self.wrote_pattern {
|
||||
let _ = writeln!(self.body, "%_1 /Int ({PATTERN_SPACE_KEY}) ,");
|
||||
}
|
||||
self.body.push_str("%_;\n%_\n");
|
||||
mask_written
|
||||
}
|
||||
@@ -1483,7 +1490,8 @@ impl<'a> Writer<'a> {
|
||||
let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() };
|
||||
return self.path_object(path, rule, Some(&flat), None, xy);
|
||||
};
|
||||
let tiles = def.instances_in(*xf, path.to_bezpath().bounding_box());
|
||||
let inverse = xf.inverse();
|
||||
let tiles = def.instances_in(Affine::IDENTITY, inverse.transform_rect_bbox(path.to_bezpath().bounding_box()));
|
||||
// More tiles than a fill places come back as none: the shape is filled gray, as a
|
||||
// pattern that isn't found is.
|
||||
if tiles.is_empty() && !def.art.is_empty() {
|
||||
@@ -1497,8 +1505,26 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
self.wrote_pattern = true;
|
||||
let outer = self.clip.clone();
|
||||
let region = self.cut(path, rule);
|
||||
let mut region = self.cut(path, rule);
|
||||
region.transform(inverse);
|
||||
self.clip = Some(region);
|
||||
let shown = std::mem::take(&mut self.shown);
|
||||
self.shown = shown
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut p = p.clone();
|
||||
p.apply_affine(inverse);
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
// Outline and clip strokes in pattern space before applying its affine. Moving
|
||||
// just their centerlines first kept 2pt strokes at 2pt under a 20% pattern scale;
|
||||
// scaling by one mean factor would still distort nonuniform/sheared patterns.
|
||||
let spaces = (self.to_art, self.grad_space, self.canvas, self.instance_space);
|
||||
self.to_art *= *xf;
|
||||
self.grad_space *= *xf;
|
||||
self.canvas *= *xf;
|
||||
self.instance_space *= *xf;
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
for t in &tiles {
|
||||
@@ -1511,6 +1537,8 @@ impl<'a> Writer<'a> {
|
||||
self.end_group("U", xy);
|
||||
self.nest -= 1;
|
||||
self.clip = outer;
|
||||
self.shown = shown;
|
||||
(self.to_art, self.grad_space, self.canvas, self.instance_space) = spaces;
|
||||
}
|
||||
Paint::None => {}
|
||||
}
|
||||
|
||||
@@ -430,7 +430,7 @@ impl Writer<'_> {
|
||||
}
|
||||
|
||||
/// `[a b c d tx ty]`, each number to ten decimals ([`ps::num`] writes four).
|
||||
fn matrix(m: Affine) -> String {
|
||||
pub(super) fn matrix(m: Affine) -> String {
|
||||
let n: Vec<String> = m.as_coeffs().iter().map(|v| precise(*v)).collect();
|
||||
format!("[{}]", n.join(" "))
|
||||
}
|
||||
|
||||
@@ -366,7 +366,12 @@ impl Writer<'_> {
|
||||
/// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can
|
||||
/// write it)?
|
||||
pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool {
|
||||
self.direct(&s.paint) && crate::ai_ops::plain_stroke(s)
|
||||
let [a, b, c, d, ..] = self.to_art.as_coeffs();
|
||||
// Operators receive transformed path coordinates, but their width is in art units.
|
||||
// A non-isometric map needs the stroke's outline transformed too (including in masks,
|
||||
// whose dictionary temporarily clears the clipping region of a pattern fallback).
|
||||
let isometry = (a * a + b * b - 1.0).abs() < 1e-9 && (c * c + d * d - 1.0).abs() < 1e-9 && (a * c + b * d).abs() < 1e-9;
|
||||
isometry && self.direct(&s.paint) && crate::ai_ops::plain_stroke(s)
|
||||
}
|
||||
|
||||
/// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the
|
||||
@@ -575,10 +580,10 @@ impl Writer<'_> {
|
||||
|
||||
/// Can pattern `name` be written as a definition and painted with from here: the document has
|
||||
/// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used
|
||||
/// in another pattern's tile or a symbol's art (the reader keeps no symbol whose art paints with
|
||||
/// a pattern) or nested more than [`MAX_NEST`] deep?
|
||||
/// in another pattern's tile or nested more than [`MAX_NEST`] deep? A large canvas's symbol
|
||||
/// art uses the original document, whose same-name tiles can differ from the reduced page's.
|
||||
pub(super) fn pattern_writable(&self, name: &str) -> bool {
|
||||
if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol {
|
||||
if !self.defining.is_empty() || self.nest >= MAX_NEST || (self.in_symbol && !self.symbols_live) {
|
||||
return false;
|
||||
}
|
||||
if self.patterns.find(name).is_some() {
|
||||
@@ -604,7 +609,14 @@ impl Writer<'_> {
|
||||
let doc = self.doc;
|
||||
// The tile's box is an object of the definition ([`Self::take_objects`]).
|
||||
let (before, bound) = (self.charges(), self.bound.len());
|
||||
let Some(def) = doc.pattern(name).filter(|_| self.take_objects(1)) else { return false };
|
||||
let Some(def) = doc.pattern(name) else { return false };
|
||||
// A pattern is a separate global resource, even when first discovered in symbol art.
|
||||
// Charge its objects outside the symbol-art budget and isolate parent dictionaries.
|
||||
let in_symbol = std::mem::take(&mut self.in_symbol);
|
||||
if !self.take_objects(1) {
|
||||
self.in_symbol = in_symbol;
|
||||
return false;
|
||||
}
|
||||
self.defining.push(name.to_string());
|
||||
// The art is written in the pattern's space, y up, from the state a definition starts in.
|
||||
let saved = (
|
||||
@@ -616,6 +628,7 @@ impl Writer<'_> {
|
||||
self.block_end,
|
||||
// The tile's masks' objects are written with their art styles, those of no other art.
|
||||
(std::mem::replace(&mut self.styled, self.pattern_styled.get(name).cloned().unwrap_or_default()), self.mask_level.take()),
|
||||
(in_symbol, self.root_entries.take(), self.instance_entries.take(), self.block_start),
|
||||
);
|
||||
// `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its
|
||||
// placement is worked out in the tile's space turned y up.
|
||||
@@ -646,6 +659,7 @@ impl Writer<'_> {
|
||||
(self.clip, self.shown),
|
||||
self.block_end,
|
||||
(self.styled, self.mask_level),
|
||||
(self.in_symbol, self.root_entries, self.instance_entries, self.block_start),
|
||||
) = saved;
|
||||
let art = std::mem::replace(&mut self.body, art);
|
||||
self.defining.pop();
|
||||
@@ -678,7 +692,18 @@ impl Writer<'_> {
|
||||
return self.plain_color(Color::gray(0.5), stroke);
|
||||
};
|
||||
let m = self.to_art * xf * Affine::translate((0.0, h)) * Affine::FLIP_Y;
|
||||
let _ = writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), ps::matrix(m), if stroke { 'P' } else { 'p' });
|
||||
let written = Affine::new(m.as_coeffs().map(|v| (v * 1e10).round() / 1e10));
|
||||
// Keep a definition's reference readable after serialization; a singular or rounded-flat
|
||||
// paint must not make the reader discard the entire symbol that contains it.
|
||||
if !written.as_coeffs().iter().all(|v| v.is_finite()) || !written.determinant().is_finite() || written.determinant().abs() < 1e-12 {
|
||||
self.warn(super::PATTERN_PLACEMENT);
|
||||
return self.plain_color(Color::gray(0.5), stroke);
|
||||
}
|
||||
// Indirect pattern paint (for example in brush art) also prevents a live symbol
|
||||
// instance: the canvas keeps its pattern phase fixed when placing that instance.
|
||||
self.wrote_pattern = true;
|
||||
let _ =
|
||||
writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), super::images::matrix(m), if stroke { 'P' } else { 'p' });
|
||||
}
|
||||
|
||||
/// The definitions, in the setup before the palette: the gradients the art uses (`n Bn`, then
|
||||
|
||||
@@ -19,6 +19,9 @@ pub(in crate::ai_editing) const SYMBOL_CHANGES: &str =
|
||||
"the changes of dynamic symbol instances are kept in dictionary entries of their own, which other apps leave out";
|
||||
pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol";
|
||||
pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides";
|
||||
/// Version 1 declares that pattern matrices in this definition use its art coordinates.
|
||||
/// Foreign definitions without that declaration retain the reader's conservative fallback.
|
||||
pub(crate) const PATTERN_SPACE_KEY: &str = "VectorCraftSymbolPatternSpace";
|
||||
const MAX_OVERRIDES_BYTES: usize = 1 << 20;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -385,6 +388,9 @@ impl Writer<'_> {
|
||||
if wrap {
|
||||
self.line("u");
|
||||
self.node(root);
|
||||
if self.symbols_live && self.wrote_pattern {
|
||||
let _ = writeln!(entries, "%_1 /Int ({PATTERN_SPACE_KEY}) ,");
|
||||
}
|
||||
let _ = write!(self.body, "U\n%_/ArtDictionary :\n{entries}%_;\n%_\n9 () XW\n");
|
||||
} else {
|
||||
// A group always writes its dictionary ([`Self::dictionary`]), which takes the entries.
|
||||
|
||||
@@ -631,8 +631,12 @@ impl<'a> Reader<'a> {
|
||||
let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1;
|
||||
let Some(frame) = sub.frames.pop().filter(|_| measured) else { return };
|
||||
let mut kids = frame.children;
|
||||
// Where a symbol's art puts a pattern's tiles isn't known.
|
||||
let whole = !head.left_out && sub.unread.is_empty() && sub.hidden_unread.is_empty() && !kids.iter().any(|n| paints_pattern(n, 0));
|
||||
// Unmarked foreign symbols do not declare the coordinate convention of their patterns.
|
||||
// Our writer explicitly declares symbol-art space, so those definitions can retain paint.
|
||||
let whole = !head.left_out
|
||||
&& sub.unread.is_empty()
|
||||
&& sub.hidden_unread.is_empty()
|
||||
&& (head.pattern_space || !kids.iter().any(|n| paints_pattern(n, 0)));
|
||||
if !whole {
|
||||
let boxes = self.doc.symbol_boxes();
|
||||
let bounds = kids.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds_with(&boxes)));
|
||||
|
||||
@@ -805,6 +805,12 @@ impl<'a> Reader<'a> {
|
||||
{
|
||||
head.dynamic = true;
|
||||
}
|
||||
if self.frames.len() == 1
|
||||
&& let Some(head) = self.symbol.as_mut()
|
||||
&& o.nums(crate::ai_editing::PATTERN_SPACE_KEY).first().copied() == Some(1.0)
|
||||
{
|
||||
head.pattern_space = true;
|
||||
}
|
||||
if let Some(text) = o.text(crate::ai_editing::OVERRIDES_KEY)
|
||||
&& let Some(bytes) = crate::ai_editing::hex_decode(&text)
|
||||
&& let Ok(list) = serde_json::from_slice::<Vec<vectorcraft_doc::SymbolOverride>>(&bytes)
|
||||
|
||||
@@ -245,6 +245,8 @@ pub(super) struct SymbolHead {
|
||||
/// `AI13PatternRegistrationType` in the dictionary after the art.
|
||||
pub(super) registration: Option<f64>,
|
||||
pub(super) dynamic: bool,
|
||||
/// The writer declares its pattern matrices to be in symbol-art coordinates (version 1).
|
||||
pub(super) pattern_space: bool,
|
||||
/// Art the reader left out (type, a placed file, non-native art, an image it can't read or
|
||||
/// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the
|
||||
/// page draws them, within the box of the rest.
|
||||
|
||||
@@ -82,6 +82,7 @@ fn export_tool_lists_engine_formats_and_options() {
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx",
|
||||
"pict",
|
||||
"dwg"
|
||||
])
|
||||
);
|
||||
|
||||
@@ -400,7 +400,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"export",
|
||||
"Export",
|
||||
"Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, dwg (the DXF drawing as a DWG file, versions 2000 to 2018), emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF and DWG take it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",
|
||||
"Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, dwg (the DXF drawing as a DWG file, versions 2000 to 2018), emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes, pict QuickDraw pictures as .pct), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF and DWG take it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",
|
||||
obj(
|
||||
json!({
|
||||
"format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::<Vec<_>>(), "description": "Default: from the path's extension"},
|
||||
|
||||
@@ -3,7 +3,7 @@ name = "vectorcraft-metafile"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF, QuickDraw PICT and binary CGM import through craft-metafile"
|
||||
description = "VectorCraft metafiles: EMF, WMF and QuickDraw PICT export and EMF, EMF+, WMF, QuickDraw PICT and binary CGM import through craft-metafile"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -18,6 +18,7 @@ vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
vectorcraft-effects = { workspace = true }
|
||||
vectorcraft-pathops = { workspace = true }
|
||||
vectorcraft-brush = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
craft-metafile = { workspace = true, features = ["write"] }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Translate VectorCraft's drawing operations to the shared metafile writers.
|
||||
//! Translate VectorCraft's drawing operations to the shared metafile writers (EMF, WMF) and to
|
||||
//! the PICT writer.
|
||||
use craft_metafile::{
|
||||
Cap, Join,
|
||||
write::{self, Dash, Op, Pen},
|
||||
@@ -9,11 +10,30 @@ use vectorcraft_geom::{FillRule, Rect};
|
||||
use crate::{Kind, scene};
|
||||
|
||||
pub(crate) fn write(ops: Vec<scene::Op>, region: Rect, kind: Kind, title: &str, warnings: &mut Vec<String>) -> Result<Vec<u8>, String> {
|
||||
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
|
||||
let invalid = || "the export region is empty".to_string();
|
||||
let mut note = |lost: bool, warning: &str| {
|
||||
if lost && !warnings.iter().any(|w| w == warning) {
|
||||
warnings.push(warning.to_string());
|
||||
}
|
||||
};
|
||||
match kind {
|
||||
Kind::Emf => write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid),
|
||||
Kind::Pict => {
|
||||
let out = crate::pict::write(&ops, region)?;
|
||||
note(out.translucent_images, "PICT has no transparency: images are written over white");
|
||||
note(out.turned_images, "PICT turns images only by quarter turns: other turns and skews are written upright, filling their bounds");
|
||||
note(out.coarsened_fills, "fills with more points than one polygon holds are written with their curves flattened more coarsely");
|
||||
note(out.split_fills, "fills with more than 8,189 points are written as several polygons, which may fill their holes");
|
||||
note(out.thinned_fills, "outlines with more than 8,187 points are written with fewer points");
|
||||
note(out.unresolved_fills, "non-zero fills too complex to resolve are written even-odd, which may leave overlaps unfilled");
|
||||
note(out.uncut_fills, "fills too complex to cut to the artboard that reach far outside it may be written distorted");
|
||||
Ok(out.bytes)
|
||||
}
|
||||
Kind::Emf => {
|
||||
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
|
||||
write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid)
|
||||
}
|
||||
Kind::Wmf => {
|
||||
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
|
||||
let out = write::wmf(&ops, region).ok_or_else(invalid)?;
|
||||
for (lost, warning) in [
|
||||
(out.translucent_images, "WMF has no transparency: images are written over white"),
|
||||
@@ -21,9 +41,7 @@ pub(crate) fn write(ops: Vec<scene::Op>, region: Rect, kind: Kind, title: &str,
|
||||
(out.clips_ignored, "clipping masks are not applied: the art they clip is written whole"),
|
||||
(out.oversized_images, "WMF images with a side over 32,767 pixels were left out"),
|
||||
] {
|
||||
if lost && !warnings.iter().any(|w| w == warning) {
|
||||
warnings.push(warning.to_string());
|
||||
}
|
||||
note(lost, warning);
|
||||
}
|
||||
Ok(out.bytes)
|
||||
}
|
||||
|
||||
@@ -1088,7 +1088,11 @@ fn retracked(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) ->
|
||||
|
||||
/// Read an EMF or WMF file.
|
||||
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
|
||||
let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?;
|
||||
let wire_kind = craft_metafile::sniff(bytes).ok_or("not an EMF or WMF file")?;
|
||||
let kind = match wire_kind {
|
||||
craft_metafile::Kind::Emf => Kind::Emf,
|
||||
craft_metafile::Kind::Wmf => Kind::Wmf,
|
||||
};
|
||||
let pic = craft_metafile::parse(bytes).map_err(|e| match e {
|
||||
craft_metafile::Error::NotMetafile | craft_metafile::Error::NotPict => "not an EMF or WMF file".to_string(),
|
||||
craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()),
|
||||
@@ -1096,10 +1100,6 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
|
||||
})?;
|
||||
let k = unit(bytes);
|
||||
let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k);
|
||||
let wire_kind = match kind {
|
||||
Kind::Emf => craft_metafile::Kind::Emf,
|
||||
Kind::Wmf => craft_metafile::Kind::Wmf,
|
||||
};
|
||||
if craft_metafile::ends_early(bytes, wire_kind) {
|
||||
m.warn(ENDS_EARLY);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Windows metafiles: hand-written EMF and WMF writers and readers.
|
||||
//! Windows metafiles: hand-written EMF and WMF writers and readers, and a QuickDraw picture (PICT)
|
||||
//! writer and reader.
|
||||
//!
|
||||
//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile,
|
||||
//! and [`export_regions`] one metafile per region:
|
||||
@@ -13,6 +14,9 @@
|
||||
//! placeable header that gives the size; WMF has no clipping paths, transparency, dashes on wide
|
||||
//! lines or gradients, so clipped art is written whole, images over white, dashes as separate
|
||||
//! lines and gradients and patterns as one colour (each loss comes back as a warning).
|
||||
//! - **PICT**: the art WMF gets, as a QuickDraw version 2 picture in device units of up to 16 to a
|
||||
//! point: fills are polygons cut to the picture's frame, strokes their filled outlines, and images
|
||||
//! 24-bit pixel maps over white (see `pict`).
|
||||
//!
|
||||
//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`)
|
||||
//! into a document of one artboard (the picture's frame) and one layer: paths with fills and
|
||||
@@ -33,26 +37,31 @@ mod bytes;
|
||||
mod dib;
|
||||
mod encode;
|
||||
mod import;
|
||||
mod pict;
|
||||
mod scene;
|
||||
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
/// A Windows metafile format.
|
||||
/// A metafile format: the Windows metafiles, and QuickDraw pictures, which [`export`] writes and
|
||||
/// [`is_pict`] and [`import_pict`] read ([`sniff`] and [`import`] read only the Windows formats).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
/// Enhanced Metafile (32-bit coordinates, Bézier curves, paths and clipping).
|
||||
Emf,
|
||||
/// Windows Metafile with a placeable header (16-bit coordinates, polygons).
|
||||
Wmf,
|
||||
/// QuickDraw picture, version 2, in a PICT file (16-bit coordinates, polygons).
|
||||
Pict,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
/// The format id (`emf`, `wmf`).
|
||||
/// The format id (`emf`, `wmf`, `pict`).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Emf => "emf",
|
||||
Self::Wmf => "wmf",
|
||||
Self::Pict => "pict",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,11 +102,21 @@ pub fn check_regions(regions: &[Rect]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_regions`] for `kind`: a PICT picture's frame is also at most 32,767 points on a side.
|
||||
pub fn check_regions_for(regions: &[Rect], kind: Kind) -> Result<(), String> {
|
||||
check_regions(regions)?;
|
||||
if kind == Kind::Pict {
|
||||
regions.iter().try_for_each(|r| pict::check_region(r.abs()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the
|
||||
/// same order, each as [`export`] writes it over that region. The live effects are applied once
|
||||
/// for all of them. When any region is empty, nothing is written and the result is an error.
|
||||
/// for all of them. When any region is empty (or, for PICT, over 32,767 points on a side),
|
||||
/// nothing is written and the result is an error.
|
||||
pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result<Vec<Output>, String> {
|
||||
check_regions(regions)?;
|
||||
check_regions_for(regions, kind)?;
|
||||
let regions: Vec<Rect> = regions.iter().map(|r| r.abs()).collect();
|
||||
if regions.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
//! The PICT writer: the art WMF gets, as a QuickDraw version 2 picture written through
|
||||
//! [`craft_metafile::write::PictWriter`], which writes the records.
|
||||
//!
|
||||
//! The picture frame is the region in whole points; the drawing is in device units of up to 16 to
|
||||
//! a point (the header's resolution, at most 1,152 dpi), as many as keep the frame within 16-bit
|
||||
//! coordinates. QuickDraw has no curves, Bézier paths or pens with joins, so:
|
||||
//!
|
||||
//! - fills are polygons (`PaintPoly`) in the fill's color, filled even-odd as QuickDraw fills
|
||||
//! polygons: a path of several figures is one polygon that runs back along the line between its
|
||||
//! figures, and a non-zero fill is first resolved into figures that do not overlap. Art is cut
|
||||
//! to the frame first, which keeps every coordinate within 16 bits.
|
||||
//! - strokes are their outlines (dashes cut first), filled the same way.
|
||||
//! - images are `DirectBitsRect` records of 24-bit pixels in tiles of at most 1,024 pixels on a
|
||||
//! side, packed by rows with PackBits; transparency is composited over white, and images that
|
||||
//! are turned or skewed by other than a quarter turn are written upright, filling their bounds.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_metafile::write::{Image, PICT_MAX_POLY_POINTS as MAX_POLY_POINTS, PictWriter};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
|
||||
use crate::scene::{Op, Pen};
|
||||
|
||||
/// The largest 16-bit coordinate.
|
||||
const MAX_I16: f64 = 32767.0;
|
||||
/// Most device units a point (16, 1,152 dpi).
|
||||
const MAX_SCALE: f64 = 16.0;
|
||||
/// Curves are flattened to within this many device units.
|
||||
const FLATNESS: f64 = 0.25;
|
||||
/// Times the flatness is raised (four-fold each time) for a fill with too many points before it
|
||||
/// is split into several polygons.
|
||||
const COARSER: u32 = 3;
|
||||
/// Most pixels along a side of one image record.
|
||||
const TILE: usize = 1024;
|
||||
/// Opacity at or above this is written as opaque.
|
||||
const OPAQUE: f32 = 0.998;
|
||||
|
||||
/// A written picture and what it could not hold.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Pict {
|
||||
pub bytes: Vec<u8>,
|
||||
/// Images with transparency were written over white.
|
||||
pub translucent_images: bool,
|
||||
/// Turned or skewed images were written upright, filling their bounds.
|
||||
pub turned_images: bool,
|
||||
/// A fill with more points than one polygon holds was written with its curves flattened more coarsely.
|
||||
pub coarsened_fills: bool,
|
||||
/// A fill with more points than one polygon holds was written as several polygons, so its
|
||||
/// holes may be filled.
|
||||
pub split_fills: bool,
|
||||
/// A figure with more points than one polygon holds was written with fewer.
|
||||
pub thinned_fills: bool,
|
||||
/// A non-zero fill too complex to resolve into figures that don't overlap was written even-odd.
|
||||
pub unresolved_fills: bool,
|
||||
/// A fill too complex to cut to the frame was written with its points past 16 bits moved in.
|
||||
pub uncut_fills: bool,
|
||||
}
|
||||
|
||||
/// The device units a point for a picture `w` × `h` points: the most, up to [`MAX_SCALE`], that
|
||||
/// keep its size within 16 bits.
|
||||
fn units_per_point(w: f64, h: f64) -> f64 {
|
||||
let side = w.max(h);
|
||||
if side > 0.0 { (MAX_I16 / side).floor().clamp(1.0, MAX_SCALE) } else { MAX_SCALE }
|
||||
}
|
||||
|
||||
/// The error for a region the picture frame can't hold: a side over 32,767 points.
|
||||
pub(crate) fn check_region(region: Rect) -> Result<(), String> {
|
||||
if region.width().round() > MAX_I16 || region.height().round() > MAX_I16 {
|
||||
return Err("PICT pictures are at most 32,767 points on a side".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `v` rounded into 16 bits.
|
||||
fn i16_of(v: f64) -> i16 {
|
||||
v.round().clamp(-MAX_I16, MAX_I16) as i16
|
||||
}
|
||||
|
||||
/// Whether every point of `fig` lies on one line, so that it encloses no area.
|
||||
fn collinear(fig: &[[i16; 2]]) -> bool {
|
||||
let Some(&[x0, y0]) = fig.first() else { return true };
|
||||
let (x0, y0) = (i64::from(x0), i64::from(y0));
|
||||
let Some(&[x1, y1]) = fig.iter().find(|p| **p != fig[0]) else { return true };
|
||||
let (dx, dy) = (i64::from(x1) - x0, i64::from(y1) - y0);
|
||||
fig.iter().all(|&[x, y]| dx * (i64::from(y) - y0) == dy * (i64::from(x) - x0))
|
||||
}
|
||||
|
||||
struct Writer {
|
||||
pic: PictWriter,
|
||||
/// Document space to device units.
|
||||
to_dev: Affine,
|
||||
/// Device units a point.
|
||||
k: f64,
|
||||
/// The frame in document space, a little larger: art is cut to it.
|
||||
cut: Rect,
|
||||
/// The frame in device units.
|
||||
frame: Rect,
|
||||
lost: Pict,
|
||||
}
|
||||
|
||||
/// Write `ops` (no clips: [`crate::scene::Scene`] gives none for this format) as a PICT file of
|
||||
/// `region` (corners in order, finite, with an area). The picture frame is the region's size in
|
||||
/// whole points, and the device frame is that times the device units a point, so a reader maps
|
||||
/// one onto the other without scaling the drawing. A region [`check_region`] refuses is refused.
|
||||
pub(crate) fn write(ops: &[Op], region: Rect) -> Result<Pict, String> {
|
||||
check_region(region)?;
|
||||
let size = |v: f64| (v.round()).clamp(1.0, MAX_I16) as i16;
|
||||
let (w, h) = (size(region.width()), size(region.height()));
|
||||
let k = units_per_point(f64::from(w), f64::from(h));
|
||||
let units = k as i16;
|
||||
let pic = PictWriter::new(w, h, units).ok_or("PICT pictures are at most 32,767 points on a side")?;
|
||||
let mut wr = Writer {
|
||||
pic,
|
||||
to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()),
|
||||
k,
|
||||
cut: Rect::from_origin_size(region.origin(), (f64::from(w), f64::from(h))).inflate(1.0, 1.0),
|
||||
frame: Rect::new(0.0, 0.0, f64::from(w) * k, f64::from(h) * k),
|
||||
lost: Pict::default(),
|
||||
};
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Fill { path, rule, rgb, .. } => wr.fill(path, *rule, *rgb),
|
||||
Op::Stroke { path, pen } => wr.stroke(path, pen),
|
||||
Op::Image { image, xf, opacity } => wr.image(image, *xf, *opacity),
|
||||
Op::Clip { .. } | Op::Unclip => {}
|
||||
}
|
||||
}
|
||||
Ok(Pict { bytes: wr.pic.finish(), ..wr.lost })
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
/// `path` filled by `rule`, as polygons QuickDraw fills even-odd: cut to the frame (which also
|
||||
/// resolves a non-zero fill into figures that don't overlap) unless it is an even-odd fill
|
||||
/// inside the frame already.
|
||||
fn fill(&mut self, path: &BezPath, rule: FillRule, rgb: [u8; 3]) {
|
||||
let b = path.bounding_box();
|
||||
let c = self.cut;
|
||||
if ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) || b.x0 >= c.x1 || c.x0 >= b.x1 || b.y0 >= c.y1 || c.y0 >= b.y1 {
|
||||
return;
|
||||
}
|
||||
let inside = self.cut.contains(b.origin()) && self.cut.contains(Point::new(b.x1, b.y1));
|
||||
let clean = if rule == FillRule::EvenOdd && inside {
|
||||
path.clone()
|
||||
} else {
|
||||
let cut = PathData::from_bezpath(&self.cut.to_path(0.1));
|
||||
match vectorcraft_pathops::try_boolean(
|
||||
&PathData::from_bezpath(path),
|
||||
rule,
|
||||
&cut,
|
||||
FillRule::NonZero,
|
||||
vectorcraft_pathops::BoolOp::Intersect,
|
||||
vectorcraft_pathops::DEFAULT_PRECISION,
|
||||
) {
|
||||
Ok(p) => p.to_bezpath(),
|
||||
// Too complex to resolve: written as it is, filled even-odd, its coordinates kept
|
||||
// within 16 bits.
|
||||
Err(_) => {
|
||||
self.lost.unresolved_fills |= rule == FillRule::NonZero;
|
||||
let d = self.to_dev.transform_rect_bbox(b);
|
||||
self.lost.uncut_fills |= [d.x0, d.y0, d.x1, d.y1].iter().any(|v| v.abs() > MAX_I16);
|
||||
path.clone()
|
||||
}
|
||||
}
|
||||
};
|
||||
self.polygons(&clean, rgb);
|
||||
}
|
||||
|
||||
/// A stroke's outline (`vectorcraft_effects::stroke::line_outline`, with its dashes, caps,
|
||||
/// joins and miter limit), filled non-zero in its color as [`Writer::fill`] fills. A stroke
|
||||
/// thinner than a device unit is written one unit wide.
|
||||
fn stroke(&mut self, path: &BezPath, pen: &Pen) {
|
||||
if !(pen.width.is_finite() && pen.width > 0.0) {
|
||||
return;
|
||||
}
|
||||
let width = pen.width.max(1.0 / self.k);
|
||||
let mut st = StrokeLayer::new(Paint::None, width);
|
||||
st.cap = pen.cap;
|
||||
st.join = pen.join;
|
||||
st.miter_limit = pen.miter;
|
||||
st.dash = pen.dash.clone();
|
||||
let outline = vectorcraft_effects::stroke::line_outline(path, &st, width, FLATNESS / self.k);
|
||||
self.fill(&outline, FillRule::NonZero, pen.rgb);
|
||||
}
|
||||
|
||||
/// The figures of `path` (document space) in device units, flattened to within `flatness`
|
||||
/// device units, each without repeated points and with three or more.
|
||||
fn figures(&self, path: &BezPath, flatness: f64) -> Vec<Vec<[i16; 2]>> {
|
||||
let mut figs: Vec<Vec<[i16; 2]>> = vec![];
|
||||
let mut cur: Vec<[i16; 2]> = vec![];
|
||||
let mut done = |cur: &mut Vec<[i16; 2]>| {
|
||||
if cur.len() > 1 && cur.first() == cur.last() {
|
||||
cur.pop();
|
||||
}
|
||||
if cur.len() > 2 {
|
||||
figs.push(std::mem::take(cur));
|
||||
}
|
||||
cur.clear();
|
||||
};
|
||||
let dev = self.to_dev * path.clone();
|
||||
vectorcraft_geom::flatten(dev.iter(), flatness, |el| match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
done(&mut cur);
|
||||
cur.push([i16_of(p.x), i16_of(p.y)]);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
let q = [i16_of(p.x), i16_of(p.y)];
|
||||
if cur.last() != Some(&q) {
|
||||
cur.push(q);
|
||||
}
|
||||
}
|
||||
PathEl::ClosePath => done(&mut cur),
|
||||
_ => {}
|
||||
});
|
||||
done(&mut cur);
|
||||
figs
|
||||
}
|
||||
|
||||
/// `path` painted as polygons. All its figures go into one polygon, which returns along the
|
||||
/// lines between them: each such line is crossed twice and changes nothing in an even-odd
|
||||
/// fill. A path with more points than a polygon holds is flattened more coarsely, and past
|
||||
/// that split into several polygons.
|
||||
fn polygons(&mut self, path: &BezPath, rgb: [u8; 3]) {
|
||||
let count = |figs: &[Vec<[i16; 2]>]| figs.iter().map(|f| f.len() + 2).sum::<usize>();
|
||||
let mut flatness = FLATNESS;
|
||||
let mut figs = self.figures(path, flatness);
|
||||
let mut coarsened = false;
|
||||
for _ in 0..COARSER {
|
||||
if count(&figs) <= MAX_POLY_POINTS {
|
||||
break;
|
||||
}
|
||||
flatness *= 4.0;
|
||||
coarsened = false;
|
||||
figs = vectorcraft_geom::bez::subpaths(path)
|
||||
.into_iter()
|
||||
.flat_map(|(range, _)| {
|
||||
let subpath = BezPath::from_vec(path.elements()[range].to_vec());
|
||||
let coarse = self.figures(&subpath, flatness);
|
||||
// A small curved figure can collapse to two points, or to points on one line.
|
||||
// Keep its finer outline rather than lose its area; splitting and thinning
|
||||
// still bound polygon size.
|
||||
if coarse.is_empty() || coarse.iter().any(|fig| collinear(fig)) {
|
||||
self.figures(&subpath, FLATNESS)
|
||||
} else {
|
||||
coarsened |= subpath.elements().iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..)));
|
||||
coarse
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
if figs.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.lost.coarsened_fills |= coarsened;
|
||||
let mut group: Vec<&[[i16; 2]]> = vec![];
|
||||
let mut points = 0;
|
||||
let thinned: Vec<Vec<[i16; 2]>> = figs
|
||||
.iter()
|
||||
.map(|fig| {
|
||||
// A figure no polygon holds keeps evenly spaced points, as many as one holds.
|
||||
let n = fig.len();
|
||||
if n + 2 <= MAX_POLY_POINTS {
|
||||
return fig.clone();
|
||||
}
|
||||
self.lost.thinned_fills = true;
|
||||
let keep = MAX_POLY_POINTS - 2;
|
||||
(0..keep).map(|i| fig[i * n / keep]).collect()
|
||||
})
|
||||
.collect();
|
||||
for fig in &thinned {
|
||||
if !group.is_empty() && points + fig.len() + 2 > MAX_POLY_POINTS {
|
||||
self.lost.split_fills = true;
|
||||
self.poly(rgb, &group);
|
||||
group.clear();
|
||||
points = 0;
|
||||
}
|
||||
points += fig.len() + 2;
|
||||
group.push(fig);
|
||||
}
|
||||
self.poly(rgb, &group);
|
||||
}
|
||||
|
||||
/// One polygon of `figs` in `rgb`. Each figure is counted above at two points more than
|
||||
/// [`PictWriter::paint_poly`] adds for it, so every group fits one polygon and is written.
|
||||
fn poly(&mut self, rgb: [u8; 3], figs: &[&[[i16; 2]]]) {
|
||||
let _written = self.pic.paint_poly(rgb, figs);
|
||||
}
|
||||
|
||||
/// An image placed by `xf`, over white. Mirrored and quarter-turned images keep their
|
||||
/// placement; other turns and skews are written upright, filling their bounds.
|
||||
fn image(&mut self, img: &Arc<Image>, xf: Affine, opacity: f32) {
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
if w == 0 || h == 0 || opacity <= 0.0 || img.rgba.len() < w * h * 4 {
|
||||
return;
|
||||
}
|
||||
let m = self.to_dev * xf;
|
||||
let [a, b, c, d, e, f] = m.as_coeffs();
|
||||
if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let tiny = |v: f64| v.abs() < 1e-9;
|
||||
// Output pixel (x, y) shows source pixel `src(x, y)`, in an output `ow` × `oh`.
|
||||
let swapped = tiny(a) && tiny(d) && !tiny(b) && !tiny(c);
|
||||
let upright = tiny(b) && tiny(c) && !tiny(a) && !tiny(d);
|
||||
if !(upright || swapped) {
|
||||
self.lost.turned_images = true;
|
||||
}
|
||||
let (ow, oh) = if swapped { (h, w) } else { (w, h) };
|
||||
let (flip_x, flip_y) = if swapped { (c < 0.0, b < 0.0) } else { (upright && a < 0.0, upright && d < 0.0) };
|
||||
let src = |x: usize, y: usize| {
|
||||
let (x, y) = (if flip_x { ow - 1 - x } else { x }, if flip_y { oh - 1 - y } else { y });
|
||||
if swapped { (y, x) } else { (x, y) }
|
||||
};
|
||||
let dst = m.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64));
|
||||
// The device edges of output columns and rows, and the ones that reach into the frame.
|
||||
let edge = |from: f64, to: f64, n: usize, i: usize| from + (to - from) * i as f64 / n as f64;
|
||||
let span = |from: f64, to: f64, n: usize, lo: f64, hi: f64| {
|
||||
let first = (0..n).find(|&i| edge(from, to, n, i + 1) > lo);
|
||||
let last = (0..n).rev().find(|&i| edge(from, to, n, i) < hi);
|
||||
match (first, last) {
|
||||
(Some(f), Some(l)) if f <= l => Some((f, l + 1)),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let (Some((x0, x1)), Some((y0, y1))) =
|
||||
(span(dst.x0, dst.x1, ow, self.frame.x0, self.frame.x1), span(dst.y0, dst.y1, oh, self.frame.y0, self.frame.y1))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let alpha = opacity.clamp(0.0, 1.0);
|
||||
let mut translucent = false;
|
||||
let mut pixel = |x: usize, y: usize| {
|
||||
let (sx, sy) = src(x, y);
|
||||
let i = (sy * w + sx) * 4;
|
||||
let p = &img.rgba[i..i + 4];
|
||||
let a = f32::from(p[3]) / 255.0 * alpha;
|
||||
if a < OPAQUE {
|
||||
translucent = true;
|
||||
}
|
||||
[0, 1, 2].map(|c| (f32::from(p[c]) * a + 255.0 * (1.0 - a)).round() as u8)
|
||||
};
|
||||
// Tiles of up to `TILE` columns (rows). The edges between the visible columns lie in the
|
||||
// frame; an outer edge past 16 bits is moved in, so its column (row) is a tile of its own,
|
||||
// one color however far it is stretched.
|
||||
let tiles = |from: f64, to: f64, n: usize, first: usize, end: usize| {
|
||||
let far = |i: usize| edge(from, to, n, i).abs() > MAX_I16;
|
||||
let mut cuts = vec![];
|
||||
let (mut i, mut stop) = (first, end);
|
||||
if far(i) && i + 1 < stop {
|
||||
cuts.push((i, i + 1));
|
||||
i += 1;
|
||||
}
|
||||
let last = (far(stop) && i + 1 < stop).then(|| {
|
||||
stop -= 1;
|
||||
(stop, stop + 1)
|
||||
});
|
||||
while i < stop {
|
||||
let next = (i + TILE).min(stop);
|
||||
cuts.push((i, next));
|
||||
i = next;
|
||||
}
|
||||
cuts.extend(last);
|
||||
cuts
|
||||
};
|
||||
for (ty, ty1) in tiles(dst.y0, dst.y1, oh, y0, y1) {
|
||||
for (tx, tx1) in tiles(dst.x0, dst.x1, ow, x0, x1) {
|
||||
let rect = [
|
||||
i16_of(edge(dst.x0, dst.x1, ow, tx)),
|
||||
i16_of(edge(dst.y0, dst.y1, oh, ty)),
|
||||
i16_of(edge(dst.x0, dst.x1, ow, tx1)),
|
||||
i16_of(edge(dst.y0, dst.y1, oh, ty1)),
|
||||
];
|
||||
if rect[2] > rect[0] && rect[3] > rect[1] {
|
||||
let pixels: Vec<[u8; 3]> = (ty..ty1).flat_map(|y| (tx..tx1).map(move |x| (x, y))).map(|(x, y)| pixel(x, y)).collect();
|
||||
// Tiles are at most `TILE` pixels a side and `rect` has an area, so the
|
||||
// pixel map is written.
|
||||
let _written = self.pic.direct_bits(tx1 - tx, ty1 - ty, &pixels, rect);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.lost.translucent_images |= translucent;
|
||||
}
|
||||
}
|
||||
@@ -483,6 +483,9 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
|
||||
fn stroke(&mut self, bp: &BezPath, rule: FillRule, st: &StrokeLayer, bounds: Rect) {
|
||||
if st.blend != BlendMode::Normal {
|
||||
self.warn(BLENDING);
|
||||
}
|
||||
if st.brush.is_some()
|
||||
&& self.nest < MAX_NEST
|
||||
&& let Some(art) = self.brush_art(bp, st)
|
||||
@@ -495,9 +498,6 @@ impl<'a> Scene<'a> {
|
||||
self.opacity = opacity;
|
||||
return;
|
||||
}
|
||||
if st.blend != BlendMode::Normal {
|
||||
self.warn(BLENDING);
|
||||
}
|
||||
// A pen paints one colour along the path itself: anything else is the stroke's outline,
|
||||
// filled.
|
||||
let flat_paint = matches!(st.paint, Paint::Solid { .. }) || !self.clips;
|
||||
|
||||
@@ -16,6 +16,7 @@ use crate::*;
|
||||
mod cgm;
|
||||
mod import;
|
||||
mod pict;
|
||||
mod pict_export;
|
||||
|
||||
/// Add `n` (with a fresh id) on top of `d`'s first layer.
|
||||
pub(crate) fn add(d: &mut Document, mut n: Node) {
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
//! PICT output read back through `craft_metafile`'s QuickDraw reader: the frame and resolution,
|
||||
//! fills and their fill rules, strokes, images and their placement, and what the format leaves
|
||||
//! out.
|
||||
|
||||
use craft_metafile::{Item, Seg};
|
||||
use vectorcraft_geom::{BezPath, FillRule, Shape};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn pict(d: &Document) -> Output {
|
||||
export(d, d.artboards[0].rect, Kind::Pict).unwrap()
|
||||
}
|
||||
|
||||
fn read(out: &Output) -> craft_metafile::Picture {
|
||||
let pic = craft_metafile::parse_pict(&out.bytes).unwrap();
|
||||
assert!(!pic.truncated && pic.skipped_records == 0 && pic.dropped_images == 0, "{pic:?}");
|
||||
pic
|
||||
}
|
||||
|
||||
fn bez(segs: &[Seg]) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
for s in segs {
|
||||
match *s {
|
||||
Seg::Move(x, y) => bp.move_to((f64::from(x), f64::from(y))),
|
||||
Seg::Line(x, y) => bp.line_to((f64::from(x), f64::from(y))),
|
||||
Seg::Cubic(a, b, c, d, e, f) => bp.curve_to((f64::from(a), f64::from(b)), (f64::from(c), f64::from(d)), (f64::from(e), f64::from(f))),
|
||||
Seg::Close => bp.close_path(),
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// The filled paths of `pic`: their outline and their color.
|
||||
fn fills(pic: &craft_metafile::Picture) -> Vec<(BezPath, [u8; 4])> {
|
||||
pic.items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
Item::Path { segs, fill: Some(c), stroke: None, .. } => Some((bez(segs), *c)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Is `p` painted by one of `pic`'s fills, each filled even-odd as QuickDraw fills polygons?
|
||||
fn painted(pic: &craft_metafile::Picture, p: (f64, f64)) -> bool {
|
||||
fills(pic).iter().any(|(bp, _)| bp.winding(p.into()) % 2 != 0)
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect, tol: f64) -> bool {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() <= tol)
|
||||
}
|
||||
|
||||
fn compound(parts: &[BezPath], rule: FillRule) -> Node {
|
||||
let mut bp = BezPath::new();
|
||||
parts.iter().for_each(|p| bp.extend(p.iter()));
|
||||
let mut n = path(PathData::from_bezpath(&bp), red(), Paint::None, 0.0);
|
||||
if let NodeKind::Path { rule: r, .. } = &mut n.kind {
|
||||
*r = rule;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn square(x0: f64, y0: f64, x1: f64, y1: f64, clockwise: bool) -> BezPath {
|
||||
let mut pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)];
|
||||
if !clockwise {
|
||||
pts.reverse();
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(pts[0]);
|
||||
pts[1..].iter().for_each(|p| bp.line_to(*p));
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
/// Walk the writer's version 2 opcodes and collect their PaintPoly data.
|
||||
fn paint_polys(bytes: &[u8]) -> Vec<&[u8]> {
|
||||
let word = |at: usize| u16::from_be_bytes(bytes[at..at + 2].try_into().unwrap());
|
||||
let mut at = 522; // Application data, picSize, and frame.
|
||||
let mut polys = vec![];
|
||||
loop {
|
||||
at += at % 2;
|
||||
let opcode = word(at);
|
||||
at += 2;
|
||||
let len = match opcode {
|
||||
0x0011 => {
|
||||
assert_eq!(word(at), 0x02FF);
|
||||
2
|
||||
}
|
||||
0x0C00 => 24,
|
||||
0x0001 => usize::from(word(at)),
|
||||
0x0008 => 2,
|
||||
0x0009 => 8,
|
||||
0x001A => 6,
|
||||
0x0071 => {
|
||||
let len = usize::from(word(at));
|
||||
polys.push(&bytes[at..at + len]);
|
||||
len
|
||||
}
|
||||
0x009A => {
|
||||
let row_bytes = usize::from(word(at + 4) & 0x3FFF);
|
||||
let rows = usize::from(word(at + 10) - word(at + 6));
|
||||
let mut end = at + 68; // PixMap, source and destination rectangles, mode.
|
||||
for _ in 0..rows {
|
||||
if row_bytes < 8 {
|
||||
end += row_bytes;
|
||||
} else if row_bytes > 250 {
|
||||
end += 2 + usize::from(word(end));
|
||||
} else {
|
||||
end += 1 + usize::from(bytes[end]);
|
||||
}
|
||||
}
|
||||
end - at
|
||||
}
|
||||
0x00FF => {
|
||||
assert_eq!(at, bytes.len());
|
||||
return polys;
|
||||
}
|
||||
_ => panic!("unexpected PICT opcode {opcode:#06X}"),
|
||||
};
|
||||
at += len;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pict_frame_is_the_region_in_points_and_art_lands_within_a_sixteenth_of_a_point() {
|
||||
let r = Rect::new(10.5, 20.25, 100.0, 50.0);
|
||||
let d = doc_with(612.0, 792.0, vec![path(shapes::rectangle(r), red(), Paint::None, 0.0)]);
|
||||
let out = pict(&d);
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
// 512 bytes of application data, then the frame (top, left, bottom, right) at 72 dpi and the
|
||||
// version 2 opcodes.
|
||||
assert_eq!(out.bytes[514..522], [0, 0, 0, 0, 3, 24, 2, 100]);
|
||||
assert_eq!(out.bytes[522..528], [0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]);
|
||||
let pic = read(&out);
|
||||
assert_eq!((pic.width, pic.height), (612.0, 792.0));
|
||||
let f = fills(&pic);
|
||||
assert_eq!(f.len(), 1, "{f:?}");
|
||||
assert_eq!(f[0].1, [255, 0, 0, 255]);
|
||||
assert!(near(f[0].0.bounding_box(), r, 1.0 / 16.0), "{:?}", f[0].0.bounding_box());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pict_fractional_artboards_keep_art_within_a_sixteenth_of_a_point() {
|
||||
let r = Rect::new(20.25, 10.5, 80.0, 50.0);
|
||||
let d = doc_with(100.4, 60.7, vec![path(shapes::rectangle(r), red(), Paint::None, 0.0)]);
|
||||
let pic = read(&pict(&d));
|
||||
let artboard = d.artboards[0].rect;
|
||||
assert_eq!((pic.width, pic.height), (artboard.width().round() as f32, artboard.height().round() as f32));
|
||||
let f = fills(&pic);
|
||||
assert_eq!(f.len(), 1, "{f:?}");
|
||||
assert!(near(f[0].0.bounding_box(), r, 1.0 / 16.0), "{:?}", f[0].0.bounding_box());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_keep_their_holes_and_non_zero_overlaps() {
|
||||
let even_odd = compound(&[square(10.0, 10.0, 90.0, 90.0, true), square(30.0, 30.0, 70.0, 70.0, true)], FillRule::EvenOdd);
|
||||
let mut d = doc_with(300.0, 100.0, vec![even_odd]);
|
||||
// Two overlapping squares drawn the same way round: non-zero fills where they overlap.
|
||||
add(&mut d, compound(&[square(110.0, 10.0, 150.0, 50.0, true), square(130.0, 30.0, 170.0, 70.0, true)], FillRule::NonZero));
|
||||
// A square with a hole drawn the other way round.
|
||||
add(&mut d, compound(&[square(210.0, 10.0, 290.0, 90.0, true), square(230.0, 30.0, 270.0, 70.0, false)], FillRule::NonZero));
|
||||
let pic = read(&pict(&d));
|
||||
for (p, filled) in [
|
||||
((20.0, 20.0), true),
|
||||
((50.0, 50.0), false),
|
||||
((120.0, 20.0), true),
|
||||
((140.0, 40.0), true),
|
||||
((160.0, 60.0), true),
|
||||
((120.0, 60.0), false),
|
||||
((220.0, 20.0), true),
|
||||
((250.0, 50.0), false),
|
||||
] {
|
||||
assert_eq!(painted(&pic, p), filled, "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_off_the_frame_is_cut_to_it() {
|
||||
// Far enough out that its device coordinates would not fit 16 bits.
|
||||
let wide = path(shapes::rectangle(Rect::new(-5000.0, 10.0, 5000.0, 20.0)), red(), Paint::None, 0.0);
|
||||
let away = path(shapes::rectangle(Rect::new(400.0, 10.0, 410.0, 20.0)), blue(), Paint::None, 0.0);
|
||||
let pic = read(&pict(&doc_with(100.0, 100.0, vec![wide, away])));
|
||||
let f = fills(&pic);
|
||||
assert_eq!(f.len(), 1, "{f:?}");
|
||||
let b = f[0].0.bounding_box();
|
||||
assert!(b.x0 >= -1.0 && b.x1 <= 101.0 && near(Rect::new(0.0, b.y0, 100.0, b.y1), Rect::new(0.0, 10.0, 100.0, 20.0), 1.0 / 16.0), "{b:?}");
|
||||
assert!(painted(&pic, (1.0, 15.0)) && painted(&pic, (99.0, 15.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strokes_are_written_as_their_outlines() {
|
||||
let line = |y: f64| {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((10.0, y));
|
||||
bp.line_to((50.0, y));
|
||||
path(PathData::from_bezpath(&bp), Paint::None, blue(), 4.0)
|
||||
};
|
||||
let butt = line(20.0);
|
||||
let mut round = line(60.0);
|
||||
if let Some(s) = round.appearance.stroke_mut() {
|
||||
s.cap = LineCap::Round;
|
||||
}
|
||||
let pic = read(&pict(&doc_with(100.0, 100.0, vec![butt, round])));
|
||||
let f = fills(&pic);
|
||||
assert_eq!(f.len(), 2, "{f:?}");
|
||||
assert!(f.iter().all(|(_, c)| *c == [0, 0, 255, 255]));
|
||||
let tol = 1.0 / 8.0;
|
||||
assert!(near(f[0].0.bounding_box(), Rect::new(10.0, 18.0, 50.0, 22.0), tol), "{:?}", f[0].0.bounding_box());
|
||||
assert!(near(f[1].0.bounding_box(), Rect::new(8.0, 58.0, 52.0, 62.0), tol), "{:?}", f[1].0.bounding_box());
|
||||
// A stroke wider than the shape covers its interior.
|
||||
let dot = path(shapes::ellipse(Rect::new(45.0, 45.0, 55.0, 55.0)), Paint::None, blue(), 40.0);
|
||||
let pic = read(&pict(&doc_with(100.0, 100.0, vec![dot])));
|
||||
assert!(painted(&pic, (50.0, 50.0)) && painted(&pic, (50.0, 32.0)) && !painted(&pic, (50.0, 20.0)));
|
||||
}
|
||||
|
||||
/// A PNG of `w` × `h` pixels, `rgba` row by row.
|
||||
fn png_of(w: u32, h: u32, rgba: Vec<u8>) -> Vec<u8> {
|
||||
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap();
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// A bitmap read back: where it goes (`[x, y, w, h]`), its width and height in pixels, and its
|
||||
/// RGB pixels.
|
||||
type Bitmap = ([f32; 4], u32, u32, Vec<[u8; 3]>);
|
||||
|
||||
/// The bitmaps of `pic`.
|
||||
fn bitmaps(pic: &craft_metafile::Picture) -> Vec<Bitmap> {
|
||||
pic.items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
Item::Bitmap { rect, width, height, rgba, .. } => {
|
||||
Some((*rect, *width, *height, rgba.as_chunks::<4>().0.iter().map(|p| [p[0], p[1], p[2]]).collect()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each pixel of a bitmap read back shows the pixel of `src` (`w` × `h`) that `xf` places under
|
||||
/// its center.
|
||||
fn shows(bitmap: &Bitmap, src: &[[u8; 3]], w: usize, xf: Affine) {
|
||||
let (rect, bw, bh, px) = bitmap;
|
||||
let inv = xf.inverse();
|
||||
let (cw, ch) = (f64::from(rect[2]) / f64::from(*bw), f64::from(rect[3]) / f64::from(*bh));
|
||||
for y in 0..*bh as usize {
|
||||
for x in 0..*bw as usize {
|
||||
let at = Point::new(f64::from(rect[0]) + (x as f64 + 0.5) * cw, f64::from(rect[1]) + (y as f64 + 0.5) * ch);
|
||||
let s = inv * at;
|
||||
let want = src[s.y.floor() as usize * w + s.x.floor() as usize];
|
||||
assert_eq!(px[y * *bw as usize + x], want, "pixel ({x}, {y}) at {at:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_keep_their_pixels_mirrored_and_quarter_turned() {
|
||||
let src: Vec<[u8; 3]> = vec![[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 255, 255], [255, 0, 255]];
|
||||
let bytes = png_of(3, 2, src.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect());
|
||||
let places = [
|
||||
Affine::translate((10.0, 10.0)) * Affine::scale(4.0),
|
||||
Affine::translate((40.0, 10.0)) * Affine::scale_non_uniform(-4.0, 4.0),
|
||||
Affine::translate((60.0, 10.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale(4.0),
|
||||
Affine::translate((70.0, 60.0)) * Affine::rotate(-std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(4.0, -4.0),
|
||||
];
|
||||
let mut d = doc_with(100.0, 100.0, vec![]);
|
||||
for xf in places {
|
||||
let n = image_node(&mut d, bytes.clone(), 3, 2, xf);
|
||||
add(&mut d, n);
|
||||
}
|
||||
let out = pict(&d);
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
let bm = bitmaps(&read(&out));
|
||||
assert_eq!(bm.len(), places.len());
|
||||
for (b, xf) in bm.iter().zip(places) {
|
||||
let want = xf.transform_rect_bbox(Rect::new(0.0, 0.0, 3.0, 2.0));
|
||||
let got = Rect::new(f64::from(b.0[0]), f64::from(b.0[1]), f64::from(b.0[0] + b.0[2]), f64::from(b.0[1] + b.0[3]));
|
||||
assert!(near(got, want, 1.0 / 16.0), "{got:?} {want:?}");
|
||||
shows(b, &src, 3, xf);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turned_and_translucent_images_are_reported() {
|
||||
let mut d = doc_with(100.0, 100.0, vec![]);
|
||||
// One pixel: a row narrower than two pixels is stored unpacked.
|
||||
let half = image_node(&mut d, png(1, 1, [0, 0, 0, 128]), 1, 1, Affine::translate((10.0, 10.0)) * Affine::scale(10.0));
|
||||
add(&mut d, half);
|
||||
let out = pict(&d);
|
||||
assert_eq!(out.warnings, ["PICT has no transparency: images are written over white"]);
|
||||
let bm = bitmaps(&read(&out));
|
||||
assert_eq!(bm.len(), 1);
|
||||
assert_eq!(bm[0].3, [[127, 127, 127]]);
|
||||
let turned = image_node(&mut d, png(2, 2, [0, 0, 0, 255]), 2, 2, Affine::translate((50.0, 50.0)) * Affine::rotate(0.5));
|
||||
add(&mut d, turned);
|
||||
assert!(pict(&d).warnings.iter().any(|w| w.contains("quarter turns")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brushed_stroke_reports_its_blending_mode() {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((10.0, 50.0));
|
||||
bp.line_to((90.0, 50.0));
|
||||
let plain = path(PathData::from_bezpath(&bp), Paint::None, blue(), 3.0);
|
||||
let mut line = plain.clone();
|
||||
if let Some(s) = line.appearance.stroke_mut() {
|
||||
s.brush = Some("3 pt. Round".into());
|
||||
s.blend = vectorcraft_color::BlendMode::Multiply;
|
||||
}
|
||||
let out = pict(&doc_with(100.0, 100.0, vec![line]));
|
||||
assert!(!fills(&read(&out)).is_empty(), "the brush's art is written");
|
||||
// A brush that doesn't resolve falls back to the stroke's outline.
|
||||
let mut unresolved = plain;
|
||||
if let Some(s) = unresolved.appearance.stroke_mut() {
|
||||
s.brush = Some("missing".into());
|
||||
s.blend = vectorcraft_color::BlendMode::Multiply;
|
||||
}
|
||||
let fallback = pict(&doc_with(100.0, 100.0, vec![unresolved]));
|
||||
assert_ne!(out.bytes, fallback.bytes, "the brush resolves, so its art is written rather than the fallback outline");
|
||||
assert!(out.warnings.iter().any(|w| w.contains("blending modes are left out")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_images_are_written_in_tiles() {
|
||||
let (w, h) = (1500usize, 3usize);
|
||||
// Red changes along each row and green stays the same over long runs: both literal and
|
||||
// repeated bytes are packed, in rows longer than 250 bytes.
|
||||
let src: Vec<[u8; 3]> = (0..w * h).map(|i| [(i % w % 256) as u8, (i % w / 256) as u8, (i / w * 60) as u8]).collect();
|
||||
let mut d = doc_with(100.0, 100.0, vec![]);
|
||||
// A pixel a device unit (a sixteenth of a point) wide.
|
||||
let xf = Affine::translate((5.0, 5.0)) * Affine::scale(0.0625);
|
||||
let n = image_node(&mut d, png_of(w as u32, h as u32, src.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect()), w as u32, h as u32, xf);
|
||||
add(&mut d, n);
|
||||
let bm = bitmaps(&read(&pict(&d)));
|
||||
assert_eq!(bm.iter().map(|b| (b.1, b.2)).collect::<Vec<_>>(), [(1024, 3), (476, 3)]);
|
||||
for b in &bm {
|
||||
shows(b, &src, w, xf);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pict_polygon_sizes_fit_a_signed_word() {
|
||||
// 8,800 figure points, plus closing points and bridges, fit the old unsigned limit.
|
||||
let squares: Vec<BezPath> = (0..2200)
|
||||
.map(|i| (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0))
|
||||
.map(|(x, y)| square(x, y, x + 1.0, y + 1.0, true))
|
||||
.collect();
|
||||
let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::EvenOdd)]));
|
||||
let polys = paint_polys(&out.bytes);
|
||||
assert!(!polys.is_empty());
|
||||
for poly in polys {
|
||||
let size = i16::from_be_bytes(poly[..2].try_into().unwrap());
|
||||
assert!(size > 0, "polySize must be a positive signed byte count: {size}");
|
||||
let (points, remainder) = poly[10..].as_chunks::<4>();
|
||||
assert!(remainder.is_empty());
|
||||
assert!(!points.is_empty());
|
||||
assert_eq!(size as usize, 10 + 4 * points.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pict_warns_when_curved_fills_fit_only_after_coarsening() {
|
||||
// At the finest flatness the circles hold more points than one polygon; coarser, they fit.
|
||||
let circles: Vec<BezPath> = (0..900)
|
||||
.map(|i| {
|
||||
let center = (f64::from(i % 30) * 4.5 + 5.0, f64::from(i / 30) * 4.5 + 5.0);
|
||||
vectorcraft_geom::kurbo::Circle::new(center, 2.0).to_path(0.01)
|
||||
})
|
||||
.collect();
|
||||
let small = pict(&doc_with(140.0, 140.0, vec![compound(&circles[..1], FillRule::EvenOdd)]));
|
||||
assert!(small.warnings.is_empty(), "{:?}", small.warnings);
|
||||
let out = pict(&doc_with(140.0, 140.0, vec![compound(&circles, FillRule::EvenOdd)]));
|
||||
assert!(out.warnings.iter().any(|w| w.contains("curves flattened more coarsely")), "{:?}", out.warnings);
|
||||
assert!(!out.warnings.iter().any(|w| w.contains("several polygons")), "{:?}", out.warnings);
|
||||
assert_eq!(paint_polys(&out.bytes).len(), 1);
|
||||
let pic = read(&out);
|
||||
assert!(painted(&pic, (5.0, 5.0)) && painted(&pic, (135.5, 135.5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pict_coarse_flattening_keeps_small_curved_figures() {
|
||||
// Even four points per lens, plus closing points and bridges, exceed one polygon.
|
||||
// At the coarsest flatness both curves become lines between the same two endpoints.
|
||||
let lenses: Vec<BezPath> = (0..2200)
|
||||
.map(|i| {
|
||||
let (x, y) = (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0);
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((x, y));
|
||||
bp.quad_to((x + 0.5, y - 0.5), (x + 1.0, y));
|
||||
bp.quad_to((x + 0.5, y + 0.5), (x, y));
|
||||
bp.close_path();
|
||||
bp
|
||||
})
|
||||
.collect();
|
||||
let out = pict(&doc_with(100.0, 100.0, vec![compound(&lenses, FillRule::EvenOdd)]));
|
||||
let pic = read(&out);
|
||||
for i in [0, lenses.len() / 2, lenses.len() - 1] {
|
||||
let p = lenses[i].bounding_box().center();
|
||||
assert!(painted(&pic, (p.x, p.y)), "lens {i} was lost");
|
||||
}
|
||||
assert!(fills(&pic).len() > 1);
|
||||
assert!(out.warnings.iter().any(|w| w.contains("several polygons")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pict_coarse_flattening_keeps_figures_that_become_one_line() {
|
||||
// At the coarsest flatness the curve becomes a line, and its three points lie on one line.
|
||||
let bumps: Vec<BezPath> = (0..2200)
|
||||
.map(|i| {
|
||||
let (x, y) = (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0);
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((x, y));
|
||||
bp.quad_to((x + 0.5, y - 0.5), (x + 1.0, y));
|
||||
bp.line_to((x + 0.5, y));
|
||||
bp.close_path();
|
||||
bp
|
||||
})
|
||||
.collect();
|
||||
let out = pict(&doc_with(100.0, 100.0, vec![compound(&bumps, FillRule::EvenOdd)]));
|
||||
let pic = read(&out);
|
||||
for i in [0_u32, 1100, 2199] {
|
||||
let (x, y) = (f64::from(i % 50) * 1.5 + 1.0, f64::from(i / 50) * 1.5 + 1.0);
|
||||
assert!(painted(&pic, (x + 0.5, y - 0.1)), "bump {i} was lost");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_past_one_polygon_is_split_or_thinned() {
|
||||
// 3,000 separate squares: more points than one polygon holds.
|
||||
let squares: Vec<BezPath> = (0..3000)
|
||||
.map(|i| (f64::from(i % 60) * 1.5 + 1.0, f64::from(i / 60) * 1.5 + 1.0))
|
||||
.map(|(x, y)| square(x, y, x + 1.0, y + 1.0, true))
|
||||
.collect();
|
||||
let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::EvenOdd)]));
|
||||
assert!(out.warnings.iter().any(|w| w.contains("several polygons")), "{:?}", out.warnings);
|
||||
let pic = read(&out);
|
||||
assert!(fills(&pic).len() > 1);
|
||||
assert!(painted(&pic, (1.5, 1.5)) && painted(&pic, (59.0 * 1.5 + 1.5, 49.0 * 1.5 + 1.5)));
|
||||
// One outline of 20,000 points.
|
||||
let mut star = BezPath::new();
|
||||
for i in 0..20_000 {
|
||||
let t = f64::from(i) / 20_000.0 * std::f64::consts::TAU;
|
||||
let r = if i % 2 == 0 { 45.0 } else { 40.0 };
|
||||
let p = (50.0 + r * t.cos(), 50.0 + r * t.sin());
|
||||
if i == 0 { star.move_to(p) } else { star.line_to(p) }
|
||||
}
|
||||
star.close_path();
|
||||
let out = pict(&doc_with(100.0, 100.0, vec![compound(&[star], FillRule::EvenOdd)]));
|
||||
assert!(out.warnings.iter().any(|w| w.contains("fewer points")), "{:?}", out.warnings);
|
||||
let pic = read(&out);
|
||||
assert!(painted(&pic, (50.0, 50.0)) && !painted(&pic, (2.0, 2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_reaching_far_past_the_frame_keeps_its_columns_in_place() {
|
||||
// Two columns, each 2,550 pt wide: red ends at x = 50, well inside the frame, while the outer
|
||||
// edges lie past 16-bit device coordinates.
|
||||
let mut d = doc_with(100.0, 100.0, vec![]);
|
||||
let bytes = png_of(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]);
|
||||
let n = image_node(&mut d, bytes, 2, 1, Affine::translate((-2500.0, 10.0)) * Affine::scale_non_uniform(2550.0, 10.0));
|
||||
add(&mut d, n);
|
||||
let bm = bitmaps(&read(&pict(&d)));
|
||||
let color_at = |x: f64| {
|
||||
bm.iter().find_map(|(r, bw, _, px)| {
|
||||
let (x0, w) = (f64::from(r[0]), f64::from(r[2]));
|
||||
(x0..x0 + w).contains(&x).then(|| px[((x - x0) / w * f64::from(*bw)) as usize])
|
||||
})
|
||||
};
|
||||
assert_eq!(color_at(25.0), Some([255, 0, 0]), "{bm:?}");
|
||||
assert_eq!(color_at(49.0), Some([255, 0, 0]), "{bm:?}");
|
||||
assert_eq!(color_at(51.0), Some([0, 0, 255]), "{bm:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_zero_fill_too_complex_to_resolve_is_reported() {
|
||||
let squares: Vec<BezPath> = (0..1000).map(|_| square(10.0, 10.0, 50.0, 50.0, true)).collect();
|
||||
let out = pict(&doc_with(100.0, 100.0, vec![compound(&squares, FillRule::NonZero)]));
|
||||
assert!(out.warnings.iter().any(|w| w.contains("written even-odd")), "{:?}", out.warnings);
|
||||
// The same for a stroke whose outline can't be resolved: it is still written, not left out.
|
||||
let mut lines = BezPath::new();
|
||||
for _ in 0..1000 {
|
||||
lines.move_to((10.0, 50.0));
|
||||
lines.line_to((90.0, 50.0));
|
||||
}
|
||||
let out = pict(&doc_with(100.0, 100.0, vec![path(PathData::from_bezpath(&lines), Paint::None, blue(), 4.0)]));
|
||||
assert!(out.warnings.iter().any(|w| w.contains("written even-odd")), "{:?}", out.warnings);
|
||||
assert!(!fills(&read(&out)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pict_regions_over_32767_points_are_refused() {
|
||||
let d = doc_with(100.0, 100.0, vec![]);
|
||||
assert!(export(&d, Rect::new(0.0, 0.0, 40_000.0, 10.0), Kind::Pict).is_err());
|
||||
assert!(check_regions_for(&[Rect::new(0.0, 0.0, 40_000.0, 10.0)], Kind::Pict).is_err());
|
||||
assert!(check_regions_for(&[Rect::new(0.0, 0.0, 40_000.0, 10.0)], Kind::Emf).is_ok());
|
||||
assert!(export(&d, Rect::new(0.0, 0.0, 32_000.0, 10.0), Kind::Pict).is_ok());
|
||||
}
|
||||
@@ -3016,6 +3016,56 @@ fn photoshop_filters_on_content_larger_than_the_budget() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Glowing Edges scales every edge by the strongest one in the object, so a zoomed-in frame draws
|
||||
/// a point's glow as the whole object draws it. The object is a white 4 × 80 pt bar beside
|
||||
/// stripes 0.5 pt wide and 1 pt apart, whose edges lie close together and glow strongest, on
|
||||
/// black. At 400 % the whole object fits the pixel budget; at 6400 % a 200 × 200 view shows only
|
||||
/// the bar's left edge, and the stripes lie beyond what the effect reads around the view. The pans
|
||||
/// move the view 10 and 20 pixels, the second within the margin a raster made again at the same
|
||||
/// zoom keeps, which reaches the stripes.
|
||||
#[test]
|
||||
fn glowing_edges_zoomed_in_glow_as_bright_as_in_the_whole_object() {
|
||||
use vectorcraft_geom::{PathData, SubPath};
|
||||
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| {
|
||||
SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true)
|
||||
};
|
||||
let mut subpaths = vec![rect(10.0, 10.0, 14.0, 90.0)];
|
||||
subpaths.extend((0..30).map(|i| rect(16.0 + f64::from(i), 10.0, 16.5 + f64::from(i), 90.0)));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let mut ap = Appearance::basic(Paint::solid(Color::rgb(1.0, 1.0, 1.0)), Paint::None, 0.0);
|
||||
ap.effects =
|
||||
vec![Effect { id: "stylize.glowingEdges".into(), params: json!({"edgeWidth": 1, "edgeBrightness": 6, "smoothness": 1}), visible: true }];
|
||||
let n = Node::path(d.alloc_id(), PathData::new(subpaths), ap);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
let opts = RenderOptions { background: Some([0, 0, 0, 255]), ..Default::default() };
|
||||
// Just inside the bar's left edge.
|
||||
let at = Point::new(10.125, 50.0);
|
||||
let glow = |img: &Rendered, view: Affine| {
|
||||
let p = view * at;
|
||||
img.pixel(p.x.floor() as u32, p.y.floor() as u32)[0]
|
||||
};
|
||||
let whole_view = Affine::scale(4.0);
|
||||
let mut whole = Renderer::new();
|
||||
let whole_img = whole.render(&d, 400, 400, whole_view, &opts);
|
||||
assert_eq!(whole.stats.view_sized, 0, "at 400 % the whole object is one raster");
|
||||
let whole = glow(&whole_img, whole_view);
|
||||
let zoomed = |dx: f64| Affine::translate((100.0 - dx, 100.0)) * Affine::scale(64.0) * Affine::translate((-at.x, -at.y));
|
||||
let mut r = Renderer::new();
|
||||
let mut seen = vec![];
|
||||
for dx in [0.0, 10.0, 20.0] {
|
||||
let view = zoomed(dx);
|
||||
let panned = glow(&r.render(&d, 200, 200, view, &opts), view);
|
||||
let fresh = glow(&Renderer::new().render(&d, 200, 200, view, &opts), view);
|
||||
seen.push((dx, panned, fresh));
|
||||
assert!(panned.abs_diff(fresh) <= 2, "panned {dx} px, the frame draws the glow a fresh renderer draws: {seen:?}");
|
||||
}
|
||||
assert!(r.stats.view_sized > 0, "at 6400 % the object is over the pixel budget");
|
||||
for (dx, panned, _) in &seen {
|
||||
assert!(panned.abs_diff(whole) <= 24, "panned {dx} px, the glow is as bright as the whole object's {whole}: {seen:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5308: an image's Inner Glow follows its visible pixels, not its frame. A 40 × 40 image whose
|
||||
/// left half is transparent and right half opaque black, on a black page, with a white glow from
|
||||
/// the edges: the transparent half stays black, and the glow lights the opaque half's left edge
|
||||
|
||||
@@ -100,11 +100,9 @@ pub struct FontDb {
|
||||
colours: Mutex<GlyphColours>,
|
||||
/// The installed fonts: the system font scan's faces, found by any of their names
|
||||
/// ([`FontDb::catalog`]). Lookups by family name wait for its first scan, so what they find
|
||||
/// never depends on what ran before them. The bundled faces join it on the first call of
|
||||
/// [`FontDb::catalog`], so its faces are read through that call.
|
||||
/// never depends on what ran before them. It also holds the bundled faces, added when the
|
||||
/// database is made and read from the binary in place.
|
||||
catalog: Arc<Catalog>,
|
||||
/// The bundled faces were added to [`Self::catalog`].
|
||||
bundled_cataloged: std::sync::Once,
|
||||
/// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces,
|
||||
/// so no family name, font menu, fallback or PostScript name lookup finds them.
|
||||
pub(super) file_faces: RwLock<FileFaces>,
|
||||
@@ -399,14 +397,25 @@ mod bundled_catalog_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bundled_fonts_join_the_catalog_when_it_is_first_read() {
|
||||
fn the_bundled_fonts_are_in_the_catalog_from_the_start() {
|
||||
let db = FontDb::with_font_dirs(Vec::new());
|
||||
assert!(!db.read_faces().is_empty(), "the database draws with its bundled faces from the start");
|
||||
assert_eq!(bundled_in_catalog(&db.catalog), 0, "making the database copies no bundled font into the catalog");
|
||||
let added = bundled_in_catalog(&db.catalog);
|
||||
assert!(added > 0, "making the database adds the bundled fonts to the catalog");
|
||||
// The catalog reads each bundled face from the bytes in the binary, not from a copy.
|
||||
let embedded: Vec<*const u8> = super::face::BUNDLED.iter().map(|b| b.as_ptr()).collect();
|
||||
for face in db.catalog.faces().iter().filter(|f| f.source == craft::font_catalog::Source::Bundled) {
|
||||
let data = db.catalog.face_data(face).expect("a bundled face's bytes");
|
||||
let ptr = data.bytes().as_ptr();
|
||||
assert!(
|
||||
embedded.contains(&ptr) || crate::craft_fonts::document_fonts().iter().any(|f| f.bytes.as_ptr() == ptr),
|
||||
"{} {} is read from a copy of its font file",
|
||||
face.family,
|
||||
face.style
|
||||
);
|
||||
}
|
||||
// A lookup that only the catalog answers finds a bundled face.
|
||||
assert_eq!(db.by_postscript_name("SourceSans3-Bold"), Some(("Source Sans 3".to_string(), "Bold".to_string())));
|
||||
let added = bundled_in_catalog(&db.catalog);
|
||||
assert!(added > 0, "the first read of the catalog adds the bundled fonts");
|
||||
assert!(db.catalog().families().iter().any(|f| f == "Inter"), "font pickers list a bundled family");
|
||||
assert_eq!(bundled_in_catalog(db.catalog()), added, "later reads add them no second time");
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use craft::font_catalog::{Catalog, FontEnv, Limits, Os, Source};
|
||||
use craft::font_catalog::{Catalog, FontEnv, Os, Source};
|
||||
|
||||
use super::build::make_face;
|
||||
use super::cache::{CanonicalNames, GlyphCache};
|
||||
@@ -58,6 +58,11 @@ impl FontDb {
|
||||
faces.push(Arc::new(f));
|
||||
}
|
||||
}
|
||||
// The catalog reads the bytes in place, so font pickers list the bundled faces without a
|
||||
// second copy of them in memory.
|
||||
if let Err(e) = catalog.add_static(data, Source::Bundled) {
|
||||
log::warn!("a bundled font is not in the font catalog: {e}");
|
||||
}
|
||||
}
|
||||
Self {
|
||||
faces: RwLock::new(faces),
|
||||
@@ -65,7 +70,6 @@ impl FontDb {
|
||||
images: Mutex::new(GlyphCache::default()),
|
||||
colours: Mutex::new(GlyphCache::default()),
|
||||
catalog: Arc::new(catalog),
|
||||
bundled_cataloged: std::sync::Once::new(),
|
||||
file_faces: RwLock::new(super::FileFaces::default()),
|
||||
canonical_cache: Mutex::new(CanonicalNames::new()),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -121,19 +125,9 @@ impl FontDb {
|
||||
/// The installed fonts this database finds by name, shared with the framework's font menus and
|
||||
/// pickers. Its lookups wait for its first scan ([`FontDb::scan_in_background`]).
|
||||
///
|
||||
/// The first call adds the bundled fonts to it as [`Source::Bundled`] faces, so font pickers
|
||||
/// list them. A run that never looks a font up in the catalog, such as exporting a file without
|
||||
/// type, does not hold the catalog's copies of their bytes.
|
||||
// The catalog keeps its own copy of the bytes it is given. Adding the bundled fonts on first use
|
||||
// can go once the catalog takes static bytes without copying them (craft-libs#4888).
|
||||
/// It holds the bundled fonts as [`Source::Bundled`] faces, read from the binary in place, so
|
||||
/// font pickers list them.
|
||||
pub fn catalog(&self) -> &Arc<Catalog> {
|
||||
self.bundled_cataloged.call_once(|| {
|
||||
for data in bundled_fonts() {
|
||||
if let Err(e) = self.catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) {
|
||||
log::warn!("a bundled font is not in the font catalog: {e}");
|
||||
}
|
||||
}
|
||||
});
|
||||
&self.catalog
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool
|
||||
pub struct EyedropperTool {
|
||||
/// Sampling for the selected gradient stop: the tool to switch back to afterwards.
|
||||
stop: Option<String>,
|
||||
/// Sampling for the selected freeform point: the tool to switch back to afterwards.
|
||||
point: Option<String>,
|
||||
/// The Type tool's highlighted range while sampling, including its selection overlay.
|
||||
text_selection: crate::text::TypeTool,
|
||||
/// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`].
|
||||
@@ -567,8 +569,14 @@ impl Tool for EyedropperTool {
|
||||
}
|
||||
Click::Back(back) => {
|
||||
self.stop = None;
|
||||
self.point = None;
|
||||
vec![Action::SwitchTool(back)]
|
||||
}
|
||||
Click::SamplePoint(color, _, index, back) => {
|
||||
self.point = None;
|
||||
let params = json!({ "index": index, "stroke": !cx.fill_active, "color": color_json(&color), "keepModel": true });
|
||||
vec![Action::Exec("paint.freeform.setPoint".into(), params), Action::SwitchTool(back)]
|
||||
}
|
||||
Click::MeshPoints(id, points, color) => {
|
||||
let params = json!({ "id": id.0, "points": points, "color": color_json(&color), "keepModel": true });
|
||||
vec![Action::Exec("object.mesh.setPointColor".into(), params)]
|
||||
@@ -605,6 +613,9 @@ impl Tool for EyedropperTool {
|
||||
let mut options = if selected.get("editing").is_some_and(|v| !v.is_null()) { selected } else { json!({}) };
|
||||
if let Some(o) = options.as_object_mut() {
|
||||
o.insert("stop".into(), json!(self.stop));
|
||||
if let Some(back) = &self.point {
|
||||
o.insert("freeformPoint".into(), json!(back));
|
||||
}
|
||||
o.insert("brushKeyColor".into(), json!(self.brush_key_color));
|
||||
if let Some(binding) = &self.image_trace_ignore_color {
|
||||
o.insert("imageTraceIgnoreColor".into(), binding.clone());
|
||||
@@ -621,7 +632,18 @@ impl Tool for EyedropperTool {
|
||||
/// Type tool or a tool that picks mesh points.
|
||||
fn set_option(&mut self, key: &str, value: &Value) {
|
||||
match key {
|
||||
"stop" => self.stop = value.as_str().map(str::to_string),
|
||||
"stop" => {
|
||||
self.stop = value.as_str().map(str::to_string);
|
||||
if self.stop.is_some() {
|
||||
self.point = None;
|
||||
}
|
||||
}
|
||||
"freeformPoint" => {
|
||||
self.point = value.as_str().map(str::to_string);
|
||||
if self.point.is_some() {
|
||||
self.stop = None;
|
||||
}
|
||||
}
|
||||
"brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false),
|
||||
"imageTraceIgnoreColor" => self.image_trace_ignore_color = (!value.is_null()).then(|| value.clone()),
|
||||
"meshPoints" => self.mesh_points = crate::meshedit::points_of(value),
|
||||
@@ -633,7 +655,7 @@ impl Tool for EyedropperTool {
|
||||
fn check_option(&self, key: &str, value: &Value) -> Result<(), String> {
|
||||
use crate::option_check as c;
|
||||
match key {
|
||||
"stop" => c::string_or_null(key, value),
|
||||
"stop" | "freeformPoint" => c::string_or_null(key, value),
|
||||
"brushKeyColor" => c::boolean(key, value),
|
||||
"textSelection" => self.text_selection.check_option(key, value),
|
||||
_ => Err(c::unknown(key)),
|
||||
@@ -663,6 +685,9 @@ impl Tool for EyedropperTool {
|
||||
if key != ToolKey::Escape || !self.picking() {
|
||||
return vec![];
|
||||
}
|
||||
if let Some(back) = self.point.take() {
|
||||
return vec![Action::SwitchTool(back)];
|
||||
}
|
||||
if let Some(binding) = self.image_trace_ignore_color.take() {
|
||||
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
|
||||
return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "cancel": true })), Action::SwitchTool(back)];
|
||||
@@ -678,7 +703,7 @@ impl Tool for EyedropperTool {
|
||||
}
|
||||
|
||||
fn returns_to(&self) -> Option<&str> {
|
||||
self.stop.as_deref().filter(|_| !self.brush_key_color && self.image_trace_ignore_color.is_none())
|
||||
self.point.as_deref().or_else(|| self.stop.as_deref().filter(|_| !self.brush_key_color && self.image_trace_ignore_color.is_none()))
|
||||
}
|
||||
|
||||
/// Escape is the tool's while a pick is armed, so it switches back and ends nothing else.
|
||||
@@ -697,9 +722,10 @@ enum Click {
|
||||
ImageTrace(Value),
|
||||
/// Brush Options › Key Color: this color, sampled from this object.
|
||||
BrushKeyColor(Color, NodeId),
|
||||
/// A pick for a stop of the gradient a tool paints with (the Live Paint Bucket's, the Shape
|
||||
/// Builder's fill) that is no longer selected switches back to that tool unsampled.
|
||||
/// The pick's target is no longer valid. Return to the previous tool without sampling.
|
||||
Back(String),
|
||||
/// This color, sampled from this object, goes to the armed freeform point.
|
||||
SamplePoint(Color, NodeId, usize, String),
|
||||
/// The fill color goes to these points of this selected gradient mesh.
|
||||
MeshPoints(NodeId, Vec<usize>, Color),
|
||||
/// `appearance.copyFrom` this source, with `reverse` or `append` or neither.
|
||||
@@ -715,19 +741,28 @@ impl Click {
|
||||
fn object(&self) -> Option<NodeId> {
|
||||
match self {
|
||||
Click::ImageTrace(_) | Click::Back(_) => None,
|
||||
Click::BrushKeyColor(_, id) | Click::MeshPoints(id, ..) | Click::CopyFrom(id, _) | Click::Sample { source: id, .. } => Some(*id),
|
||||
Click::BrushKeyColor(_, id)
|
||||
| Click::SamplePoint(_, id, ..)
|
||||
| Click::MeshPoints(id, ..)
|
||||
| Click::CopyFrom(id, _)
|
||||
| Click::Sample { source: id, .. } => Some(*id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EyedropperTool {
|
||||
/// Is a gradient stop, Brush Key Color or Image Trace Ignore Color pick armed?
|
||||
/// Is a gradient stop, freeform point, Brush Key Color or Image Trace Ignore Color pick armed?
|
||||
fn picking(&self) -> bool {
|
||||
self.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some()
|
||||
self.stop.is_some() || self.point.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some()
|
||||
}
|
||||
|
||||
/// What a click at `p` with `mods` does, or None when it does nothing.
|
||||
fn click(&self, cx: &ToolContext, p: Point, mods: Mods) -> Option<Click> {
|
||||
if let Some(back) = &self.point {
|
||||
let Some(index) = cx.freeform_point else { return Some(Click::Back(back.clone())) };
|
||||
let (color, source) = sample_at(cx, p)?;
|
||||
return Some(Click::SamplePoint(color, source, index, back.clone()));
|
||||
}
|
||||
if let Some(binding) = &self.image_trace_ignore_color {
|
||||
return Some(Click::ImageTrace(binding.clone()));
|
||||
}
|
||||
|
||||
@@ -512,14 +512,26 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R
|
||||
// Where new art goes now is taken before Replace selects the object it swaps again.
|
||||
let current = placement.and_then(|_| crate::placing::Insertion::of(app));
|
||||
// A drawing converted off the UI thread replaces the object selected when Place
|
||||
// started, selected again, unless it changed meanwhile.
|
||||
// started, selected again, unless it changed meanwhile. When the drawing is not placed,
|
||||
// the user's selection comes back.
|
||||
let mut user_selection = None;
|
||||
if let Some((old, node)) = placement.and_then(|pl| pl.replaced.as_ref()) {
|
||||
let st = app.session.doc().map_err(|e| e.to_string())?;
|
||||
if st.doc.node(*old) != Some(node) {
|
||||
return Err("replace: the object to replace was changed or deleted".into());
|
||||
}
|
||||
if st.selection.objects != [*old] || st.selection.symbol_part.is_some() {
|
||||
let user = st.selection.clone();
|
||||
app.session.execute("select.set", &json!({ "ids": [old.0] })).map_err(|e| e.to_string())?;
|
||||
let st = app.session.doc().map_err(|e| e.to_string())?;
|
||||
user_selection = Some(crate::placing::Reselect {
|
||||
doc: st.uid,
|
||||
swapped: st.selection.clone(),
|
||||
selections: st.selections,
|
||||
art: st.doc.clone(),
|
||||
isolation: st.isolation,
|
||||
user,
|
||||
});
|
||||
}
|
||||
}
|
||||
// It goes where new art went when Place started, and what the user changed since is
|
||||
@@ -537,12 +549,19 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R
|
||||
if let Some(path) = &source.path {
|
||||
app.placing.bytes_next = Some((path.clone(), source.file.clone()));
|
||||
}
|
||||
app.placing.select_on_failure = user_selection.clone();
|
||||
let r = crate::place::run_for_user(app, &p).map(|_| ());
|
||||
app.placing.keep_next = None;
|
||||
app.placing.bytes_next = None;
|
||||
app.placing.select_on_failure = None;
|
||||
if let (Some(current), Some(insertion)) = (current, restore) {
|
||||
current.restore_changed(&insertion, app);
|
||||
}
|
||||
if r.is_err()
|
||||
&& let Some(back) = &user_selection
|
||||
{
|
||||
crate::placing::reselect(app, back);
|
||||
}
|
||||
r
|
||||
}
|
||||
None => {
|
||||
@@ -1107,6 +1126,60 @@ mod tests {
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap();
|
||||
assert!(app.opening.converting.is_empty());
|
||||
assert!(app.ui.status.contains("select the one object to replace"), "{}", app.ui.status);
|
||||
// A Replace that fails keeps the selection the user made since Place started.
|
||||
let replaced = rect(&mut app, 90.0);
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap();
|
||||
let selected_since = rect(&mut app, 130.0);
|
||||
finish_conversions(&mut app);
|
||||
set(&app, "layout", json!("No such layout"));
|
||||
let undo = undo_steps(&app, first);
|
||||
let _ = host::confirm(&mut app, KIND);
|
||||
placed(&mut app);
|
||||
assert!(app.ui.status.contains("no layout"), "{}", app.ui.status);
|
||||
let st = app.session.doc().unwrap();
|
||||
assert!(st.doc.node(replaced).is_some(), "the object is not replaced");
|
||||
assert_eq!(st.selection.objects, vec![selected_since], "the selection made since Place started is kept");
|
||||
assert_eq!(undo_steps(&app, first), undo);
|
||||
host::cancel(&app, KIND);
|
||||
// A selection made while the drawing is read is kept too.
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap();
|
||||
rect(&mut app, 170.0);
|
||||
finish_conversions(&mut app);
|
||||
set(&app, "layout", json!("No such layout"));
|
||||
let _ = host::confirm(&mut app, KIND);
|
||||
app.run("select.set", json!({ "ids": [selected_since.0] })).unwrap();
|
||||
placed(&mut app);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![selected_since], "the selection made since OK is kept");
|
||||
host::cancel(&app, KIND);
|
||||
// Selecting the replacement target again after OK keeps that selection on failure.
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap();
|
||||
rect(&mut app, 210.0);
|
||||
finish_conversions(&mut app);
|
||||
set(&app, "layout", json!("No such layout"));
|
||||
let _ = host::confirm(&mut app, KIND);
|
||||
app.run("select.set", json!({ "ids": [replaced.0] })).unwrap();
|
||||
placed(&mut app);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![replaced], "the target selected again since OK is kept");
|
||||
host::cancel(&app, KIND);
|
||||
// Cancel restores the source document's selection while another document stays active.
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan, "replace": true })).unwrap();
|
||||
let selected_since = rect(&mut app, 250.0);
|
||||
finish_conversions(&mut app);
|
||||
set(&app, "layout", json!("No such layout"));
|
||||
let _ = host::confirm(&mut app, KIND);
|
||||
let other_index = app.session.documents().iter().position(|st| st.uid == other).unwrap();
|
||||
let undo = undo_steps(&app, first);
|
||||
app.session.set_active(other_index);
|
||||
let other_selection = app.session.doc().unwrap().selection.clone();
|
||||
assert_eq!(crate::placing::cancel_all(&mut app)["cancelled"], 1);
|
||||
assert_eq!(app.session.doc().unwrap().uid, other);
|
||||
assert_eq!(app.session.doc().unwrap().selection, other_selection);
|
||||
let st = app.session.documents().iter().find(|st| st.uid == first).unwrap();
|
||||
assert_eq!(st.selection.objects, vec![selected_since], "Cancel restores the background document's selection");
|
||||
assert_eq!(st.history.undo.len(), undo);
|
||||
host::cancel(&app, KIND);
|
||||
let first_index = app.session.documents().iter().position(|st| st.uid == first).unwrap();
|
||||
app.session.set_active(first_index);
|
||||
// Closed meanwhile.
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap();
|
||||
app.session.execute("file.close", &json!({})).unwrap();
|
||||
|
||||
@@ -510,11 +510,12 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi
|
||||
Entry::new(Tab::Swatches, tl!("Swatches").to_owned()).icon(IconId::new("swatch-book")),
|
||||
];
|
||||
Segmented::new("View", Bind::bound(&mut *tab), &tabs).show(ui);
|
||||
// A stop's colour can come from the art, as from the Gradient panel's eyedropper.
|
||||
if !feed.point {
|
||||
let tip = tl!("Eyedropper: click the art to sample the stop's colour").to_owned();
|
||||
filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true);
|
||||
}
|
||||
let tip = if feed.point {
|
||||
tl!("Eyedropper: click the art to sample the point's colour")
|
||||
} else {
|
||||
tl!("Eyedropper: click the art to sample the stop's colour")
|
||||
};
|
||||
filed.eyedropper |= DropperButton::new(tip.to_owned(), Bind::given(false)).show(ui).edit.value() == Some(&true);
|
||||
if *tab == Tab::Color {
|
||||
let (closed, picked) = mode_menu(ui, &feed.shown, panel.mode);
|
||||
outside |= closed;
|
||||
@@ -834,7 +835,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
if filed.eyedropper {
|
||||
dialogs.with(|host| host.cancel_by_id(ctx, id));
|
||||
crate::panels::gradient::stop_eyedropper(app);
|
||||
match target {
|
||||
Target::Stop(..) => crate::panels::gradient::stop_eyedropper(app),
|
||||
Target::Point(..) => crate::panels::gradient::point_eyedropper(app),
|
||||
}
|
||||
return;
|
||||
}
|
||||
let updated = selected(app).filter(|target| owner.key.matches(app, target)).zip(app.session.gradient_edit_paints(!owner.key.fill).ok());
|
||||
@@ -1722,6 +1726,91 @@ mod tests {
|
||||
assert!(!is_open(&app));
|
||||
}
|
||||
|
||||
fn point_sampling_panel() -> (crate::tests::panel_harness::Panel, NodeId, NodeId, usize) {
|
||||
let mut app = app();
|
||||
let target = app.session.active().unwrap().selection.objects[0];
|
||||
app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap();
|
||||
app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap();
|
||||
app.run("paint.freeform.addPoint", json!({"at": [150, 150], "color": "#0000ff"})).unwrap();
|
||||
let index = app.session.selected_freeform_point().unwrap();
|
||||
let source = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 60, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#00aa5a", "keepModel": true})).unwrap();
|
||||
app.run("select.set", json!({"ids": [target.0]})).unwrap();
|
||||
app.run("paint.freeform.selectPoint", json!({"index": index})).unwrap();
|
||||
let panel = crate::tests::panel_harness::Panel::new(app, |app, ui| {
|
||||
app.dialogs().unwrap().with(|host| host.run(ui));
|
||||
host::pump(app, ui.ctx());
|
||||
});
|
||||
(panel, target, NodeId(source), index)
|
||||
}
|
||||
|
||||
fn arm_point_sample(panel: &mut crate::tests::panel_harness::Panel, index: usize) {
|
||||
open_at(&mut panel.app(), index, Anchor::Screen(egui::pos2(200.0, 200.0)));
|
||||
panel.frame();
|
||||
panel.click("Eyedropper: click the art to sample the point's colour");
|
||||
assert!(!is_open(&panel.app()));
|
||||
assert_eq!(panel.app().session.tool_id(), "eyedropper");
|
||||
}
|
||||
|
||||
fn click_sample_source(app: &mut VectorcraftApp) {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let view = app.view_info();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
let requests = app.session.pointer(&PointerEvent::new(kind, 250.0, 115.0), view).unwrap();
|
||||
crate::canvas::apply_requests(app, Ok(requests));
|
||||
}
|
||||
}
|
||||
|
||||
fn node_fill(app: &VectorcraftApp, id: NodeId) -> Paint {
|
||||
app.session.active().unwrap().doc.node(id).unwrap().appearance.fill_paint()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeform_point_eyedropper_preserves_the_sample_model_and_undoes_once() {
|
||||
let (mut panel, target, source, index) = point_sampling_panel();
|
||||
let initial = node_fill(&panel.app(), target);
|
||||
let source_fill = node_fill(&panel.app(), source);
|
||||
let color = source_fill.color().unwrap();
|
||||
assert!(matches!(color, Color::Rgb { .. }), "the source stores RGB in a CMYK document");
|
||||
let points = |app: &VectorcraftApp| app.session.proxy_freeform(false).unwrap().0.points;
|
||||
let mut expected = points(&panel.app());
|
||||
assert_ne!(expected[index].color, color);
|
||||
|
||||
arm_point_sample(&mut panel, index);
|
||||
click_sample_source(&mut panel.app());
|
||||
assert_eq!(panel.app().session.tool_id(), "gradient");
|
||||
expected[index].color = color;
|
||||
assert_eq!(points(&panel.app()), expected, "only the point's color changes");
|
||||
assert_eq!(node_fill(&panel.app(), source), source_fill);
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(node_fill(&panel.app(), target), initial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeform_point_eyedropper_cancels_and_skips_a_replaced_point() {
|
||||
let (mut panel, target, source, index) = point_sampling_panel();
|
||||
let initial = node_fill(&panel.app(), target);
|
||||
let source_fill = node_fill(&panel.app(), source);
|
||||
|
||||
arm_point_sample(&mut panel, index);
|
||||
let escape = egui::Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
|
||||
let ctx = ctx(&panel.app());
|
||||
crate::tests::synthetic::key_frame(&mut panel.app(), &ctx, vec![escape]);
|
||||
assert_eq!(panel.app().session.tool_id(), "gradient");
|
||||
assert_eq!(node_fill(&panel.app(), target), initial);
|
||||
|
||||
arm_point_sample(&mut panel, index);
|
||||
panel.app().run("paint.freeform.deletePoint", json!({"index": index})).unwrap();
|
||||
let replacement = panel.app().run("paint.freeform.addPoint", json!({"at": [155, 150], "color": "#ffa000"})).unwrap();
|
||||
assert_eq!(replacement["index"].as_u64(), Some(index as u64), "the replacement uses the old index");
|
||||
let before_pick = node_fill(&panel.app(), target);
|
||||
assert_eq!(panel.app().session.tool_id(), "eyedropper");
|
||||
click_sample_source(&mut panel.app());
|
||||
assert_eq!(panel.app().session.tool_id(), "gradient");
|
||||
assert_eq!(node_fill(&panel.app(), target), before_pick);
|
||||
assert_eq!(node_fill(&panel.app(), source), source_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_popover_closes_when_its_stop_goes_away() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -21,7 +21,6 @@ use std::sync::Arc;
|
||||
use craft::behavior::{Axis, DockSide, IconId};
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits, Tracked};
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::docking::{
|
||||
ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels,
|
||||
PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions,
|
||||
@@ -74,9 +73,6 @@ pub(crate) struct Runtime {
|
||||
/// A panel just floated out of a tool rail, whose window takes over the held press on the next
|
||||
/// pass, with the pointer at this point inside it ([`continue_move`]).
|
||||
hand_over: Option<(String, egui::Vec2)>,
|
||||
/// The dialogs a panel in the open flyout opened, by id and opening serial: while one is open, Auto-Collapse Iconic
|
||||
/// Panels leaves the flyout open ([`show`]).
|
||||
flyout_dialogs: Vec<(DialogId, u64)>,
|
||||
}
|
||||
|
||||
/// `ui.docking`: the layout in use, the hidden panels, the open flyout, the focused panel, the
|
||||
@@ -1350,16 +1346,6 @@ fn raise(app: &VectorcraftApp, ctx: &egui::Context, panel: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The open dialogs of the main window, by id and opening serial: a dialog closed and opened again has a new serial.
|
||||
fn open_dialogs(app: &VectorcraftApp) -> Vec<(DialogId, u64)> {
|
||||
app.dialogs().map_or_else(Vec::new, |dialogs| {
|
||||
dialogs.with(|host| {
|
||||
let host = &*host;
|
||||
host.stack().ids().filter_map(|id| Some((id, host.open_serial(id)?))).collect()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The floating window holding `panel` takes over the held primary press on the next pass, with the
|
||||
/// pointer at `grab` inside it: a panel floated out of a tool rail mid-drag follows the pointer and
|
||||
/// docks where the release lands.
|
||||
@@ -1385,15 +1371,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo
|
||||
let presenting = app.ui.screen_mode >= 3;
|
||||
// Shift+Tab, from its key, a menu or automation, closes a panel popped out of the icon column.
|
||||
let mut flyout = flyout_before.clone().filter(|_| !keeps_tools);
|
||||
let dialogs_before = open_dialogs(app);
|
||||
if flyout_before.is_some() {
|
||||
app.dock_rt.flyout_dialogs.retain(|dialog| dialogs_before.contains(dialog));
|
||||
} else {
|
||||
app.dock_rt.flyout_dialogs.clear();
|
||||
}
|
||||
// A dialog a panel of the flyout opened (the Gradient panel's stop popover) is a layer of the window's dialog host,
|
||||
// outside the flyout's: while one is open, a press in it or the focus moving into it leaves the flyout open.
|
||||
let auto_collapse = app.session.prefs.auto_collapse_icon_panels && app.dock_rt.flyout_dialogs.is_empty();
|
||||
let auto_collapse = app.session.prefs.auto_collapse_icon_panels;
|
||||
// The specs and rails leave the app for the pass, which lends the app to the panel bodies.
|
||||
let specs = std::mem::take(&mut app.dock_rt.specs);
|
||||
let rails = std::mem::take(&mut app.dock_rt.rails);
|
||||
@@ -1439,12 +1417,6 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo
|
||||
if app.ui.open_panel == flyout_before {
|
||||
app.ui.open_panel = flyout;
|
||||
}
|
||||
if app.ui.open_panel.is_some() {
|
||||
let opened: Vec<_> = open_dialogs(app).into_iter().filter(|dialog| !dialogs_before.contains(dialog)).collect();
|
||||
app.dock_rt.flyout_dialogs.extend(opened);
|
||||
} else {
|
||||
app.dock_rt.flyout_dialogs.clear();
|
||||
}
|
||||
if output.error.is_some() {
|
||||
Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[]));
|
||||
app.status(tl!("Invalid panel layout; restored the default dock").to_string());
|
||||
|
||||
@@ -1351,7 +1351,8 @@ fn a_tab_menus_stock_items_start_at_the_panel_items_check_column() {
|
||||
}
|
||||
|
||||
/// With Auto-Collapse Iconic Panels on, the popover the Gradient panel's stop chip opens from the panel's flyout leaves
|
||||
/// the flyout open while it shows; once it closes, a click away from the flyout still closes it.
|
||||
/// the flyout open while it shows; once it closes, a click away from the flyout still closes it, and a press away from
|
||||
/// both closes the popover and the flyout together.
|
||||
#[test]
|
||||
fn a_popover_opened_from_an_auto_collapsing_flyout_leaves_the_flyout_open() {
|
||||
let mut h = Harness::new();
|
||||
@@ -1385,4 +1386,17 @@ fn a_popover_opened_from_an_auto_collapsing_flyout_leaves_the_flyout_open() {
|
||||
assert_eq!(h.app.ui.open_panel, flyout, "closing the popover leaves the flyout open");
|
||||
h.click(h.canvas().center());
|
||||
assert_eq!(h.app.ui.open_panel, None, "a click away from the flyout still closes it");
|
||||
|
||||
// With the popover open again, one press away from both closes the popover and the flyout.
|
||||
h.app.run("window.panel", json!({"panel": "gradient"})).unwrap();
|
||||
h.frames(3);
|
||||
assert_eq!(h.app.ui.open_panel, flyout, "the flyout opens again");
|
||||
h.click(chip.center());
|
||||
h.frames(3);
|
||||
assert!(popover_open(&h), "the chip opens the stop popover again");
|
||||
assert_eq!(h.app.ui.open_panel, flyout, "the flyout stays open while the popover shows");
|
||||
h.click(h.canvas().center());
|
||||
h.frames(2);
|
||||
assert!(!popover_open(&h), "a press away closes the popover");
|
||||
assert_eq!(h.app.ui.open_panel, None, "and the flyout with it");
|
||||
}
|
||||
@@ -895,10 +895,18 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra
|
||||
/// selected stop, then hands back to the current tool (or, while a pick is already armed, to the
|
||||
/// tool that armed it).
|
||||
pub(crate) fn stop_eyedropper(app: &mut VectorcraftApp) {
|
||||
gradient_eyedropper(app, "stop");
|
||||
}
|
||||
|
||||
pub(crate) fn point_eyedropper(app: &mut VectorcraftApp) {
|
||||
gradient_eyedropper(app, "freeformPoint");
|
||||
}
|
||||
|
||||
fn gradient_eyedropper(app: &mut VectorcraftApp, option: &str) {
|
||||
let tool = app.session.tool_id();
|
||||
let back = (tool == "eyedropper").then(|| app.session.tool_returns_to()).flatten().unwrap_or_else(|| tool.to_string());
|
||||
app.select_tool("eyedropper");
|
||||
app.session.set_tool_option("stop", &json!(back));
|
||||
app.session.set_tool_option(option, &json!(back));
|
||||
}
|
||||
|
||||
/// Open the stop popover for stop `i` at screen position `at`, the stop selected first.
|
||||
|
||||
@@ -139,6 +139,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() {
|
||||
json!("game-trails"),
|
||||
json!("energy-beams"),
|
||||
json!("dry-media"),
|
||||
json!("impact-bursts"),
|
||||
json!("tech-circuit"),
|
||||
json!("engraving"),
|
||||
json!("arrows"),
|
||||
|
||||
@@ -184,6 +184,27 @@ pub struct Pending {
|
||||
pub(crate) started: f64,
|
||||
/// What stays alive until this entry is removed ([`Placing::keep_next`]).
|
||||
_keep: Option<Box<dyn std::any::Any + Send>>,
|
||||
/// The selection its document gets back when the file is not placed ([`Placing::select_on_failure`]).
|
||||
select_on_failure: Option<Reselect>,
|
||||
}
|
||||
|
||||
/// The user's selection, which a Replace swapped for the object it replaces ([`Placing::select_on_failure`]).
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Reselect {
|
||||
/// The document whose selection Replace changed.
|
||||
pub(crate) doc: u64,
|
||||
/// The selection Replace made: the object it swaps.
|
||||
pub(crate) swapped: vectorcraft_doc::Selection,
|
||||
/// The document's selection count ([`vectorcraft_engine::DocState::selections`]) after it.
|
||||
/// The user's selection comes back only while neither changed, whatever else was edited.
|
||||
pub(crate) selections: u64,
|
||||
/// The art then: the user's selection comes back only while each object it holds is as it
|
||||
/// was, so that its selected anchors and segments still name the same points.
|
||||
pub(crate) art: std::sync::Arc<vectorcraft_doc::Document>,
|
||||
/// The group or layer isolated then: the user's selection comes back only in the same isolation.
|
||||
pub(crate) isolation: Option<vectorcraft_doc::NodeId>,
|
||||
/// The user's selection before it.
|
||||
pub(crate) user: vectorcraft_doc::Selection,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -202,6 +223,10 @@ pub struct Placing {
|
||||
/// dropped: the conversion of a DWG drawing placed through its import options, which the read
|
||||
/// then finds without converting the drawing again.
|
||||
pub(crate) keep_next: Option<Box<dyn std::any::Any + Send>>,
|
||||
/// The selection the next read started ([`spawn_labeled`]) gives its document back when its
|
||||
/// file is not placed: the user's selection before a DWG drawing's Replace selected the object
|
||||
/// it swaps again.
|
||||
pub(crate) select_on_failure: Option<Reselect>,
|
||||
/// The path and the bytes of a drawing placed through its import options: the next place of
|
||||
/// that path ([`crate::place::run_for_user`]) places these bytes, the ones the dialog showed,
|
||||
/// instead of reading the file again.
|
||||
@@ -447,6 +472,7 @@ fn spawn_labeled(
|
||||
app.placing.lane.push(&*jobs, "vectorcraft-place", job);
|
||||
let started = crate::export_progress::now(app);
|
||||
let keep = app.placing.keep_next.take();
|
||||
let select_on_failure = app.placing.select_on_failure.take();
|
||||
app.placing.pending.push(Pending {
|
||||
name,
|
||||
label: label.clone(),
|
||||
@@ -461,6 +487,7 @@ fn spawn_labeled(
|
||||
hidden: false,
|
||||
started,
|
||||
_keep: keep,
|
||||
select_on_failure,
|
||||
});
|
||||
let status = format!("{label}…");
|
||||
app.status(status.clone());
|
||||
@@ -574,6 +601,11 @@ fn finish(app: &mut VectorcraftApp, p: &Pending, r: Result<Read, String>) {
|
||||
Ok(Read::Paste(paste)) => return finish_paste(app, *paste),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
if r.is_err()
|
||||
&& let Some(back) = &p.select_on_failure
|
||||
{
|
||||
reselect(app, back);
|
||||
}
|
||||
app.sync_views();
|
||||
let name = &p.name;
|
||||
match r {
|
||||
@@ -583,6 +615,32 @@ fn finish(app: &mut VectorcraftApp, p: &Pending, r: Result<Read, String>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the user's selection while the selection Replace made is unchanged and the user's objects
|
||||
/// are still there as they were. The whole selection, guides, slices and new art included, goes through the selection filters as
|
||||
/// they are now, and the current layer and active document stay current.
|
||||
pub(crate) fn reselect(app: &mut VectorcraftApp, back: &Reselect) {
|
||||
let Some(st) = app.session.documents().iter().find(|st| st.uid == back.doc) else { return };
|
||||
let kept = |id: &vectorcraft_doc::NodeId| st.doc.node(*id).is_some_and(|n| back.art.node(*id) == Some(n));
|
||||
// A symbol part names a child of the symbol's art, which an edit to the symbol can change.
|
||||
let part_kept = back.user.symbol_part.is_none() || std::sync::Arc::ptr_eq(&st.doc, &back.art);
|
||||
if st.selections != back.selections
|
||||
|| st.selection != back.swapped
|
||||
|| st.isolation != back.isolation
|
||||
|| !part_kept
|
||||
|| !back.user.objects.iter().all(kept)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let layer = st.active_layer;
|
||||
if let Err(e) = app.session.restore_selection(back.doc, back.user.clone()) {
|
||||
app.status(e.to_string());
|
||||
return;
|
||||
}
|
||||
if let Some(st) = app.session.document_mut(back.doc) {
|
||||
st.active_layer = layer;
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a paste whose bitmap was decoded off the UI thread, in its document, which is the active one:
|
||||
/// the image replaces the internal clipboard, the objects selected when the paste started are
|
||||
/// selected again, and the paste command runs as it runs at once ([`VectorcraftApp::run`]), into
|
||||
@@ -861,6 +919,11 @@ pub fn cancel_all(app: &mut VectorcraftApp) -> Value {
|
||||
if !app.placing.pending[i].paste {
|
||||
let p = app.placing.pending.remove(i);
|
||||
p.token.cancel();
|
||||
if let Some(back) = &p.select_on_failure
|
||||
&& app.session.documents().iter().any(|st| st.uid == p.doc && st.reverts == p.reverts)
|
||||
{
|
||||
reselect(app, back);
|
||||
}
|
||||
if app.ui.status == format!("{}…", p.label) {
|
||||
app.ui.status.clear();
|
||||
}
|
||||
|
||||
@@ -2060,3 +2060,336 @@ fn cancelling_a_place_places_nothing() {
|
||||
assert_eq!(names(&app), initial_names, "no document nodes mutated or added");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), 0, "no undo step added");
|
||||
}
|
||||
|
||||
/// The selection a failed Replace gives back, after the object it swaps was selected in its place.
|
||||
fn swapped_out(app: &mut VectorcraftApp, other: NodeId) -> Reselect {
|
||||
let user = app.session.doc().unwrap().selection.clone();
|
||||
app.run("select.set", json!({"ids": [other.0]})).unwrap();
|
||||
let st = app.session.doc().unwrap();
|
||||
Reselect { doc: st.uid, swapped: st.selection.clone(), selections: st.selections, art: st.doc.clone(), isolation: st.isolation, user }
|
||||
}
|
||||
|
||||
/// Restore `back`, then check that the journal entries the restore added select the same again
|
||||
/// when they are run after the swapped object is selected.
|
||||
fn reselect_and_replay(app: &mut VectorcraftApp, back: &Reselect, other: NodeId) {
|
||||
let from = app.session.journal.len();
|
||||
reselect(app, back);
|
||||
let restored = app.session.doc().unwrap().selection.clone();
|
||||
let steps: Vec<(String, serde_json::Value)> = app.session.journal.since(from).to_vec();
|
||||
assert!(!steps.is_empty(), "the journal records the restored selection");
|
||||
app.run("select.set", json!({"ids": [other.0]})).unwrap();
|
||||
for (id, p) in steps {
|
||||
app.run(&id, p).unwrap();
|
||||
}
|
||||
assert_eq!(app.session.doc().unwrap().selection, restored, "the journal replays the restored selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_segment_selection_replays_as_segments() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
app.run("select.segments", json!({"id": mine.0, "segments": [[0, 1]]})).unwrap();
|
||||
assert!(!app.session.doc().unwrap().selection.segments.is_empty());
|
||||
let back = swapped_out(&mut app, other);
|
||||
reselect_and_replay(&mut app, &back, other);
|
||||
assert!(app.session.doc().unwrap().selection.segments.contains_key(&mine), "the segment is selected again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restore_inside_a_canceled_undo_group_leaves_the_journal() {
|
||||
let mut app = app(false);
|
||||
let (_, other) = two_rectangles(&mut app);
|
||||
let before = app.session.journal.len();
|
||||
app.run("edit.undoGroup.begin", json!({})).unwrap();
|
||||
let made = NodeId(app.run("shape.rectangle", json!({"x": 120, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("select.set", json!({"ids": [made.0]})).unwrap();
|
||||
let back = swapped_out(&mut app, other);
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![made]);
|
||||
let last = app.session.journal.last().cloned().unwrap();
|
||||
assert_eq!(last, ("select.set".to_string(), json!({"ids": [made.0]})), "the restore is journaled");
|
||||
app.run("edit.undoGroup.end", json!({"cancel": true})).unwrap();
|
||||
let left: Vec<&str> = app.session.journal.since(before).iter().map(|(id, _)| id.as_str()).collect();
|
||||
assert!(!left.iter().any(|id| *id == "select.set" || *id == "shape.rectangle"), "{left:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_selection_is_journaled_and_brings_its_paints_back() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
app.run("paint.setFill", json!({"ids": [mine.0], "color": "#ff0000"})).unwrap();
|
||||
app.run("paint.setFill", json!({"ids": [other.0], "color": "#0000ff"})).unwrap();
|
||||
// Selecting the red rectangle loads its paints for new art.
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.run("select.set", json!({"ids": [mine.0]})).unwrap();
|
||||
let red = app.session.paint.clone();
|
||||
let back = swapped_out(&mut app, other);
|
||||
assert_ne!(app.session.paint, red, "selecting the swapped object loads its paints");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![mine]);
|
||||
assert_eq!(app.session.paint, red, "the restored selection's paints are the paints for new art");
|
||||
let last = app.session.journal.last().cloned().unwrap();
|
||||
assert_eq!(last, ("select.set".to_string(), json!({"ids": [mine.0]})), "the journal records the restored selection");
|
||||
// Replayed, the journal leaves the same paints for new art.
|
||||
app.run("select.set", json!({"ids": [other.0]})).unwrap();
|
||||
app.run(&last.0, last.1).unwrap();
|
||||
assert_eq!(app.session.paint, red, "the replay loads the same paints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_selection_gives_new_art_its_appearance_with_basic_appearance_off() {
|
||||
let mut app = app(false);
|
||||
app.session.prefs.new_art_basic = false;
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
app.run("paint.setFill", json!({"ids": [mine.0], "color": "#ff0000"})).unwrap();
|
||||
app.run("paint.setFill", json!({"ids": [other.0], "color": "#0000ff"})).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.run("select.set", json!({"ids": [mine.0]})).unwrap();
|
||||
let red = app.session.paint.clone();
|
||||
let back = swapped_out(&mut app, other);
|
||||
assert_ne!(app.session.paint, red, "new art takes the swapped object's appearance");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.paint, red, "new art takes the restored object's appearance again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restore_after_a_defaults_only_paint_gives_new_art_the_restored_appearance() {
|
||||
let mut app = app(false);
|
||||
app.session.prefs.new_art_basic = false;
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
app.run("paint.setFill", json!({"ids": [mine.0], "color": "#ff0000"})).unwrap();
|
||||
app.run("paint.setFill", json!({"ids": [other.0], "color": "#0000ff"})).unwrap();
|
||||
app.run("select.set", json!({"ids": [mine.0, other.0]})).unwrap();
|
||||
let back = swapped_out(&mut app, mine);
|
||||
let red = app.session.paint.clone();
|
||||
app.run("paint.setFill", json!({"color": "#00ff00", "defaultsOnly": true})).unwrap();
|
||||
assert_ne!(app.session.paint, red, "the defaults-only paint changes the defaults");
|
||||
let from = app.session.journal.len();
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.paint, red, "new art takes the restored selection's appearance");
|
||||
// Replayed after the same defaults-only paint, the journal leaves the same defaults.
|
||||
let steps: Vec<(String, serde_json::Value)> = app.session.journal.since(from).to_vec();
|
||||
app.run("select.set", json!({"ids": [mine.0]})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#00ff00", "defaultsOnly": true})).unwrap();
|
||||
for (id, p) in steps {
|
||||
app.run(&id, p).unwrap();
|
||||
}
|
||||
assert_eq!(app.session.paint, red, "the replay gives new art the same appearance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_symbol_part_leaves_the_paints_as_its_replay_does() {
|
||||
let mut app = app(false);
|
||||
let rect = |app: &mut VectorcraftApp, x: i32, color: &str| {
|
||||
let id = app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap();
|
||||
id
|
||||
};
|
||||
let (left, right) = (rect(&mut app, 10, "#ff0000"), rect(&mut app, 40, "#00ff00"));
|
||||
let other = NodeId(rect(&mut app, 120, "#0000ff"));
|
||||
let instance = app.run("symbol.new", json!({"type": "dynamic", "ids": [left, right]})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("symbol.instance.selectPart", json!({"id": instance, "path": [0]})).unwrap();
|
||||
let back = swapped_out(&mut app, other);
|
||||
let blue = app.session.paint.clone();
|
||||
let from = app.session.journal.len();
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.symbol_part.as_ref().map(|p| p.path.clone()), Some(vec![0]));
|
||||
// `symbol.instance.selectPart` keeps the paints for new art, and so does the restore.
|
||||
assert_eq!(app.session.paint, blue, "the restored part keeps the paints for new art");
|
||||
let steps: Vec<(String, serde_json::Value)> = app.session.journal.since(from).to_vec();
|
||||
assert!(steps.iter().any(|(id, _)| id == "symbol.instance.selectPart"), "{steps:?}");
|
||||
app.run("select.set", json!({"ids": [other.0]})).unwrap();
|
||||
for (id, p) in steps {
|
||||
app.run(&id, p).unwrap();
|
||||
}
|
||||
assert_eq!(app.session.paint, blue, "the replay leaves the same paints");
|
||||
}
|
||||
|
||||
/// The objects selected before the swap, with two rectangles drawn: the user's and the swapped one.
|
||||
fn two_rectangles(app: &mut VectorcraftApp) -> (NodeId, NodeId) {
|
||||
let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let (mine, other) = (rect(10.0), rect(60.0));
|
||||
app.run("select.set", json!({"ids": [mine.0]})).unwrap();
|
||||
(mine, other)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_raised_revision_alone_does_not_block_the_restore() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
let back = swapped_out(&mut app, other);
|
||||
// The rollback of a failed Replace puts the document back as it was and raises its revision
|
||||
// (`Session::place_read`), which this does alone.
|
||||
let uid = app.session.doc().unwrap().uid;
|
||||
app.session.document_mut(uid).unwrap().revision += 1;
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![mine], "the user's selection comes back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_undo_and_redo_gave_back_is_kept() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
app.run("select.set", json!({"ids": [other.0]})).unwrap();
|
||||
app.run("artboard.setProps", json!({"index": 0, "name": "Front"})).unwrap();
|
||||
app.run("select.set", json!({"ids": [mine.0]})).unwrap();
|
||||
let back = swapped_out(&mut app, other);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
app.run("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "Redo selects the object again");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the selection Redo gave back is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_isolation_gave_back_is_kept() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
let group = NodeId(app.run("object.group", json!({ "ids": [other.0] })).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("select.set", json!({"ids": [mine.0]})).unwrap();
|
||||
let back = swapped_out(&mut app, group);
|
||||
app.run("object.isolate", json!({"id": group.0})).unwrap();
|
||||
app.run("object.exitIsolation", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "leaving isolation selects the group again");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "the selection leaving isolation made is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_a_batch_step_gave_back_is_kept() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
let group = NodeId(app.run("object.group", json!({ "ids": [other.0] })).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("select.set", json!({"ids": [mine.0]})).unwrap();
|
||||
let back = swapped_out(&mut app, group);
|
||||
let steps = json!([{"command": "object.isolate", "params": {"id": group.0}}, {"command": "object.exitIsolation"}]);
|
||||
app.run("command.batch", json!({"commands": steps})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "leaving isolation selects the group again");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "the selection the batch made is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_isolation_onto_the_swapped_group_keeps_it_selected() {
|
||||
let mut app = app(false);
|
||||
let (_, other) = two_rectangles(&mut app);
|
||||
let group = NodeId(app.run("object.group", json!({ "ids": [other.0] })).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("object.isolate", json!({"id": group.0})).unwrap();
|
||||
app.run("select.set", json!({"ids": [other.0]})).unwrap();
|
||||
let back = swapped_out(&mut app, group);
|
||||
app.run("object.exitIsolation", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "leaving isolation selects the group");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![group], "the selection leaving isolation made is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_a_lock_and_unlock_batch_gave_back_is_kept() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
app.run("select.set", json!({"ids": [mine.0]})).unwrap();
|
||||
let back = swapped_out(&mut app, other);
|
||||
let steps = json!([{"command": "object.lock"}, {"command": "object.unlockAll"}]);
|
||||
app.run("command.batch", json!({"commands": steps})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "Unlock All selects what it unlocks");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the selection the batch made is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_is_not_restored_into_another_isolation() {
|
||||
let mut app = app(false);
|
||||
let (_, other) = two_rectangles(&mut app);
|
||||
let group = NodeId(app.run("object.group", json!({ "ids": [other.0] })).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
let mut back = swapped_out(&mut app, group);
|
||||
app.run("object.isolate", json!({"id": group.0})).unwrap();
|
||||
app.run("select.set", json!({"ids": [group.0]})).unwrap();
|
||||
let st = app.session.doc().unwrap();
|
||||
(back.swapped, back.selections) = (st.selection.clone(), st.selections);
|
||||
let selected = st.selection.objects.clone();
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, selected, "the selection made in isolation is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_that_fails_and_puts_the_selection_back_does_not_block_the_restore() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
let back = swapped_out(&mut app, other);
|
||||
let far = NodeId(app.run("shape.rectangle", json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("select.set", json!({"ids": [other.0]})).unwrap();
|
||||
let mut back = back;
|
||||
let st = app.session.doc().unwrap();
|
||||
(back.swapped, back.selections, back.art) = (st.selection.clone(), st.selections, st.doc.clone());
|
||||
assert!(app.run("object.pathfinder.intersect", json!({"ids": [other.0, far.0]})).is_err(), "disjoint shapes have no intersection");
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the failed command puts the selection back");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![mine], "the user's selection comes back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_part_is_not_restored_after_an_edit() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
let mut back = swapped_out(&mut app, other);
|
||||
back.user.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: mine, path: vec![0] });
|
||||
app.run("artboard.setProps", json!({"index": 0, "name": "Front"})).unwrap();
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "a part of art that may have changed is not restored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_anchors_of_a_reversed_path_are_not_restored() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
app.run("select.anchors", json!({"id": mine.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let back = swapped_out(&mut app, other);
|
||||
app.run("path.reverse", json!({"ids": [mine.0], "reversed": true})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the edit keeps the selection");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "anchor numbers of the edited path are not restored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_keeps_the_selection_still_restores_it() {
|
||||
let mut app = app(false);
|
||||
let (mine, other) = two_rectangles(&mut app);
|
||||
let back = swapped_out(&mut app, other);
|
||||
let revision = app.session.doc().unwrap().revision;
|
||||
app.run("artboard.setProps", json!({"index": 0, "name": "Front"})).unwrap();
|
||||
assert_ne!(app.session.doc().unwrap().revision, revision, "the edit changes the document");
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![other], "the edit keeps the selection");
|
||||
reselect(&mut app, &back);
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![mine], "the user's selection comes back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_selection_leaves_out_guides_locked_since() {
|
||||
let mut app = app(false);
|
||||
let other = NodeId(app.run("shape.rectangle", json!({"x": 60, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("guide.add", json!({"vertical": true, "pos": 40})).unwrap();
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
app.run("guide.select", json!({"indexes": [0]})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().selection.guides.len(), 1, "the ruler guide is selected");
|
||||
let mut back = swapped_out(&mut app, other);
|
||||
app.run("view.guides.lock", json!({"locked": true})).unwrap();
|
||||
let st = app.session.doc().unwrap();
|
||||
(back.swapped, back.selections) = (st.selection.clone(), st.selections);
|
||||
reselect(&mut app, &back);
|
||||
assert!(app.session.doc().unwrap().selection.guides.is_empty(), "the locked guide is not selected again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restored_selection_keeps_new_art_on_a_locked_artboard() {
|
||||
let mut app = app(false);
|
||||
app.run("artboard.setProps", json!({"index": 0, "locked": true})).unwrap();
|
||||
let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
|
||||
let (other, drawn) = (rect(60.0), rect(10.0));
|
||||
assert_eq!(app.session.doc().unwrap().selection.objects, vec![drawn], "new art is selected");
|
||||
let back = swapped_out(&mut app, other);
|
||||
reselect(&mut app, &back);
|
||||
let st = app.session.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, vec![drawn], "the new art is selected again");
|
||||
assert!(st.selection.new_art.contains(&drawn), "it is still new art");
|
||||
}
|
||||
@@ -199,7 +199,9 @@ or point selected, it paints the inactive Fill or Stroke.
|
||||
|
||||
Freeform gradients: double-clicking a point with the Gradient tool opens the same `gradientStop` popover on the selected
|
||||
point (`paint.freeform.selectPoint`); its fields are `color` (hex), `opacity` and `spread` (percentages), applied by
|
||||
`ui.dialog.confirm` through `paint.freeform.setPoint`. `ui.key` Escape ends the line Lines mode is drawing.
|
||||
`ui.dialog.confirm` through `paint.freeform.setPoint`. Its eyedropper chooses the Eyedropper tool and sets the
|
||||
`freeformPoint` option to the tool to return to. The next click on art samples its color into the same point if it
|
||||
is still current. Escape cancels a pick and switches back. When drawing a line, `ui.key` Escape ends that line.
|
||||
|
||||
Tool options: double-clicking a tool button runs `tool.options {tool}`. For `gradient` it opens the Gradient panel;
|
||||
for `eyedropper` it opens Eyedropper Options, an `eyedropperOptions` dialog (fields `sampleSize` 1/3/5, `pickUp` and
|
||||
@@ -991,9 +993,10 @@ artboard. OK is disabled with none checked. Save As to an EPS file opens the sam
|
||||
a pick writes the option's value (`"tiffColor"`, `"preserve"`, a built-in preset's id such as `"medium"` or a saved
|
||||
preset's name, the level as a number), and a value none of them names shows as it is.
|
||||
|
||||
EMF and WMF: Export As… lists both formats (`file.exportAs {format: "emf"}` or `"wmf"`); they have no options
|
||||
dialog, so `ui.dialog.confirm` asks for the path and writes the file (one per artboard with Use Artboards). Open and
|
||||
Place read `.emf` and `.wmf`; a paste of `image/emf` from a system clipboard service runs `clipboard.importEmf`.
|
||||
EMF, WMF and PICT: Export As… lists the three formats (`file.exportAs {format: "emf"}`, `"wmf"` or `"pict"`); they
|
||||
have no options dialog, so `ui.dialog.confirm` asks for the path and writes the file (one per artboard with Use
|
||||
Artboards). Open and Place read `.emf`, `.wmf`, `.pct`, `.pic` and `.pict`; a paste of `image/emf` from a system clipboard service runs
|
||||
`clipboard.importEmf`.
|
||||
|
||||
HP-GL Options: Export As… with the HP-GL format (`file.exportAs {format: "hpgl"}`, then the save dialog), or
|
||||
`ui.hpglOptionsDialog {path?, …HP-GL options}` for agents, opens the `hpglOptions` dialog. Its fields are
|
||||
|
||||
@@ -141,8 +141,12 @@ private editing data. VectorCraft:
|
||||
shape of their own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a clipping object,
|
||||
instances scaled almost flat, instances that turn, mirror or scale symbols holding type, live objects,
|
||||
instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art,
|
||||
instances that scale their symbol more than 100 times and instances on the layers of a large canvas are written as their art, pattern fills in a
|
||||
symbol's art are written as their tiles cut to the shape, symbols past 4,096 are written only as their
|
||||
instances that scale their symbol more than 100 times and instances on the layers of a large canvas are written as their art. Pattern fills in
|
||||
large-canvas symbol art are written as their tiles cut to the shape. On normal canvases, supported pattern
|
||||
fills in symbol definitions retain the shared pattern resource and their affine; VectorCraft declares that
|
||||
coordinate convention in its own dictionary entry, while unmarked foreign symbol patterns keep the reader's
|
||||
conservative fallback. Tile fallback transforms stroke outlines with the full pattern affine, including
|
||||
strokes in opacity masks. Symbols past 4,096 are written only as their
|
||||
instances' art, and symbols' 9-slice guides and export types are left out, each with a
|
||||
warning. A dynamic symbol instance whose only changes of its own are its parts' changes is not written as its
|
||||
art when it otherwise qualifies: it stays a live instance. The symbol's dynamic type and the instance's changes
|
||||
@@ -384,7 +388,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's
|
||||
| Layered raster `.pcraft` | open, place | yes (as one image: the full-size composite when the file has one; else the layers combined at the canvas size when the document is RGB at 8 or 16 bits and every visible layer is a Normal raster layer without clipping, layer effects, a vector mask, a frame, advanced blending or a feathered layer mask; else the composite preview, with a warning when it is smaller than the canvas) | no | read with craft-doc; sized by the document's resolution, the preview at the canvas's size (at least 1 ppi); a linked file is read the same way again when it is updated; a missing or damaged full-size composite or preview is an error; `tests_pcraftread.rs` |
|
||||
| PCX | open, place | yes (1 bit in the header palette's first two colors, black and white without them; 1 bit in two to four planes and 4 bits with up to 16 colors; 2 bits in the CGA colors the header's CGA palette settings pick; 8 bits with the 256-color palette, gray without one; 24-bit color in three planes) | no | the header's HDpi and VDpi size the image; a file of another depth or plane count, cut short or past the pixel allowance is refused with a message; tests in `crates/engine/src/cmd/fileio/tests_pcxread.rs` and `crates/engine/tests/import_fuzz.rs` |
|
||||
| JPEG 2000 | open, place | yes (JP2 and raw codestream images; multiple codestreams and JPX composition or layers are refused) | no | `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c`, `.jpc`; resolution uses the valid `resd` (display) value on each axis, or else the valid `resc` (capture) value, or 72 ppi; bounded decoding; `tests_jp2read.rs` |
|
||||
| PICT | open, place (legacy) | yes (versions 1 and 2: shapes, lines, regions, text, bitmaps, pixel maps and QuickTime JPEG images; placed as one group clipped to the picture's frame) | no | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; a two-color pattern fills with its average color; inverted shapes, transfer modes other than a copy and QuickTime images in other formats come back as warnings; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs` and `crates/engine/tests/import_fuzz.rs` |
|
||||
| PICT | open, place (legacy) | yes (versions 1 and 2: shapes, lines, regions, text, bitmaps, pixel maps and QuickTime JPEG images; placed as one group clipped to the picture's frame) | yes (a version 2 `.pct` of an artboard, or one per artboard: fills as polygons cut to the frame, strokes as their outlines, images as 24-bit pixel maps over white, at up to 16 device units a point) | `.pct`, `.pic` and `.pict`; a version 2 picture also opens by its content; export writes clipping masks, gradients, patterns and transparency as WMF does and reports each loss, and `crates/metafile/src/tests/pict_export.rs` reads its pictures back through the reader; a two-color pattern fills with its average color; inverted shapes, transfer modes other than a copy and QuickTime images in other formats come back as warnings; a picture cut short keeps what came before it; tests in `crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs` and `crates/engine/tests/import_fuzz.rs` |
|
||||
| Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` |
|
||||
| FreeHand `.fh*` | open (legacy) | no | no | |
|
||||
| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; after an open with a warning, an export or Save As to the drawing's own path needs `acknowledgeLoss: true`; record layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Localization parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** patch (Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; UI not exposed pending upstream `storytold/craft-i18n` catalog; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-05 · **Change:** minor (number fields and command parameters read Devanagari, Gujarati and other Unicode digits, one digit set per number; previously patch: Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; UI not exposed pending upstream `storytold/craft-i18n` catalog; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Brazilian Portuguese: 154 rows for the strings the sibling catalogs translate — smart-filter and print presets, dimension lines, swatches, canvas messages; previously minor: Bosnian (`bs`): complete catalog; previously minor: Vietnamese text: stacked diacritics tested and attach in every form, #4491; previously: Catalan (`ca`) catalog added, complete under the tests)
|
||||
|
||||
Per-language status of VectorCraft's interface. How the catalogs work and how to add a language:
|
||||
[`development.md` › Localisation](development.md#localisation). Part of
|
||||
@@ -92,6 +92,15 @@ other mark style; the untranslated report lists a catalog that lacks one of them
|
||||
Native review is still needed, and catalog coverage does not prove that every variable in the UI is
|
||||
translated.
|
||||
|
||||
## Number input
|
||||
|
||||
Number fields and command parameters given as text (MCP, the control channel, `addon.units.convert`) read the
|
||||
decimal digits of Unicode 16 (Devanagari `१२ mm`, Gujarati `૪૫*૨`, Bengali, Arabic-Indic, full-width). Units, arithmetic and the decimal
|
||||
comma work as they do with ASCII digits. One number mixing digit sets (`1२`) is refused. Both readers take their digits
|
||||
from craft-i18n (storytold/craft-libs#198 track 5): the dialog fields and parameters VectorCraft reads itself through
|
||||
`vectorcraft_doc::units` use `craft_i18n::ascii_digits`, and fields on the shared craft number field (the panels, and
|
||||
dialog rows such as Character Style Options › Tsume) use the shared reader (storytold/craft-libs#4872).
|
||||
|
||||
## Not done in any language
|
||||
|
||||
Locale-aware number and date formats, a right-to-left interface, translated help, and a Traditional Chinese UI
|
||||
@@ -101,6 +110,7 @@ font for the web build.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-05 | minor | Number input: number fields and command parameters given as text read Devanagari, Gujarati and other Unicode 16 decimal digits, with units, arithmetic and the decimal comma as for ASCII digits; a number mixing digit sets is refused. `vectorcraft_doc::units` uses `craft_i18n::ascii_digits`, and the shared craft number field reads the same digits after storytold/craft-libs#4872 (storytold/craft-libs#198 track 5); scores and estimates unchanged |
|
||||
| 2026-12-02 | minor | Gujarati: status and error messages translated (4,926 new `@msg`/`@msgplural` rows, machine-assisted draft, native review pending); `gu` joins `COMPLETE_MESSAGES`. Scores and estimates unchanged. |
|
||||
| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. |
|
||||
| 2026-11-25 | patch | Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; kept unavailable to users pending upstream `storytold/craft-i18n` catalog |
|
||||
|
||||
+42
-7
@@ -882,7 +882,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
|
||||
| `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. |
|
||||
| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG (`.jpg`/`.jpeg`/`.jpe`), GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read), DWG drawings (`.dwg`, `.dws`, `.dwt`). Templates (`.vctemplate`, `.ait`, `.cdt`, `.dwt`) open as a new untitled document. A text, RTF or Word file (`.txt`, `.rtf`, `.docx`, `.doc`) opens as a new letter-size document named after the file, its text area type 36 pt inside the artboard as `file.place` sets it; `run_command document.open` with `text` gives a `.txt` file's Text Import Options, and Save asks for a name. A `.txt` file without text, and an RTF file that ends inside a group, are refused and open nothing. A file with one of those extensions that starts with a PDF header or an Affinity signature opens as that format instead. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. |
|
||||
| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: <reason>` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. |
|
||||
| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. |
|
||||
| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `pict` (a QuickDraw `.pct` picture), `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF, PICT and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. |
|
||||
| `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. |
|
||||
| `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. |
|
||||
| `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". |
|
||||
@@ -8461,9 +8461,9 @@ error.
|
||||
|
||||
## Brush libraries
|
||||
|
||||
Brush libraries are read-only sets of brushes: fifteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle
|
||||
Brushes with one bristle brush for each tip shape, Pattern Borders, Decorative with Leaf Vine, Blossom Chain, Pennant Garland and Lantern String, Scatter Shapes, Stipple with Fine, Dense, Soft and Bold dot textures, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and
|
||||
Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, Engraving with Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching art brushes, id `engraving`, and Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`), the `.vectorcraft` files in the user library folder of the desktop app (User
|
||||
Brush libraries are read-only sets of brushes: twenty-one generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle
|
||||
Brushes with one bristle brush for each tip shape, Paint, Pattern Borders, Decorative with Leaf Vine, Blossom Chain, Pennant Garland and Lantern String, Ornamental, Scatter Shapes, Stipple with Fine, Dense, Soft and Bold dot textures, Game Trails, Energy Beams, Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and
|
||||
Charcoal Dust art brushes, id `dry-media`, Impact Bursts with Star Burst, Ring Shock, Slash Arc, Spark Fan, Debris Spray and Crack Line art brushes, id `impact-bursts`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, Engraving with Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching art brushes, id `engraving`, Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`, Image Brush, Artistic Brushes and Vector Packs), the `.vectorcraft` files in the user library folder of the desktop app (User
|
||||
Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has
|
||||
the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and
|
||||
`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). A name
|
||||
@@ -13045,7 +13045,7 @@ error that says to save as DXF. `.dws` drawing standards files and `.dwt` templa
|
||||
`dws` or `dwt` answers with a hint to export DWG or DXF. Web builds and FreeBSD on 64-bit ARM have no DWG decoder:
|
||||
there `document.formats` lists `dwg` and `dwt` as not readable, File › Open, File › Place and `openExtensions` list
|
||||
`.dwg`, `.dws` and `.dwt` only for an installed importer plug-in that reads them, and a DWG drawing opens or places only
|
||||
through such a plug-in. PICT files open and place (see PICT import) but can't be written.
|
||||
through such a plug-in. PICT files open and place (see PICT import), and PICT export writes them.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"document.exportDxf","params":{"path":"/tmp/plan.dxf","version":"2013","unit":"mm","scale":10,"preserve":"editability"}}}
|
||||
@@ -13690,13 +13690,47 @@ under any name. Opcodes and their data lengths follow Apple's
|
||||
inverted shapes, transfer modes other than a copy (drawn as a copy), QuickTime images in formats other than JPEG, and
|
||||
regions or images past the reader's limits. A picture cut short keeps what came before it with a warning, and one that
|
||||
draws nothing VectorCraft reads opens empty with a warning. A file that holds no picture is refused with
|
||||
"not a PICT file". PICT can't be written: `document.export` to it is refused with "PICT files can be opened but not
|
||||
written".
|
||||
"not a PICT file".
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/logo.pct","at":[300,200]}}}
|
||||
```
|
||||
|
||||
## PICT export
|
||||
|
||||
`document.export` (and `export`) with format `pict`, or a path ending in `.pct`, `.pic` or `.pict`, writes a QuickDraw
|
||||
version 2 picture of the first artboard (or `artboard`): 512 bytes of application data, then the picture. Export As
|
||||
offers it as PICT with the `.pct` extension. `useArtboards: true` writes one file per chosen artboard. With a `path`, one
|
||||
chosen artboard goes to the path as given, and several go beside it as `{stem}-{artboard}{ext}`, keeping the path's extension
|
||||
(`.pct`, `.pic` or `.pict`). `false` writes the bounds of the visible art. The picture's frame is the artboard, or with
|
||||
`useArtboards: false` the visible art's bounds, in points, at most 32,767 points on a side (a larger frame is
|
||||
refused). The drawing uses the extended version 2 header at up to 16 device units a point (1,152 dpi), as many as keep
|
||||
the frame within 16-bit coordinates. The writer follows the opcodes and data layouts of Apple's
|
||||
[Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html) and
|
||||
[Version and Header Opcodes](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-459.html):
|
||||
|
||||
- Fills are polygons (`PaintPoly`) in their color, with curves flattened. QuickDraw fills a polygon even-odd, so a path of
|
||||
several figures is one polygon that runs back along the line between its figures, and a non-zero fill is first
|
||||
resolved into figures that don't overlap. Art is cut to the frame. A fill too complex to resolve or cut is written
|
||||
as it is, filled even-odd. Oversized fills first have their curves flattened more coarsely, with a warning.
|
||||
Each figure counts two points more than its outline holds. A fill of several figures that still counts more than
|
||||
8,189 points after that is written as several polygons; a figure of more than 8,187 points keeps that many points,
|
||||
evenly spaced, so a fill of one such figure stays one polygon. Each of these adds a warning.
|
||||
- Strokes are their filled outlines, with their caps, joins, miter limit and dashes; a stroke thinner than a device unit
|
||||
is written one unit wide.
|
||||
- Images are `DirectBitsRect` pixel maps of 24-bit color in tiles of at most 1,024 pixels on a side, each row packed
|
||||
with PackBits. Mirrored images and images turned by quarter turns keep their placement; other turns and skews are
|
||||
written upright, filling their bounds, with a warning. PICT has no transparency: images are written over white, with
|
||||
a warning.
|
||||
- Type is written as outlines. Clipping masks, gradients, patterns, transparency and blending are written as WMF writes
|
||||
them (clipped art whole, gradients and patterns as one color), each with its warning.
|
||||
|
||||
`document.open` reads a written picture back with the reader above.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"document.export","params":{"format":"pict","useArtboards":true,"path":"/tmp/icons.pct"}}}
|
||||
```
|
||||
|
||||
## HP-GL import
|
||||
|
||||
`document.open` and `file.place` read HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`) into one layer, with the
|
||||
@@ -19901,6 +19935,7 @@ Converter and in its panel (`window.panel {panel: "unitConverter"}`). Neither co
|
||||
`addon.units.convert {value, unit?}` accepts a number, or text with a unit suffix and
|
||||
`+ - * /` arithmetic, where `x`, `X` and `×` multiply as `*` does (`"10mm"`, `"1in/2"`, `"2p6"`, `"1080/2 px"`,
|
||||
`"3cm*50%"`, `"2x3 mm"`, `"13q"`). The command reads an unambiguous decimal comma as a point (`"0,5 mm"`).
|
||||
Digits may be any Unicode 16 decimal digits, one set per number (`"१२ mm"`, `"૪૫*૨"`); `"1२"` is refused.
|
||||
It refuses numbers that look like grouped integers, whether alone (`"1,000 mm"`) or in arithmetic (`"1,500+2"`).
|
||||
Text may contain at most 1024 bytes and 128 `+ - * /` signs (each multiplication sign counts).
|
||||
A number without a suffix is in `unit` (a unit's name, suffix or key: `points`, `picas`, `inches`, `millimeters`,
|
||||
|
||||
@@ -359,7 +359,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de
|
||||
| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 88% | Shaper construction widget, Pencil/Pen nuances; Touch Type (#2469), the Dimension tool (#1788) and the Blob Brush options (#2367) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/it/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged |
|
||||
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 85% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog; compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) |
|
||||
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) |
|
||||
| Strokes, brushes, width profiles | 5 | 90% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, the stylus wheel on native Wayland (it is read under X11 and XWayland, on macOS, on Windows through Wintab and in the web build), more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) |
|
||||
| Strokes, brushes, width profiles | 5 | 90% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (twenty-one generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams, Dry Media and Impact Bursts, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, the stylus wheel on native Wayland (it is read under X11 and XWayland, on macOS, on Windows through Wintab and in the web build), more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) |
|
||||
| Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` |
|
||||
| Type core | 9 | 83% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Optical Margin Alignment is done for point and area type and type on a path, right-to-left paragraphs included; remaining: Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) |
|
||||
| Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 60% | editable ruby text in standard SVG and PDF artwork (written as outlines; see [type-parity.md](type-parity.md)), custom Mojikumi sets and the Mojikumi Settings dialog, Retype from images, Retype panel matching depth and fused glyphs (see [type-parity.md](type-parity.md)), Touch Type along a line for a character with no immediately preceding logical character on the same line in the same direction (movement along the baseline is disabled; baseline shift still works) | 20–28 | estimated; Retype (`type.retype`, exact and tolerance-based outline matches, #4934); No Break suppresses automatic breaks within the marked run (a forced line break still breaks); upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged |
|
||||
@@ -618,7 +618,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Drawing tools | 7 | 86% | Eraser preserves fill when cutting fill-only open paths with fixed or varied tips or Alt-drag marquees; painted-stroke paths retain main behavior and clipping masks keep their remaining contours or empty geometry, with reproducible evaluated gradient placement preserved on ordinary paths, compounds, groups and layers (#6582); replacement-art effects, plug-ins/Rasterize, along/across strokes and placements that cannot be reproduced retain fitting; rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 |
|
||||
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 |
|
||||
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) |
|
||||
| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (fifteen generated in code including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation on native Wayland and the web | 8–15 |
|
||||
| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (twenty-one generated in code including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams, Dry Media and Impact Bursts are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation on native Wayland and the web | 8–15 |
|
||||
| Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 |
|
||||
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 |
|
||||
| 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 |
|
||||
@@ -1438,6 +1438,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Decorative library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Decorative offers Leaf Vine, Blossom Chain, Pennant Garland and Lantern String. The four original vector pattern brushes repeat plant, flower and hanging ornament tiles along paths and take the stroke color as tints. The public source identifies Decorative as a classic brush library; these preset designs are VectorCraft's own. Evidence: `decorative_brushes_repeat_distinct_art_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers distinct finite output, add/apply and saved-library reopening, and `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI.
|
||||
- **Paint library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Paint offers Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep. These original art brushes stretch broad, broken, loaded and fanned vector marks along a path and take the stroke color as tints. The public source describes the Paint category's varied thickness, textured edges and natural effects; the preset designs and names are VectorCraft's own. Evidence: `paint_brushes_draw_distinct_marks_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers finite output on short, long and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI.
|
||||
- **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`).
|
||||
- **Impact Bursts library:** Window › Brush Libraries › Impact Bursts holds six art brushes for hit sparks, shock rings and crack strokes: Star Burst, Ring Shock, Slash Arc, Spark Fan, Debris Spray and Crack Line. The brushes, their names and art are VectorCraft's own, generated in code with Tints colorization (`brush.libraries`, `brush.library`, `the_builtin_libraries_list_their_brush_names_and_counts`).
|
||||
- **Arrows library:** Window › Brush Libraries › Arrows holds five art brushes, each 100 pt long: Solid Arrow, Open Arrow (an outlined head), Double Arrow (a head at each end), Chevron Arrow (a second chevron on the shaft) and Dashed Arrow (five separate dashes and a head). Each brush stretches only the part between its guides, so the shaft follows the path's length and the heads keep their proportions, with Tints colorization. The brushes, their names and their art are VectorCraft's own, generated in code (`brush.libraries`, `brush.addFromLibrary`; `arrows_library_lists_renders_and_applies_original_brushes`, `dashed_arrow_keeps_separate_dashes_and_survives_library_save`).
|
||||
- **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`).
|
||||
- A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection; Outline Stroke when the selection has a visible stroke to outline, #5267; and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas.
|
||||
|
||||
Reference in new issue
Block a user