mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 17:37:10 +01:00
Merge main into feat/3d-classic-map-art
This commit is contained in:
commit
10d55e3ff8
176 files changed
+8750
-1750
No files matched your search
Generated
+143
-17
@@ -508,6 +508,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -981,7 +987,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
@@ -991,7 +997,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1033,6 +1039,36 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"craft-jpeg",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core 0.5.3",
|
||||
"zune-jpeg 0.5.15",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
@@ -1090,12 +1126,23 @@ dependencies = [
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2)",
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
"roxmltree 0.21.2",
|
||||
@@ -1105,6 +1152,15 @@ dependencies = [
|
||||
"vectorcraft-pathops 0.18.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -1203,6 +1259,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.3"
|
||||
@@ -1715,6 +1780,22 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "exr"
|
||||
version = "1.74.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
|
||||
dependencies = [
|
||||
"bit_field",
|
||||
"half",
|
||||
"lebe",
|
||||
"miniz_oxide 0.8.9",
|
||||
"multiversion",
|
||||
"rayon-core",
|
||||
"smallvec",
|
||||
"zune-inflate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2747,6 +2828,7 @@ dependencies = [
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png 0.18.1",
|
||||
"qoi",
|
||||
"tiff",
|
||||
"zune-core 0.5.3",
|
||||
"zune-jpeg 0.5.15",
|
||||
@@ -3200,6 +3282,12 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "lebe"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -3399,6 +3487,28 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
|
||||
dependencies = [
|
||||
"multiversion-macros",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion-macros"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
@@ -4349,21 +4459,21 @@ dependencies = [
|
||||
"unarray",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "psd"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a25f9b8cfffd65d911baf31a033239f7a0facb755faa2481575b70db5dc9195"
|
||||
dependencies = [
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pxfm"
|
||||
version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qoi"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
@@ -5734,6 +5844,12 @@ dependencies = [
|
||||
"xattr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-features"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -6546,6 +6662,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"craft-proof",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"hayro-jpeg2000",
|
||||
@@ -6558,7 +6675,6 @@ dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"roxmltree 0.21.2",
|
||||
"rustix 1.1.6",
|
||||
"ruzstd",
|
||||
"same-file",
|
||||
@@ -6734,6 +6850,7 @@ dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
"craft-pdf",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
@@ -6744,7 +6861,6 @@ dependencies = [
|
||||
"md-5",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"roxmltree 0.21.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
@@ -6785,16 +6901,16 @@ dependencies = [
|
||||
name = "vectorcraft-render"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-psd",
|
||||
"craft-tiff",
|
||||
"flate2",
|
||||
"gif 0.14.2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"proptest",
|
||||
"psd",
|
||||
"serde_json",
|
||||
"tiff",
|
||||
"unicode-general-category",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-color",
|
||||
@@ -6917,6 +7033,7 @@ dependencies = [
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -8371,6 +8488,15 @@ version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
|
||||
|
||||
[[package]]
|
||||
name = "zune-inflate"
|
||||
version = "0.2.54"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
|
||||
dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpeg"
|
||||
version = "0.4.21"
|
||||
|
||||
+6
-1
@@ -30,9 +30,14 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
|
||||
+2
-2
@@ -102,14 +102,14 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
|
||||
| Arabic | `ar` | none (no right-to-left interface) | 0% |
|
||||
| French | `fr` | full | 100% |
|
||||
| Portuguese (Brazil) | `pt-br` | full | 100% |
|
||||
| Indonesian | `id` | none | 0% |
|
||||
| Indonesian | `id` | 6,947 catalog rows; status and error messages partial | most dialogs and tooltips |
|
||||
| Japanese | `ja` | full | 100% |
|
||||
| German | `de` | full | 98% |
|
||||
| Korean | `ko` | full | 100% |
|
||||
| Bosnian | `bs` | full (AI-assisted, native review pending) | 100% |
|
||||
| Vietnamese | `vi` | full | 100% |
|
||||
|
||||
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
|
||||
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian, Georgian, Dutch, Danish and Turkish (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
|
||||
The Georgian catalog has had a native speaker's review; no other catalog has. Details: [localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
## Upcoming
|
||||
|
||||
@@ -155,6 +155,12 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
copied_file_within(paths, mimes, MAX_BYTES)
|
||||
}
|
||||
|
||||
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
|
||||
#[cfg_attr(windows, allow(dead_code))]
|
||||
fn takes_files(mimes: &[&'static str]) -> bool {
|
||||
mimes.iter().any(|&m| m != TEXT)
|
||||
}
|
||||
|
||||
/// [`copied_file`] with a file of more than `limit` bytes skipped.
|
||||
fn copied_file_within(paths: Vec<PathBuf>, mimes: &[&'static str], limit: usize) -> Option<Flavour> {
|
||||
paths.into_iter().find_map(|path| {
|
||||
@@ -727,7 +733,7 @@ mod portable {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
|
||||
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, takes_files, text_of};
|
||||
|
||||
/// What our last write put on the clipboard.
|
||||
#[derive(Clone)]
|
||||
@@ -741,7 +747,7 @@ mod portable {
|
||||
}
|
||||
|
||||
/// A read of arboard's clipboard.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Request {
|
||||
Text,
|
||||
Image,
|
||||
@@ -813,6 +819,19 @@ mod portable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a paste of one of `mimes` can take what `cb` holds: text that is not empty when one
|
||||
/// of `mimes` is text (`text` reads it), else files copied in a file manager when one of `mimes`
|
||||
/// is not text (`files` reads the list). The list is read only when the text doesn't do, and no
|
||||
/// copied file is opened: Paste checks the files themselves.
|
||||
fn arboard_has<B>(
|
||||
mimes: &[&'static str],
|
||||
cb: &mut B,
|
||||
text: impl FnOnce(&mut B) -> Result<String, String>,
|
||||
files: impl FnOnce(&mut B) -> Vec<PathBuf>,
|
||||
) -> bool {
|
||||
(mimes.contains(&TEXT) && text(cb).is_ok_and(|t| !t.is_empty())) || (takes_files(mimes) && !files(cb).is_empty())
|
||||
}
|
||||
|
||||
/// `request` read on `reads`' worker, waiting `wait` at most.
|
||||
#[cfg(test)]
|
||||
fn read_within(reads: &mut super::loads::Loads<Request, Answer>, request: Request, wait: Duration) -> Answer {
|
||||
@@ -1441,10 +1460,11 @@ mod portable {
|
||||
read
|
||||
}
|
||||
|
||||
/// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland
|
||||
/// core protocol copied files, SVG, text or PNG (by the types offered, nothing read).
|
||||
/// Text or files copied in a file manager (their list read, no file opened:
|
||||
/// [`arboard_has`]), on macOS vector art or a bitmap (by the pasteboard's types), and on the
|
||||
/// Wayland core protocol copied files, SVG, text or PNG (by the types offered, nothing read).
|
||||
/// arboard has no cheap way to ask for a bitmap (reading one costs as much as pasting it):
|
||||
/// the paste keys take it, the menu item waits for text.
|
||||
/// the paste keys take it, the menu item waits for text or copied files.
|
||||
fn has(&mut self, mimes: &[&'static str]) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
if super::mac::has(mimes) {
|
||||
@@ -1455,7 +1475,7 @@ mod portable {
|
||||
if let Backend::Wayland(wl) = cb {
|
||||
return wl.has(mimes);
|
||||
}
|
||||
mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty())
|
||||
arboard_has(mimes, cb, Backend::get_text, Backend::file_list)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1619,6 +1639,40 @@ mod portable {
|
||||
assert!(Answer::Text(Ok("art.svg".into())).files().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_is_available_for_files_copied_in_a_file_manager() {
|
||||
use vectorcraft_engine::cmd::clipboard::{PASTE_ORDER, SVG};
|
||||
/// What the clipboard holds, and which reads [`arboard_has`] made.
|
||||
struct Held {
|
||||
text: Option<String>,
|
||||
files: Vec<PathBuf>,
|
||||
reads: Vec<Request>,
|
||||
}
|
||||
fn has(mimes: &[&'static str], text: Option<&str>, files: &[&str]) -> (bool, Vec<Request>) {
|
||||
let mut held = Held { text: text.map(String::from), files: files.iter().map(PathBuf::from).collect(), reads: vec![] };
|
||||
let text = |h: &mut Held| {
|
||||
h.reads.push(Request::Text);
|
||||
h.text.clone().ok_or_else(|| "no text".to_string())
|
||||
};
|
||||
let files = |h: &mut Held| {
|
||||
h.reads.push(Request::Files);
|
||||
h.files.clone()
|
||||
};
|
||||
let has = arboard_has(mimes, &mut held, text, files);
|
||||
(has, held.reads)
|
||||
}
|
||||
// Files a file manager copied, with no text: the Paste menu item is available.
|
||||
assert_eq!(has(&PASTE_ORDER, None, &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files]));
|
||||
assert_eq!(has(&PASTE_ORDER, Some(""), &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files]));
|
||||
assert_eq!(has(&[SVG], None, &["/tmp/art.svg"]), (true, vec![Request::Files]));
|
||||
// Text does, and the list is not read.
|
||||
assert_eq!(has(&PASTE_ORDER, Some("hello"), &[]), (true, vec![Request::Text]));
|
||||
// An empty list and no text: nothing to paste.
|
||||
assert_eq!(has(&PASTE_ORDER, None, &[]), (false, vec![Request::Text, Request::Files]));
|
||||
// A paste of text alone can't take copied files, and their list is not read.
|
||||
assert_eq!(has(&[TEXT], None, &["/tmp/art.svg"]), (false, vec![Request::Text]));
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
|
||||
@@ -1925,7 +1979,7 @@ mod wayland {
|
||||
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
|
||||
|
||||
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
|
||||
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths};
|
||||
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
|
||||
|
||||
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
|
||||
/// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`.
|
||||
@@ -2016,11 +2070,6 @@ mod wayland {
|
||||
Some(first)
|
||||
}
|
||||
|
||||
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
|
||||
fn takes_files(mimes: &[&'static str]) -> bool {
|
||||
mimes.iter().any(|&m| m != TEXT)
|
||||
}
|
||||
|
||||
/// The first type among `offered` that lists copied files ([`FILE_LISTS`]), in any letter case.
|
||||
fn file_list_type(offered: &[String]) -> Option<&str> {
|
||||
FILE_LISTS.iter().find_map(|(list, _)| offered.iter().find(|o| o.eq_ignore_ascii_case(list))).map(String::as_str)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! VectorCraft desktop app.
|
||||
//!
|
||||
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--present-mode <mode>] [--frame-latency <frames>] [--] [files…]`,
|
||||
//! `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//!
|
||||
//! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is
|
||||
//! a file.
|
||||
@@ -19,6 +20,9 @@
|
||||
//! `--automation-write-root` (or `VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`) confine the
|
||||
//! files its requests read and write (`vectorcraft_engine::file_access`); the person at the
|
||||
//! keyboard isn't confined.
|
||||
//!
|
||||
//! `--present-mode` and `--frame-latency` (or `VECTORCRAFT_PRESENT_MODE` / `_FRAME_LATENCY`) change
|
||||
//! how the window's frames reach the display (`presentation`).
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
|
||||
mod automation_args;
|
||||
@@ -59,6 +63,7 @@ mod portal_request;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
|
||||
mod portal_save;
|
||||
mod prefs_dir;
|
||||
mod presentation;
|
||||
mod printing;
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
mod quit_windows;
|
||||
@@ -158,6 +163,14 @@ Options:
|
||||
--safe-mode Start without plug-ins: none loads or runs until
|
||||
VectorCraft starts normally (Help › Safe Mode); the
|
||||
files open in a new window, as with --new-instance
|
||||
--present-mode <mode> How frames reach the display: fifo (vsync),
|
||||
autovsync (the default; relaxed vsync where the
|
||||
driver offers it) or novsync
|
||||
(or VECTORCRAFT_PRESENT_MODE)
|
||||
--frame-latency <frames> Frames the display may queue, 1 to 3 (the default
|
||||
is 1) (or VECTORCRAFT_FRAME_LATENCY); with either
|
||||
one set, the files open in a new window, as with
|
||||
--new-instance
|
||||
--version Print the version and exit
|
||||
-h, --help Print this help and exit
|
||||
-- Treat every argument after it as a file
|
||||
@@ -177,13 +190,16 @@ struct CommandLine {
|
||||
safe_mode: bool,
|
||||
}
|
||||
|
||||
/// Reads the arguments after the program name. The automation roots and the control port go into
|
||||
/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and
|
||||
/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails.
|
||||
/// Reads the arguments after the program name. The automation roots, the control port and the
|
||||
/// presentation overrides (with `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY` filling
|
||||
/// what the flags leave unset) go into `roots_args`, `control` and `presentation`. `Err` is the exit code
|
||||
/// when the process ends here: `--version` and `--help` print and succeed; a bad automation or
|
||||
/// presentation option or an unknown option prints an error and fails.
|
||||
fn read_command_line(
|
||||
mut args: impl Iterator<Item = String>,
|
||||
control: &mut automation_args::ControlArg,
|
||||
roots_args: &mut automation_args::AutomationArgs,
|
||||
presentation: &mut presentation::Overrides,
|
||||
) -> Result<CommandLine, std::process::ExitCode> {
|
||||
let mut files = Vec::new();
|
||||
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
@@ -196,7 +212,11 @@ fn read_command_line(
|
||||
files.extend(args.by_ref());
|
||||
break;
|
||||
}
|
||||
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
|
||||
match roots_args
|
||||
.consume(&a, &mut args)
|
||||
.and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) })
|
||||
.and_then(|taken| if taken { Ok(true) } else { presentation.consume(&a, &mut args) })
|
||||
{
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
@@ -235,6 +255,14 @@ fn read_command_line(
|
||||
eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
// After the arguments: the flags, `--version` and `--help` win over a bad environment value.
|
||||
match presentation.with_env(std::env::var_os("VECTORCRAFT_PRESENT_MODE"), std::env::var_os("VECTORCRAFT_FRAME_LATENCY")) {
|
||||
Ok(overrides) => *presentation = overrides,
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
}
|
||||
Ok(CommandLine { files, in_window_menus, new_instance, safe_mode })
|
||||
}
|
||||
|
||||
@@ -253,8 +281,9 @@ fn main() -> std::process::ExitCode {
|
||||
let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from);
|
||||
let mut roots_args =
|
||||
automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT"));
|
||||
let mut presentation = presentation::Overrides::default();
|
||||
let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
|
||||
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) {
|
||||
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) {
|
||||
Ok(command_line) => command_line,
|
||||
Err(code) => return code,
|
||||
};
|
||||
@@ -275,7 +304,8 @@ fn main() -> std::process::ExitCode {
|
||||
// Files opened from the file manager while VectorCraft runs open in its window (#4892). Before
|
||||
// the log file is attached: a launch that hands its files over leaves the running app's log be.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) {
|
||||
// A launch that sets the presentation runs as its own app: a running app keeps its own surface.
|
||||
match single_instance::start(control_port.is_some(), new_instance || presentation.is_set(), safe_mode_flag, &files) {
|
||||
single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS,
|
||||
single_instance::Start::Running(primary) => single_instance::hold(primary),
|
||||
}
|
||||
@@ -427,7 +457,10 @@ fn main() -> std::process::ExitCode {
|
||||
let mut options = options;
|
||||
// One frame queued, not two: the canvas is rasterized on the CPU and the GPU only
|
||||
// composites it, so the window answers the pointer a frame sooner (#444).
|
||||
options.wgpu_options.surface = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
|
||||
// `--present-mode` and `--frame-latency` change it for a launch (`presentation`).
|
||||
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
|
||||
// What the app asks for: the driver picks novsync's mode and may clamp the latency.
|
||||
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation));
|
||||
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone()));
|
||||
@@ -458,6 +491,10 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
options
|
||||
};
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
if presentation != presentation::Overrides::default() {
|
||||
log::warn!("--present-mode and --frame-latency set the wgpu renderer's window surface: ignored without it");
|
||||
}
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu::watch_panics();
|
||||
#[cfg(feature = "wgpu")]
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! `--present-mode <mode>` (or `VECTORCRAFT_PRESENT_MODE`) and `--frame-latency <frames>` (or
|
||||
//! `VECTORCRAFT_FRAME_LATENCY`) set how the window's frames reach the display for one launch. The
|
||||
//! modes are `fifo` (vsync), `autovsync` (the default: wgpu picks relaxed vsync, which tears a late
|
||||
//! frame, else vsync, by what the driver offers) and `novsync` (wgpu picks Immediate, else Mailbox,
|
||||
//! else Fifo). A mode the driver may not offer is never requested. The latency is the number of
|
||||
//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag
|
||||
//! overrides its variable; a value that isn't one of these stops the app with a message, as
|
||||
//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`.
|
||||
//! The surface the app asks for is logged at start-up.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// A present mode the command line or the environment can ask for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Fifo,
|
||||
AutoVsync,
|
||||
NoVsync,
|
||||
}
|
||||
|
||||
/// The present mode and frame latency this launch asked for (`None`: the app's own setting).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Overrides {
|
||||
pub mode: Option<Mode>,
|
||||
pub latency: Option<u32>,
|
||||
}
|
||||
|
||||
/// A present mode named by `name` (the flag or the variable): `fifo`, `autovsync` or `novsync`, any case.
|
||||
fn mode(name: &str, value: Option<&str>) -> Result<Mode, String> {
|
||||
let need = format!("{name} needs fifo, autovsync or novsync");
|
||||
let Some(v) = value else { return Err(need) };
|
||||
match v.trim().to_ascii_lowercase().as_str() {
|
||||
"fifo" => Ok(Mode::Fifo),
|
||||
"autovsync" => Ok(Mode::AutoVsync),
|
||||
"novsync" => Ok(Mode::NoVsync),
|
||||
_ => Err(format!("{need}, not `{v}`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame latency named by `name`: 1, 2 or 3.
|
||||
fn latency(name: &str, value: Option<&str>) -> Result<u32, String> {
|
||||
let need = format!("{name} needs 1, 2 or 3 frames");
|
||||
let Some(v) = value else { return Err(need) };
|
||||
v.trim().parse().ok().filter(|n| (1..=3).contains(n)).ok_or(format!("{need}, not `{v}`"))
|
||||
}
|
||||
|
||||
/// The value of `--flag <value>` or `--flag=<value>` when `arg` is that flag; `None` when it isn't.
|
||||
fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) -> Option<Option<String>> {
|
||||
match arg.strip_prefix(flag)? {
|
||||
"" => Some(args.next()),
|
||||
rest => rest.strip_prefix('=').map(|v| Some(v.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
impl Overrides {
|
||||
/// Whether a flag or a variable set the present mode or the frame latency.
|
||||
pub fn is_set(&self) -> bool {
|
||||
*self != Self::default()
|
||||
}
|
||||
|
||||
/// Returns whether this argument is `--present-mode` or `--frame-latency`. The next argument is
|
||||
/// its value whatever it is, as with `--control`.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
if let Some(value) = flag_value("--present-mode", arg, args) {
|
||||
if self.mode.is_some() {
|
||||
return Err("--present-mode given twice".into());
|
||||
}
|
||||
self.mode = Some(mode("--present-mode", value.as_deref())?);
|
||||
return Ok(true);
|
||||
}
|
||||
if let Some(value) = flag_value("--frame-latency", arg, args) {
|
||||
if self.latency.is_some() {
|
||||
return Err("--frame-latency given twice".into());
|
||||
}
|
||||
self.latency = Some(latency("--frame-latency", value.as_deref())?);
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Fills what the flags left unset from `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY`.
|
||||
/// Unset or empty is no override; a variable is not read when its flag was given.
|
||||
pub fn with_env(self, mode_var: Option<OsString>, latency_var: Option<OsString>) -> Result<Self, String> {
|
||||
let set = |v: Option<OsString>| v.filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned());
|
||||
let mode = match (self.mode, set(mode_var)) {
|
||||
(Some(m), _) => Some(m),
|
||||
(None, Some(v)) => Some(mode("VECTORCRAFT_PRESENT_MODE", Some(&v))?),
|
||||
(None, None) => None,
|
||||
};
|
||||
let latency = match (self.latency, set(latency_var)) {
|
||||
(Some(n), _) => Some(n),
|
||||
(None, Some(v)) => Some(latency("VECTORCRAFT_FRAME_LATENCY", Some(&v))?),
|
||||
(None, None) => None,
|
||||
};
|
||||
Ok(Self { mode, latency })
|
||||
}
|
||||
|
||||
/// `surface` with the overrides applied.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let present_mode = match self.mode {
|
||||
Some(Mode::Fifo) => PresentMode::Fifo,
|
||||
Some(Mode::AutoVsync) => PresentMode::AutoVsync,
|
||||
Some(Mode::NoVsync) => PresentMode::AutoNoVsync,
|
||||
None => surface.present_mode,
|
||||
};
|
||||
eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The present mode and frame latency `surface` asks for, for the start-up log:
|
||||
/// "autovsync, frame latency 1", with "(override)"
|
||||
/// after a value a flag or variable set.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let mode = match surface.present_mode {
|
||||
PresentMode::AutoVsync => "autovsync",
|
||||
PresentMode::AutoNoVsync => "novsync",
|
||||
PresentMode::Fifo => "fifo",
|
||||
PresentMode::FifoRelaxed => "fiforelaxed",
|
||||
PresentMode::Immediate => "immediate",
|
||||
PresentMode::Mailbox => "mailbox",
|
||||
};
|
||||
let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
|
||||
let tag = |set: bool| if set { " (override)" } else { "" };
|
||||
format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Overrides, String> {
|
||||
let mut overrides = Overrides::default();
|
||||
let mut args = args.iter().map(|a| a.to_string());
|
||||
while let Some(a) = args.next() {
|
||||
assert!(overrides.consume(&a, &mut args)?, "{a}");
|
||||
}
|
||||
Ok(overrides)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_take_the_three_modes_and_latencies_from_1_to_3() {
|
||||
assert_eq!(parse(&[]), Ok(Overrides::default()));
|
||||
assert_eq!(parse(&["--present-mode", "fifo"]).map(|o| o.mode), Ok(Some(Mode::Fifo)));
|
||||
assert_eq!(parse(&["--present-mode=AutoVsync"]).map(|o| o.mode), Ok(Some(Mode::AutoVsync)));
|
||||
assert_eq!(parse(&["--present-mode", " novsync "]).map(|o| o.mode), Ok(Some(Mode::NoVsync)));
|
||||
for n in 1..=3 {
|
||||
assert_eq!(parse(&["--frame-latency", &n.to_string()]).map(|o| o.latency), Ok(Some(n)));
|
||||
}
|
||||
assert_eq!(parse(&["--frame-latency=2", "--present-mode", "fifo"]), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_flag_values_are_errors() {
|
||||
let modes = "--present-mode needs fifo, autovsync or novsync";
|
||||
assert_eq!(parse(&["--present-mode"]), Err(modes.into()));
|
||||
for bad in ["mailbox", "immediate", "vsync", "fast", ""] {
|
||||
assert_eq!(parse(&["--present-mode", bad]), Err(format!("{modes}, not `{bad}`")));
|
||||
assert_eq!(parse(&[&format!("--present-mode={bad}")]), Err(format!("{modes}, not `{bad}`")));
|
||||
}
|
||||
assert_eq!(parse(&["--present-mode", "--frame-latency"]), Err(format!("{modes}, not `--frame-latency`")));
|
||||
let frames = "--frame-latency needs 1, 2 or 3 frames";
|
||||
assert_eq!(parse(&["--frame-latency"]), Err(frames.into()));
|
||||
for bad in ["0", "4", "-1", "one", "1.5", "99999999999", ""] {
|
||||
assert_eq!(parse(&["--frame-latency", bad]), Err(format!("{frames}, not `{bad}`")));
|
||||
}
|
||||
assert_eq!(parse(&["--present-mode", "fifo", "--present-mode=novsync"]), Err("--present-mode given twice".into()));
|
||||
assert_eq!(parse(&["--frame-latency=1", "--frame-latency", "2"]), Err("--frame-latency given twice".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_arguments_are_not_presentation_flags() {
|
||||
let mut overrides = Overrides::default();
|
||||
let mut args = ["fifo".to_owned()].into_iter();
|
||||
for other in ["--present-modes", "--present", "--frame-latency-2", "drawing.svg", "--control"] {
|
||||
assert!(!overrides.consume(other, &mut args).unwrap(), "{other}");
|
||||
}
|
||||
assert_eq!(args.next().as_deref(), Some("fifo"));
|
||||
assert_eq!(overrides, Overrides::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_fill_what_the_flags_leave_unset_and_bad_values_are_errors() {
|
||||
let none = Overrides::default();
|
||||
assert_eq!(none.with_env(None, None), Ok(none));
|
||||
assert_eq!(none.with_env(Some("".into()), Some("".into())), Ok(none));
|
||||
assert_eq!(none.with_env(Some("FIFO".into()), Some("2".into())), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) }));
|
||||
assert_eq!(
|
||||
none.with_env(Some("mailbox".into()), None),
|
||||
Err("VECTORCRAFT_PRESENT_MODE needs fifo, autovsync or novsync, not `mailbox`".into())
|
||||
);
|
||||
assert_eq!(none.with_env(None, Some("0".into())), Err("VECTORCRAFT_FRAME_LATENCY needs 1, 2 or 3 frames, not `0`".into()));
|
||||
// A flag wins, and its variable is not read, so a bad value there doesn't stop the app.
|
||||
let flags = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
|
||||
assert_eq!(flags.with_env(Some("bad".into()), Some("9".into())), Ok(flags));
|
||||
let mode_only = Overrides { mode: Some(Mode::AutoVsync), latency: None };
|
||||
assert_eq!(mode_only.with_env(Some("bad".into()), Some("1".into())), Ok(Overrides { mode: Some(Mode::AutoVsync), latency: Some(1) }));
|
||||
// Either value set makes the launch run as its own app.
|
||||
assert!(!none.is_set());
|
||||
assert!(mode_only.is_set());
|
||||
assert!(Overrides { mode: None, latency: Some(1) }.is_set());
|
||||
}
|
||||
|
||||
/// `--help` states the app's own surface as the default, so it changes with it.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn the_usage_names_the_app_surface_as_the_default() {
|
||||
let app = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
|
||||
let usage = crate::USAGE.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
assert_eq!(app.present_mode, eframe::wgpu::PresentMode::AutoVsync, "the usage calls autovsync the default");
|
||||
assert!(usage.contains("autovsync (the default"), "{usage}");
|
||||
let Some(frames) = app.desired_maximum_frame_latency else { panic!("the usage gives a default frame latency") };
|
||||
assert!(usage.contains(&format!("(the default is {frames})")), "{usage}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn overrides_change_only_what_they_set_on_the_app_surface() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
// No override: the surface the app asks for is unchanged.
|
||||
assert_eq!(Overrides::default().apply(app), app);
|
||||
let latency = Overrides { mode: None, latency: Some(2) };
|
||||
let s = latency.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2)));
|
||||
assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)");
|
||||
let fifo = Overrides { mode: Some(Mode::Fifo), latency: None };
|
||||
let s = fifo.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency));
|
||||
// Never a mode the driver may lack: no vsync lets wgpu fall back by support.
|
||||
let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
|
||||
let s = novsync.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3)));
|
||||
assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)");
|
||||
let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None };
|
||||
assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default");
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,17 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}");
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] {
|
||||
for flag in [
|
||||
"--control",
|
||||
"--automation-read-root",
|
||||
"--automation-write-root",
|
||||
"--in-window-menus",
|
||||
"--safe-mode",
|
||||
"--present-mode",
|
||||
"--frame-latency",
|
||||
"--version",
|
||||
"--help",
|
||||
] {
|
||||
assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}");
|
||||
}
|
||||
// Headless work is the CLI's: the usage says where to go.
|
||||
@@ -73,6 +83,32 @@ fn help_wins_over_a_bad_control_port_variable() {
|
||||
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
|
||||
}
|
||||
|
||||
/// A bad presentation variable stops the app with a message before it starts; `--help` and the
|
||||
/// matching flag win over it. A run that gets past it stops at the control port `run` makes fail.
|
||||
#[test]
|
||||
fn a_bad_presentation_variable_is_an_error_unless_help_or_its_flag_is_given() {
|
||||
for (var, value, need) in [
|
||||
("VECTORCRAFT_FRAME_LATENCY", "0", "needs 1, 2 or 3 frames, not `0`"),
|
||||
("VECTORCRAFT_PRESENT_MODE", "mailbox", "needs fifo, autovsync or novsync, not `mailbox`"),
|
||||
] {
|
||||
let out = run(&[], &[(var, value)]);
|
||||
assert!(!out.status.success(), "{var}");
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), format!("vectorcraft: {var} {need}\n"));
|
||||
prints_usage(&["--help"], &[(var, value)]);
|
||||
}
|
||||
for (args, env) in [
|
||||
(&["--frame-latency", "2"][..], ("VECTORCRAFT_FRAME_LATENCY", "0")),
|
||||
(&["--present-mode=fifo"], ("VECTORCRAFT_PRESENT_MODE", "mailbox")),
|
||||
(&[], ("VECTORCRAFT_FRAME_LATENCY", "3")),
|
||||
] {
|
||||
let stderr = String::from_utf8(run(args, &[env]).stderr).unwrap();
|
||||
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains(env.0), "{args:?}: {stderr}");
|
||||
}
|
||||
let out = run(&["--frame-latency", "4"], &[]);
|
||||
assert!(!out.status.success());
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), "vectorcraft: --frame-latency needs 1, 2 or 3 frames, not `4`\n");
|
||||
}
|
||||
|
||||
/// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with
|
||||
/// plug-ins; a later `--help` still wins.
|
||||
#[test]
|
||||
|
||||
@@ -3,7 +3,7 @@ name = "vectorcraft-cad"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer"
|
||||
description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
+19
-4
@@ -1,4 +1,4 @@
|
||||
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on
|
||||
//! CAD interchange: a DXF writer (versions R12 to 2018) on `craft_dxf::drawing` and a reader on
|
||||
//! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer.
|
||||
//!
|
||||
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
|
||||
@@ -15,7 +15,7 @@
|
||||
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
|
||||
//!
|
||||
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
|
||||
//! - `writer`: group codes, handles and the file's sections, tables and objects.
|
||||
//! - The ASCII file around those entities is written by `craft_dxf::drawing`.
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
@@ -24,7 +24,6 @@ mod aci;
|
||||
pub mod hpgl;
|
||||
pub mod import;
|
||||
mod scene;
|
||||
mod writer;
|
||||
|
||||
use vectorcraft_doc::{Document, Unit};
|
||||
use vectorcraft_geom::Rect;
|
||||
@@ -136,11 +135,27 @@ impl DxfVersion {
|
||||
self >= Self::R2004
|
||||
}
|
||||
/// Text is UTF-8 (earlier versions escape what isn't ASCII as `\U+XXXX`).
|
||||
fn utf8(self) -> bool {
|
||||
pub fn utf8(self) -> bool {
|
||||
self >= Self::R2007
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DxfVersion> for craft_dxf::drawing::Format {
|
||||
fn from(v: DxfVersion) -> Self {
|
||||
match v {
|
||||
DxfVersion::R12 => Self::R12,
|
||||
DxfVersion::R13 => Self::R13,
|
||||
DxfVersion::R14 => Self::R14,
|
||||
DxfVersion::R2000 => Self::R2000,
|
||||
DxfVersion::R2004 => Self::R2004,
|
||||
DxfVersion::R2007 => Self::R2007,
|
||||
DxfVersion::R2010 => Self::R2010,
|
||||
DxfVersion::R2013 => Self::R2013,
|
||||
DxfVersion::R2018 => Self::R2018,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many colours entities may use: indexed colours of the 256-colour palette, or true colour
|
||||
/// (with the nearest index for apps that read only the index).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
|
||||
@@ -14,8 +14,8 @@ use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
|
||||
use crate::aci::nearest_aci;
|
||||
use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed};
|
||||
use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat};
|
||||
use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed};
|
||||
|
||||
/// Curves are flattened to within this distance (points) where DXF needs straight segments
|
||||
/// (hatch boundaries, R12 polylines).
|
||||
@@ -543,7 +543,7 @@ impl<'a> Scene<'a> {
|
||||
o,
|
||||
to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]),
|
||||
k,
|
||||
e: Codes::new(o.version),
|
||||
e: Codes::new(o.version.into()),
|
||||
next: fixed::FIRST_FREE,
|
||||
layers: vec![],
|
||||
layer_names: Names::with(&["0", "Defpoints"]),
|
||||
@@ -551,7 +551,7 @@ impl<'a> Scene<'a> {
|
||||
flags: LayerFlags { off: false, locked: false, plot: true },
|
||||
linetypes: vec![],
|
||||
styles: vec![],
|
||||
style_names: Names::with(&[crate::writer::STANDARD_STYLE]),
|
||||
style_names: Names::with(&[STANDARD_STYLE]),
|
||||
images: vec![],
|
||||
files: vec![],
|
||||
by_key: HashMap::new(),
|
||||
@@ -579,7 +579,7 @@ impl<'a> Scene<'a> {
|
||||
let one = (self.o.scale - 1.0).abs() < 1e-12;
|
||||
let insunits = if one { crate::insunits_code(self.o.unit).unwrap_or(0) } else { 0 };
|
||||
let drawing = Drawing {
|
||||
version: self.o.version,
|
||||
version: self.o.version.into(),
|
||||
layers: self.layers,
|
||||
linetypes: self.linetypes,
|
||||
styles: self.styles,
|
||||
|
||||
@@ -1451,3 +1451,23 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
assert!(entities(&out).is_empty());
|
||||
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_bytes_match_shared_writer_goldens() {
|
||||
use std::path::PathBuf;
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data");
|
||||
let cases: [(&str, DxfVersion, Document); 2] =
|
||||
[("shapes_r12.dxf", DxfVersion::R12, shapes_doc()), ("shapes_r2018.dxf", DxfVersion::R2018, shapes_doc())];
|
||||
for (name, version, doc) in cases {
|
||||
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
|
||||
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
|
||||
let path = dir.join(name);
|
||||
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&path, got).unwrap();
|
||||
continue;
|
||||
}
|
||||
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
}
|
||||
}
|
||||
@@ -1,674 +0,0 @@
|
||||
//! The ASCII DXF file: group codes, handles, and the sections, tables and objects around the
|
||||
//! entities. DXF R13 and later give every object a handle and subclass markers; R2000 and later
|
||||
//! add layouts and plot styles, which CAD apps expect to find.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::DxfVersion;
|
||||
|
||||
/// An object handle (written in hex).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Handle(pub u32);
|
||||
|
||||
/// The handles of the fixed objects every drawing has. Entities and table entries count up from
|
||||
/// [`FIRST_FREE`].
|
||||
pub(crate) mod fixed {
|
||||
use super::Handle;
|
||||
pub const LAYER_TABLE: Handle = Handle(0x1);
|
||||
pub const LTYPE_TABLE: Handle = Handle(0x2);
|
||||
pub const APPID_TABLE: Handle = Handle(0x3);
|
||||
pub const DIMSTYLE_TABLE: Handle = Handle(0x4);
|
||||
pub const STYLE_TABLE: Handle = Handle(0x5);
|
||||
pub const UCS_TABLE: Handle = Handle(0x6);
|
||||
pub const VIEW_TABLE: Handle = Handle(0x7);
|
||||
pub const VPORT_TABLE: Handle = Handle(0x8);
|
||||
pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9);
|
||||
pub const ROOT: Handle = Handle(0xA);
|
||||
pub const GROUPS: Handle = Handle(0xB);
|
||||
pub const LAYOUTS: Handle = Handle(0xC);
|
||||
pub const MODEL_RECORD: Handle = Handle(0xD);
|
||||
pub const PAPER_RECORD: Handle = Handle(0xE);
|
||||
pub const MODEL_BLOCK: Handle = Handle(0xF);
|
||||
pub const MODEL_END: Handle = Handle(0x10);
|
||||
pub const PAPER_BLOCK: Handle = Handle(0x11);
|
||||
pub const PAPER_END: Handle = Handle(0x12);
|
||||
pub const MODEL_LAYOUT: Handle = Handle(0x13);
|
||||
pub const PAPER_LAYOUT: Handle = Handle(0x14);
|
||||
pub const ACTIVE_VPORT: Handle = Handle(0x15);
|
||||
pub const ACAD_APPID: Handle = Handle(0x16);
|
||||
pub const STANDARD_DIMSTYLE: Handle = Handle(0x17);
|
||||
pub const IMAGE_DICT: Handle = Handle(0x18);
|
||||
pub const IMAGE_VARS: Handle = Handle(0x19);
|
||||
pub const PLOT_STYLES: Handle = Handle(0x1A);
|
||||
pub const PLOT_NORMAL: Handle = Handle(0x1B);
|
||||
pub const FIRST_FREE: u32 = 0x30;
|
||||
}
|
||||
|
||||
/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite.
|
||||
pub(crate) fn num(v: f64) -> String {
|
||||
if !v.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
let s = format!("{v:.6}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" || s.is_empty() { "0".into() } else { s.into() }
|
||||
}
|
||||
|
||||
/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8)
|
||||
/// every character outside ASCII as `\U+XXXX`.
|
||||
pub(crate) fn text(s: &str, utf8: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\r' | '\n' | '\t' => out.push(' '),
|
||||
c if c.is_control() => {}
|
||||
'^' => out.push_str("^ "),
|
||||
c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) {
|
||||
Ok(u) => _ = write!(out, "\\U+{u:04X}"),
|
||||
Err(_) => out.push('?'),
|
||||
},
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Group-code/value pairs in the order they are written.
|
||||
pub(crate) struct Codes {
|
||||
pub v: DxfVersion,
|
||||
out: String,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
pub fn new(v: DxfVersion) -> Self {
|
||||
Self { v, out: String::new() }
|
||||
}
|
||||
|
||||
pub fn into_string(self) -> String {
|
||||
self.out
|
||||
}
|
||||
|
||||
pub fn append(&mut self, other: &str) {
|
||||
self.out.push_str(other);
|
||||
}
|
||||
|
||||
/// A value written as it is (names and keywords the writer itself chose).
|
||||
pub fn raw(&mut self, code: u16, value: &str) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
/// Text from the document, encoded for the version (see [`text`]).
|
||||
pub fn str(&mut self, code: u16, value: &str) {
|
||||
let t = text(value, self.v.utf8());
|
||||
self.raw(code, &t);
|
||||
}
|
||||
|
||||
pub fn int(&mut self, code: u16, value: i64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
pub fn num(&mut self, code: u16, value: f64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{}", num(value));
|
||||
}
|
||||
|
||||
pub fn handle(&mut self, code: u16, h: Handle) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{:X}", h.0);
|
||||
}
|
||||
|
||||
/// A 2D point at `code` (x), `code + 10` (y).
|
||||
pub fn xy(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.num(code, x);
|
||||
self.num(code + 10, y);
|
||||
}
|
||||
|
||||
/// A 3D point at `code`, `code + 10`, `code + 20` (z = 0).
|
||||
pub fn xyz(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.xy(code, x, y);
|
||||
self.num(code + 20, 0.0);
|
||||
}
|
||||
|
||||
/// The extrusion direction of planar entities: the z axis.
|
||||
pub fn normal(&mut self) {
|
||||
self.num(210, 0.0);
|
||||
self.num(220, 0.0);
|
||||
self.num(230, 1.0);
|
||||
}
|
||||
|
||||
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
|
||||
fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) {
|
||||
self.raw(0, kind);
|
||||
if self.v.handles() {
|
||||
self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h);
|
||||
self.handle(330, owner);
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
/// A table entry: the shared record subclass, then the table's own (from R13).
|
||||
fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) {
|
||||
self.object(kind, h, table, "AcDbSymbolTableRecord");
|
||||
if self.v.handles() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
fn section(&mut self, name: &str) {
|
||||
self.raw(0, "SECTION");
|
||||
self.raw(2, name);
|
||||
}
|
||||
|
||||
fn end_section(&mut self) {
|
||||
self.raw(0, "ENDSEC");
|
||||
}
|
||||
|
||||
fn table(&mut self, name: &str, h: Handle, count: usize) {
|
||||
self.raw(0, "TABLE");
|
||||
self.raw(2, name);
|
||||
if self.v.handles() {
|
||||
self.handle(5, h);
|
||||
self.raw(330, "0");
|
||||
self.raw(100, "AcDbSymbolTable");
|
||||
}
|
||||
self.int(70, count as i64);
|
||||
if name == "DIMSTYLE" && self.v.r2000() {
|
||||
self.raw(100, "AcDbDimStyleTable");
|
||||
}
|
||||
}
|
||||
|
||||
fn end_table(&mut self) {
|
||||
self.raw(0, "ENDTAB");
|
||||
}
|
||||
}
|
||||
|
||||
/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct EntityStyle {
|
||||
pub aci: u8,
|
||||
/// `0xRRGGBB` (DXF 2004 and later).
|
||||
pub rgb: Option<u32>,
|
||||
/// Hundredths of a millimetre (DXF 2000 and later).
|
||||
pub lineweight: Option<i32>,
|
||||
pub linetype: Option<String>,
|
||||
/// Opacity 0–255 (DXF 2004 and later; opaque is left out).
|
||||
pub alpha: Option<u8>,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
/// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its
|
||||
/// vertices) on `layer` with its style, ending with `subclass` (none when empty).
|
||||
pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) {
|
||||
self.object(kind, h, owner, "AcDbEntity");
|
||||
self.str(8, layer);
|
||||
if let Some(lt) = &style.linetype {
|
||||
self.str(6, lt);
|
||||
}
|
||||
self.int(62, i64::from(style.aci.max(1)));
|
||||
if self.v.r2000()
|
||||
&& let Some(lw) = style.lineweight
|
||||
{
|
||||
self.int(370, i64::from(lw));
|
||||
}
|
||||
if self.v.true_color() {
|
||||
if let Some(rgb) = style.rgb {
|
||||
self.int(420, i64::from(rgb));
|
||||
}
|
||||
if let Some(a) = style.alpha {
|
||||
self.int(440, 0x0200_0000 | i64::from(a));
|
||||
}
|
||||
}
|
||||
if self.v.handles() && !subclass.is_empty() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A DXF layer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Layer {
|
||||
pub name: String,
|
||||
pub aci: u8,
|
||||
/// Switched off (a hidden layer).
|
||||
pub off: bool,
|
||||
pub locked: bool,
|
||||
/// Plotted (printable).
|
||||
pub plot: bool,
|
||||
}
|
||||
|
||||
/// A dash pattern: dash, gap, dash… lengths in drawing units.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct LineType {
|
||||
pub name: String,
|
||||
pub pattern: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A placed image file and the image entities that show it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageDef {
|
||||
pub name: String,
|
||||
pub size: (u32, u32),
|
||||
pub handle: Handle,
|
||||
/// `(reactor, image entity)` per image entity.
|
||||
pub reactors: Vec<(Handle, Handle)>,
|
||||
}
|
||||
|
||||
/// Everything around the entities, collected while they were written.
|
||||
pub(crate) struct Drawing {
|
||||
pub version: DxfVersion,
|
||||
pub layers: Vec<Layer>,
|
||||
pub linetypes: Vec<LineType>,
|
||||
/// Text styles: (style name, font family).
|
||||
pub styles: Vec<(String, String)>,
|
||||
pub images: Vec<ImageDef>,
|
||||
/// The entities' group codes.
|
||||
pub entities: String,
|
||||
/// `[x0, y0, x1, y1]` of everything written (drawing units).
|
||||
pub extents: [f64; 4],
|
||||
/// The export region (drawing units).
|
||||
pub limits: [f64; 4],
|
||||
/// `$INSUNITS`.
|
||||
pub insunits: u8,
|
||||
pub metric: bool,
|
||||
/// The next free handle.
|
||||
pub next: u32,
|
||||
}
|
||||
|
||||
/// The text style every drawing has.
|
||||
pub(crate) const STANDARD_STYLE: &str = "Standard";
|
||||
|
||||
impl Drawing {
|
||||
/// The whole file.
|
||||
pub fn write(self) -> String {
|
||||
let v = self.version;
|
||||
let mut c = Codes::new(v);
|
||||
// Table entries get the handles after the entities'.
|
||||
let mut next = self.next;
|
||||
let mut take = |n: usize| {
|
||||
let start = next;
|
||||
next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
|
||||
start
|
||||
};
|
||||
let ltype_base = take(3 + self.linetypes.len());
|
||||
let layer_base = take(1 + self.layers.len());
|
||||
let style_base = take(1 + self.styles.len());
|
||||
self.header(&mut c, next);
|
||||
if v.handles() {
|
||||
self.classes(&mut c);
|
||||
}
|
||||
c.section("TABLES");
|
||||
self.vport(&mut c);
|
||||
self.ltypes(&mut c, ltype_base);
|
||||
self.layer_table(&mut c, layer_base);
|
||||
self.style_table(&mut c, style_base);
|
||||
if v.handles() {
|
||||
for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] {
|
||||
c.table(name, h, 0);
|
||||
c.end_table();
|
||||
}
|
||||
c.table("APPID", fixed::APPID_TABLE, 1);
|
||||
c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord");
|
||||
c.raw(2, "ACAD");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1);
|
||||
c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord");
|
||||
c.raw(2, "Standard");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2);
|
||||
for (name, h, layout) in
|
||||
[("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)]
|
||||
{
|
||||
c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord");
|
||||
c.raw(2, name);
|
||||
if v.r2000() {
|
||||
c.handle(340, layout);
|
||||
c.int(70, 0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
c.section("BLOCKS");
|
||||
for (name, record, begin, end) in [
|
||||
("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END),
|
||||
("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END),
|
||||
] {
|
||||
c.object("BLOCK", begin, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockBegin");
|
||||
c.raw(2, name);
|
||||
c.int(70, 0);
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
c.raw(3, name);
|
||||
c.raw(1, "");
|
||||
c.object("ENDBLK", end, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockEnd");
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
c.section("ENTITIES");
|
||||
c.append(&self.entities);
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
self.objects(&mut c);
|
||||
}
|
||||
c.raw(0, "EOF");
|
||||
c.into_string()
|
||||
}
|
||||
|
||||
fn header(&self, c: &mut Codes, handseed: u32) {
|
||||
let v = self.version;
|
||||
let var = |c: &mut Codes, name: &str| c.raw(9, name);
|
||||
c.section("HEADER");
|
||||
var(c, "$ACADVER");
|
||||
c.raw(1, v.acadver());
|
||||
var(c, "$DWGCODEPAGE");
|
||||
c.raw(3, "ANSI_1252");
|
||||
var(c, "$INSBASE");
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
var(c, "$EXTMIN");
|
||||
c.xyz(10, x0, y0);
|
||||
var(c, "$EXTMAX");
|
||||
c.xyz(10, x1, y1);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
var(c, "$LIMMIN");
|
||||
c.xy(10, lx0, ly0);
|
||||
var(c, "$LIMMAX");
|
||||
c.xy(10, lx1, ly1);
|
||||
if v.r2000() {
|
||||
var(c, "$LWDISPLAY");
|
||||
c.int(290, 1);
|
||||
var(c, "$INSUNITS");
|
||||
c.int(70, i64::from(self.insunits));
|
||||
var(c, "$MEASUREMENT");
|
||||
c.int(70, i64::from(self.metric));
|
||||
}
|
||||
if v.handles() {
|
||||
var(c, "$HANDSEED");
|
||||
c.handle(5, Handle(handseed));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
fn classes(&self, c: &mut Codes) {
|
||||
let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![];
|
||||
if self.version.r2000() {
|
||||
classes.extend([
|
||||
("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false),
|
||||
("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false),
|
||||
("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false),
|
||||
]);
|
||||
}
|
||||
if !self.images.is_empty() {
|
||||
classes.extend([
|
||||
("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false),
|
||||
("IMAGE", "AcDbRasterImage", "ISM", 2175, true),
|
||||
("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false),
|
||||
("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false),
|
||||
]);
|
||||
}
|
||||
c.section("CLASSES");
|
||||
for (name, cpp, app, flags, entity) in classes {
|
||||
c.raw(0, "CLASS");
|
||||
c.raw(1, name);
|
||||
c.raw(2, cpp);
|
||||
c.raw(3, app);
|
||||
c.int(90, flags);
|
||||
if self.version.true_color() {
|
||||
c.int(91, 0);
|
||||
}
|
||||
c.int(280, 0);
|
||||
c.int(281, i64::from(entity));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// The active viewport, zoomed to the drawing's extents.
|
||||
fn vport(&self, c: &mut Codes) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.table("VPORT", fixed::VPORT_TABLE, 1);
|
||||
c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord");
|
||||
c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" });
|
||||
c.int(70, 0);
|
||||
c.xy(10, 0.0, 0.0);
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
c.xy(13, 0.0, 0.0);
|
||||
c.xy(14, 1.0, 1.0);
|
||||
c.xy(15, 10.0, 10.0);
|
||||
// The view direction looks down the z axis: (0, 0, 1), each code once.
|
||||
c.xy(16, 0.0, 0.0);
|
||||
c.num(36, 1.0);
|
||||
c.xyz(17, 0.0, 0.0);
|
||||
let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs());
|
||||
// The view's height, with a margin; its width follows from the aspect ratio.
|
||||
c.num(40, (h.max(w / 1.5) * 1.1).max(1.0));
|
||||
c.num(41, 1.5);
|
||||
c.num(42, 50.0);
|
||||
c.num(43, 0.0);
|
||||
c.num(44, 0.0);
|
||||
c.num(50, 0.0);
|
||||
c.num(51, 0.0);
|
||||
for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] {
|
||||
c.int(code, value);
|
||||
}
|
||||
if self.version.r2000() {
|
||||
c.int(281, 0);
|
||||
c.int(65, 0);
|
||||
c.num(146, 0.0);
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn ltypes(&self, c: &mut Codes, base: u32) {
|
||||
c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len());
|
||||
let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")];
|
||||
let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice())));
|
||||
for (i, (name, desc, pattern)) in rows.enumerate() {
|
||||
c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.str(3, if pattern.is_empty() { desc } else { "Dashed" });
|
||||
c.int(72, 65);
|
||||
c.int(73, pattern.len() as i64);
|
||||
c.num(40, pattern.iter().map(|v| v.abs()).sum());
|
||||
for v in pattern {
|
||||
c.num(49, *v);
|
||||
if self.version.handles() {
|
||||
c.int(74, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn layer_table(&self, c: &mut Codes, base: u32) {
|
||||
let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true };
|
||||
c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len());
|
||||
for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() {
|
||||
c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord");
|
||||
c.str(2, &l.name);
|
||||
c.int(70, if l.locked { 4 } else { 0 });
|
||||
// A negative colour switches the layer off.
|
||||
let aci = i64::from(l.aci.max(1));
|
||||
c.int(62, if l.off { -aci } else { aci });
|
||||
c.raw(6, "Continuous");
|
||||
if self.version.r2000() {
|
||||
c.int(290, i64::from(l.plot));
|
||||
c.int(370, -3);
|
||||
c.handle(390, fixed::PLOT_NORMAL);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn style_table(&self, c: &mut Codes, base: u32) {
|
||||
c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len());
|
||||
let standard = (STANDARD_STYLE.to_string(), String::new());
|
||||
for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() {
|
||||
c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.num(40, 0.0);
|
||||
c.num(41, 1.0);
|
||||
c.num(50, 0.0);
|
||||
c.int(71, 0);
|
||||
c.num(42, 2.5);
|
||||
// The font file; from 2000 the family name too, which is how CAD apps find a TrueType font.
|
||||
if family.is_empty() {
|
||||
c.raw(3, "txt");
|
||||
} else {
|
||||
c.str(3, &format!("{family}.ttf"));
|
||||
}
|
||||
c.raw(4, "");
|
||||
if self.version.r2000() && !family.is_empty() {
|
||||
c.raw(1001, "ACAD");
|
||||
c.str(1000, family);
|
||||
c.int(1071, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn objects(&self, c: &mut Codes) {
|
||||
let v = self.version;
|
||||
let images = !self.images.is_empty();
|
||||
c.section("OBJECTS");
|
||||
let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| {
|
||||
c.object("DICTIONARY", h, owner, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
for (name, e) in entries {
|
||||
c.str(3, name);
|
||||
c.handle(350, *e);
|
||||
}
|
||||
};
|
||||
let mut root = vec![("ACAD_GROUP", fixed::GROUPS)];
|
||||
if images {
|
||||
root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]);
|
||||
}
|
||||
if v.r2000() {
|
||||
root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]);
|
||||
}
|
||||
dict(c, fixed::ROOT, Handle(0), &root);
|
||||
dict(c, fixed::GROUPS, fixed::ROOT, &[]);
|
||||
if v.r2000() {
|
||||
dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]);
|
||||
c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
c.raw(3, "Normal");
|
||||
c.handle(350, fixed::PLOT_NORMAL);
|
||||
c.raw(100, "AcDbDictionaryWithDefault");
|
||||
c.handle(340, fixed::PLOT_NORMAL);
|
||||
// A placeholder has no data and no subclass marker of its own.
|
||||
c.raw(0, "ACDBPLACEHOLDER");
|
||||
c.handle(5, fixed::PLOT_NORMAL);
|
||||
c.handle(330, fixed::PLOT_STYLES);
|
||||
self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD);
|
||||
self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD);
|
||||
}
|
||||
if images {
|
||||
c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables");
|
||||
c.int(90, 0);
|
||||
c.int(70, 0);
|
||||
c.int(71, 1);
|
||||
c.int(72, 0);
|
||||
let entries: Vec<(&str, Handle)> = self.images.iter().map(|i| (i.name.as_str(), i.handle)).collect();
|
||||
dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries);
|
||||
for img in &self.images {
|
||||
c.raw(0, "IMAGEDEF");
|
||||
c.handle(5, img.handle);
|
||||
c.raw(102, "{ACAD_REACTORS");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
for (reactor, _) in &img.reactors {
|
||||
c.handle(330, *reactor);
|
||||
}
|
||||
c.raw(102, "}");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
c.raw(100, "AcDbRasterImageDef");
|
||||
c.int(90, 0);
|
||||
c.str(1, &img.name);
|
||||
c.xy(10, f64::from(img.size.0), f64::from(img.size.1));
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
for (reactor, image) in &img.reactors {
|
||||
c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor");
|
||||
c.int(90, 2);
|
||||
c.handle(330, *image);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// A layout (DXF 2000 and later): its plot settings, then the layout itself.
|
||||
fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings");
|
||||
c.raw(1, "");
|
||||
c.raw(2, "none_device");
|
||||
c.raw(4, "");
|
||||
c.raw(6, "");
|
||||
for code in 40..=49 {
|
||||
c.num(code, 0.0);
|
||||
}
|
||||
c.num(140, 0.0);
|
||||
c.num(141, 0.0);
|
||||
c.num(142, 1.0);
|
||||
c.num(143, 1.0);
|
||||
// Plot flags; 1024 marks the model space layout.
|
||||
c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 });
|
||||
c.int(72, 1);
|
||||
c.int(73, 0);
|
||||
c.int(74, 5);
|
||||
c.raw(7, "");
|
||||
c.int(75, 16);
|
||||
if self.version.true_color() {
|
||||
// Shade plot mode (as displayed), resolution level (normal) and custom DPI.
|
||||
c.int(76, 0);
|
||||
c.int(77, 2);
|
||||
c.int(78, 300);
|
||||
}
|
||||
c.num(147, 1.0);
|
||||
// The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158.
|
||||
c.num(148, 0.0);
|
||||
c.num(149, 0.0);
|
||||
c.raw(100, "AcDbLayout");
|
||||
c.raw(1, name);
|
||||
c.int(70, 1);
|
||||
c.int(71, tab);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
c.xy(10, lx0, ly0);
|
||||
c.xy(11, lx1, ly1);
|
||||
c.xyz(12, 0.0, 0.0);
|
||||
c.xyz(14, x0, y0);
|
||||
c.xyz(15, x1, y1);
|
||||
c.num(146, 0.0);
|
||||
c.xyz(13, 0.0, 0.0);
|
||||
c.xyz(16, 1.0, 0.0);
|
||||
c.xyz(17, 0.0, 1.0);
|
||||
c.int(76, 1);
|
||||
c.handle(330, record);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_and_text_are_written_plainly() {
|
||||
assert_eq!(num(1.5), "1.5");
|
||||
assert_eq!(num(-0.0000001), "0");
|
||||
assert_eq!(num(2.0), "2");
|
||||
assert_eq!(num(f64::NAN), "0");
|
||||
assert_eq!(text("a^b\nc", true), "a^ b c");
|
||||
assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?");
|
||||
assert_eq!(text("Größe", true), "Größe");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
HEADER
|
||||
9
|
||||
$ACADVER
|
||||
1
|
||||
AC1009
|
||||
9
|
||||
$DWGCODEPAGE
|
||||
3
|
||||
ANSI_1252
|
||||
9
|
||||
$INSBASE
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMIN
|
||||
10
|
||||
10
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMAX
|
||||
10
|
||||
180
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
9
|
||||
$LIMMIN
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
9
|
||||
$LIMMAX
|
||||
10
|
||||
200
|
||||
20
|
||||
100
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
TABLES
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
VPORT
|
||||
70
|
||||
1
|
||||
0
|
||||
VPORT
|
||||
2
|
||||
*ACTIVE
|
||||
70
|
||||
0
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
11
|
||||
1
|
||||
21
|
||||
1
|
||||
12
|
||||
95
|
||||
22
|
||||
55
|
||||
13
|
||||
0
|
||||
23
|
||||
0
|
||||
14
|
||||
1
|
||||
24
|
||||
1
|
||||
15
|
||||
10
|
||||
25
|
||||
10
|
||||
16
|
||||
0
|
||||
26
|
||||
0
|
||||
36
|
||||
1
|
||||
17
|
||||
0
|
||||
27
|
||||
0
|
||||
37
|
||||
0
|
||||
40
|
||||
124.666667
|
||||
41
|
||||
1.5
|
||||
42
|
||||
50
|
||||
43
|
||||
0
|
||||
44
|
||||
0
|
||||
50
|
||||
0
|
||||
51
|
||||
0
|
||||
71
|
||||
0
|
||||
72
|
||||
1000
|
||||
73
|
||||
1
|
||||
74
|
||||
3
|
||||
75
|
||||
0
|
||||
76
|
||||
0
|
||||
77
|
||||
0
|
||||
78
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LTYPE
|
||||
70
|
||||
3
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByBlock
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByLayer
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
Continuous
|
||||
70
|
||||
0
|
||||
3
|
||||
Solid line
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LAYER
|
||||
70
|
||||
2
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
0
|
||||
70
|
||||
0
|
||||
62
|
||||
7
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
LAYER_1
|
||||
70
|
||||
0
|
||||
62
|
||||
171
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
STYLE
|
||||
70
|
||||
1
|
||||
0
|
||||
STYLE
|
||||
2
|
||||
Standard
|
||||
70
|
||||
0
|
||||
40
|
||||
0
|
||||
41
|
||||
1
|
||||
50
|
||||
0
|
||||
71
|
||||
0
|
||||
42
|
||||
2.5
|
||||
3
|
||||
txt
|
||||
4
|
||||
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
ENTITIES
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
1
|
||||
41
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
2
|
||||
41
|
||||
2
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
120
|
||||
20
|
||||
50
|
||||
30
|
||||
0
|
||||
42
|
||||
-2.414214
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
150
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
42
|
||||
-0.414214
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
EOF
|
||||
File diff suppressed because it is too large.
Load diff
+13
-12
@@ -323,34 +323,31 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option<Hi
|
||||
/// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost
|
||||
/// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind).
|
||||
pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
let walk = ArtWalk::open();
|
||||
let _walk = ArtWalk::open();
|
||||
let opt = HitOptions { scope: scope.or(opt.scope), ..opt };
|
||||
// Normally one hit test per *object* suffices: layers and sublayers aren't selectable,
|
||||
// while a group (including a clipping group) is selected as one object. Repeatedly
|
||||
// searching the full tree for each hit made a stack of n overlapping paths O(n^2).
|
||||
// Isolation and Edit Contents change where selection groups begin; keep the original
|
||||
// traversal for those cases rather than change their Select Behind semantics.
|
||||
if opt.scope.is_some() {
|
||||
// Malformed files may contain non-layer roots; let the general traversal handle them.
|
||||
if opt.scope.is_some() || doc.layers.iter().any(|l| !l.is_layer()) {
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
}
|
||||
let mut tops = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let symbols = doc.symbol_boxes();
|
||||
for layer in doc.layers.iter().rev() {
|
||||
// Malformed files may contain non-layer roots; let the general traversal handle them.
|
||||
if !layer.is_layer() {
|
||||
walk.restart();
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
}
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely, with the whole
|
||||
// limit of symbol art to walk.
|
||||
walk.restart();
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
@@ -414,7 +411,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
|
||||
/// The general selection order also handles isolation and nested Edit Contents.
|
||||
fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
let mut tops: Vec<NodeId> = vec![];
|
||||
objects_at_repeated_after(doc, p, opt, scope, vec![])
|
||||
}
|
||||
|
||||
/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found.
|
||||
fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
|
||||
// Each round leaves out the objects found so far (and everything inside them).
|
||||
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
|
||||
if tops.contains(&top) {
|
||||
|
||||
@@ -1452,6 +1452,76 @@ fn objects_at_edit_contents_uses_general_order() {
|
||||
assert_eq!(objects_at(&d, p, opt, None), vec![b, a]);
|
||||
}
|
||||
|
||||
/// Select Behind keeps one limit of symbol art to walk when it falls back to the general
|
||||
/// traversal, for an envelope in Edit Contents and for a root that is not a layer: the fallback
|
||||
/// walks no more art than what the first pass left, and keeps what the first pass found.
|
||||
#[test]
|
||||
fn select_behind_keeps_one_art_limit_when_it_falls_back() {
|
||||
// 60 instances of `Clipped` with the rectangle hidden, which a click at (150, 50) walks the art
|
||||
// of and misses: each walk takes 3 objects of the 100.
|
||||
let stack = |d: &mut Document, count: usize| {
|
||||
let l = d.layers[0].id;
|
||||
for _ in 0..count {
|
||||
let inst = instance_of(d, "Clipped");
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
};
|
||||
// An envelope in Edit Contents at the bottom of the layer, its contents under (150, 50).
|
||||
let envelope = |d: &mut Document| {
|
||||
let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
|
||||
let (a, b) = (d.alloc_id(), d.alloc_id());
|
||||
let e = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Envelope {
|
||||
content: vec![inner(a), inner(b)],
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }),
|
||||
fidelity: 100.0,
|
||||
editing: true,
|
||||
options: Default::default(),
|
||||
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
|
||||
},
|
||||
);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, e).unwrap();
|
||||
(a, b)
|
||||
};
|
||||
let p = Point::new(150.0, 50.0);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
let (a, b) = envelope(&mut d);
|
||||
stack(&mut d, 60);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert_eq!(behind, vec![b, a]);
|
||||
assert!(arts <= 34, "envelope in Edit Contents: {arts} instances' art walked");
|
||||
// An instance that the first pass hits by its art, the limit then used up, stays in the list:
|
||||
// `Shown` is `Clipped` with its rectangle shown, below 32 instances of `Clipped`.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
let (a, b) = envelope(&mut d);
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Shown", vec![Arc::new(clip)]);
|
||||
let hit = instance_of(&mut d, "Shown");
|
||||
let hit_id = hit.id;
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
|
||||
stack(&mut d, 32);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert_eq!(behind, vec![hit_id, b, a], "hit before the fallback");
|
||||
assert!(arts <= 34, "hit before the fallback: {arts} instances' art walked");
|
||||
// A root that is not a layer, below the layer.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
stack(&mut d, 60);
|
||||
let root = Arc::new(Node::group(d.alloc_id(), vec![]));
|
||||
d.layers.insert(0, root);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert!(behind.is_empty());
|
||||
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
|
||||
@@ -16,6 +16,11 @@ pub trait ColorVisitor {
|
||||
fn color(&mut self, c: Color) -> Color;
|
||||
/// The key of embedded image `key` recoloured, `None` when it stays as it is.
|
||||
fn image(&mut self, key: &str) -> Option<String>;
|
||||
/// Whether the pass recolors child `n` of a container: false leaves `n` and everything inside
|
||||
/// it as they are.
|
||||
fn enters(&mut self, _n: &Node) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// What a recolouring pass reaches: fills (including colorized image fills and gradient-mesh
|
||||
@@ -82,6 +87,9 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi
|
||||
}
|
||||
_ => {
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if !v.enters(c) {
|
||||
continue;
|
||||
}
|
||||
let mut m = (**c).clone();
|
||||
let k = recolor_node(&mut m, reach, v);
|
||||
if k > 0 {
|
||||
|
||||
@@ -48,8 +48,10 @@ pub struct CharStyle {
|
||||
/// of the character's ink, inside its own width, that is taken away, 0 to [`MAX_TSUME`]. 50
|
||||
/// halves that space and 100 sets the ink edge to edge; the glyph itself is not scaled. A
|
||||
/// cluster takes the value of its first character. Tracking, kerning and Insert Aki are added
|
||||
/// after it. Horizontal type only.
|
||||
/// after it. In vertical type an upright character is measured above and below its ink, inside
|
||||
/// its cell down the column.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
/// <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html>
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub tsume: f64,
|
||||
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
|
||||
|
||||
@@ -117,6 +117,11 @@ thread_local! {
|
||||
/// The objects of symbol art that [`bake_document`] has baked for instances inside the art of
|
||||
/// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`].
|
||||
static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// The objects in the baked art of the instances inside the art of other instances that
|
||||
/// [`bake_node`] baked for one export and then left as they are, counted with
|
||||
/// [`NESTED_NODES`] against [`crate::SYMBOL_ART_MAX_NODES`] before more art is baked. Never
|
||||
/// given back.
|
||||
static NESTED_DROPPED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// While [`bake_document_placing_symbols`] bakes: the symbols whose instances become their
|
||||
/// placed art ([`placed_symbol_art`]).
|
||||
static PLACING: std::cell::RefCell<Option<Rc<Placing>>> = const { std::cell::RefCell::new(None) };
|
||||
@@ -369,17 +374,29 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
};
|
||||
// Instances baked inside the art of others stop at the depth limit, or once their art
|
||||
// passes the objects one export bakes that way: an instance of a symbol whose art holds
|
||||
// instances of itself is kept as it is there.
|
||||
// instances of itself is kept as it is there. The symbol's art is held in the count while
|
||||
// it bakes, so the instances inside it bake only within what is left; the art it bakes to,
|
||||
// with what its effects add, then takes its place in the count. When that art does not
|
||||
// fit, the instance stays as it is, and the art baked for it, with the art dropped for the
|
||||
// instances inside it, still counts against the instances after it.
|
||||
let instance = matches!(n.kind, NodeKind::SymbolInstance { .. });
|
||||
if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 {
|
||||
let nested = instance && INSTANCE_DEPTH.with(|c| c.get()) > 0;
|
||||
let before = NESTED_NODES.with(|c| c.get());
|
||||
if nested {
|
||||
let count = symbol.as_ref().map_or(0, |a| a.count() as u64);
|
||||
let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count);
|
||||
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES {
|
||||
let spent = before.saturating_add(count);
|
||||
let dropped = NESTED_DROPPED.with(|c| c.get());
|
||||
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent.saturating_add(dropped) > crate::SYMBOL_ART_MAX_NODES {
|
||||
return None;
|
||||
}
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
}
|
||||
let m = reshape(Some(d), n, symbol.as_ref())?;
|
||||
let Some(m) = reshape(Some(d), n, symbol.as_ref()) else {
|
||||
if nested {
|
||||
NESTED_NODES.with(|c| c.set(before));
|
||||
}
|
||||
return None;
|
||||
};
|
||||
if instance {
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() + 1));
|
||||
}
|
||||
@@ -387,7 +404,17 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
if instance {
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() - 1));
|
||||
}
|
||||
return Some(baked.unwrap_or(m));
|
||||
let baked = baked.unwrap_or(m);
|
||||
if nested {
|
||||
let spent = before.saturating_add(baked.count() as u64);
|
||||
if spent.saturating_add(NESTED_DROPPED.with(|c| c.get())) > crate::SYMBOL_ART_MAX_NODES {
|
||||
NESTED_NODES.with(|c| c.set(before));
|
||||
NESTED_DROPPED.with(|c| c.set(c.get().saturating_add(baked.count() as u64)));
|
||||
return None;
|
||||
}
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
}
|
||||
return Some(baked);
|
||||
}
|
||||
// Symbol instances whose art draws live effects, when the caller asks for them: the art
|
||||
// placed, then baked. When the baked art passes the export's budget, or would draw too deep
|
||||
@@ -1068,6 +1095,7 @@ fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option<D
|
||||
}
|
||||
let mut d = placed.into_owned();
|
||||
NESTED_NODES.with(|c| c.set(0));
|
||||
NESTED_DROPPED.with(|c| c.set(0));
|
||||
let layers = d.layers.clone();
|
||||
d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect();
|
||||
Some(d)
|
||||
|
||||
@@ -1525,3 +1525,125 @@ fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() {
|
||||
let room = bake(&d, Some((true, a + e + f, ALL))).unwrap();
|
||||
assert!(!is_instance(&room, 900) && !is_instance(&room, 901));
|
||||
}
|
||||
|
||||
/// Instance `id` of `symbol` with a geometry effect, so baking it reshapes its art.
|
||||
fn offset_instance(id: u64, symbol: &str) -> Node {
|
||||
let mut n = instance(id, symbol, vectorcraft_geom::Affine::IDENTITY);
|
||||
n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1.0})));
|
||||
n
|
||||
}
|
||||
|
||||
/// `n` baked as an instance inside another instance's art, with `spent` objects of nested symbol
|
||||
/// art already baked: the baked object, and the objects counted after it, art baked and dropped
|
||||
/// included.
|
||||
fn bake_nested(d: &mut Document, n: &Node, spent: u64) -> (Option<Node>, u64) {
|
||||
INSTANCE_DEPTH.with(|c| c.set(1));
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
NESTED_DROPPED.with(|c| c.set(0));
|
||||
let out = bake_node(d, n);
|
||||
INSTANCE_DEPTH.with(|c| c.set(0));
|
||||
(out, NESTED_NODES.with(|c| c.replace(0)).saturating_add(NESTED_DROPPED.with(|c| c.replace(0))))
|
||||
}
|
||||
|
||||
/// The object with id `id` in `n`'s subtree.
|
||||
fn find(n: &Node, id: u64) -> Option<&Node> {
|
||||
if n.id == NodeId(id) {
|
||||
return Some(n);
|
||||
}
|
||||
n.children().into_iter().flatten().find_map(|c| find(c, id))
|
||||
}
|
||||
|
||||
/// Is `n` an object other than a symbol instance?
|
||||
fn baked(n: Option<&Node>) -> bool {
|
||||
n.is_some_and(|n| !matches!(n.kind, NodeKind::SymbolInstance { .. }))
|
||||
}
|
||||
|
||||
/// An instance baked inside another instance's art counts the art it bakes to, the copies its
|
||||
/// symbol's effects make included: art that fits exactly takes the last of the budget, and art
|
||||
/// whose symbol fits but whose baked art does not leaves the instance as it is and still counts.
|
||||
#[test]
|
||||
fn nested_reshape_counts_baked_art() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Inner", gradient_copies(800));
|
||||
let n = offset_instance(900, "Inner");
|
||||
let source = d.symbols[0].art.count() as u64;
|
||||
let (all, spent) = bake_nested(&mut d, &n, 0);
|
||||
let baked = all.map_or(0, |m| m.count() as u64);
|
||||
assert!(baked > source + 1, "the copies are objects of their own: {baked} > {source} + 1");
|
||||
assert_eq!(spent, baked, "the baked art is counted in place of the symbol's art");
|
||||
let max = crate::SYMBOL_ART_MAX_NODES;
|
||||
let (exact, spent) = bake_nested(&mut d, &n, max - baked);
|
||||
assert!(exact.is_some(), "{baked} objects fit in {baked}");
|
||||
assert_eq!(spent, max);
|
||||
let (short, spent) = bake_nested(&mut d, &n, max - baked + 1);
|
||||
assert!(short.is_none(), "the symbol's {source} objects fit, the {baked} baked ones do not");
|
||||
assert_eq!(spent, max + 1, "the art baked for the instance left as it is still counts");
|
||||
}
|
||||
|
||||
/// An instance left as it is because its baked art does not fit still counts the art baked for
|
||||
/// it: an instance after it is left as it is too, before its art bakes.
|
||||
#[test]
|
||||
fn nested_reshape_refusal_keeps_its_work_counted() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Big", gradient_copies(800));
|
||||
add_symbol(&mut d, "Small", moved_square(810));
|
||||
let (big, small) = (offset_instance(900, "Big"), offset_instance(901, "Small"));
|
||||
let count = |d: &mut Document, n: &Node| bake_nested(d, n, 0).0.map_or(0, |m| m.count() as u64);
|
||||
let (b, s) = (count(&mut d, &big), count(&mut d, &small));
|
||||
assert!(s < b, "{s} < {b}");
|
||||
let first = crate::SYMBOL_ART_MAX_NODES - b + 1;
|
||||
let (refused, spent) = bake_nested(&mut d, &big, first);
|
||||
assert!(refused.is_none(), "the big art passes the budget");
|
||||
assert_eq!(spent, first + b, "the big art baked and dropped counts");
|
||||
let (later, after) = bake_nested(&mut d, &small, spent);
|
||||
assert!(later.is_none(), "the small art does not fit after the dropped art");
|
||||
assert_eq!(after, spent, "the small instance is refused before it bakes");
|
||||
}
|
||||
|
||||
/// Sibling instances inside other instances' art whose baked art each passes what is left: the
|
||||
/// first is baked and dropped, and its art counts, so the others are left as they are before
|
||||
/// their art bakes. With room for all of them, every one is baked.
|
||||
#[test]
|
||||
fn nested_reshape_refused_siblings_bake_once() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Big", gradient_copies(800));
|
||||
let one = offset_instance(900, "Big");
|
||||
let b = bake_nested(&mut d, &one, 0).0.map_or(0, |m| m.count() as u64);
|
||||
let siblings: Vec<Arc<Node>> = (0..16).map(|i| Arc::new(offset_instance(1000 + i, "Big"))).collect();
|
||||
let group = Node::group(NodeId(999), siblings);
|
||||
let first = crate::SYMBOL_ART_MAX_NODES - b + 1;
|
||||
let (refused, spent) = bake_nested(&mut d, &group, first);
|
||||
let refused = refused.unwrap_or_else(|| group.clone());
|
||||
assert!((0..16).all(|i| !baked(find(&refused, 1000 + i))), "no sibling fits: {refused:?}");
|
||||
assert_eq!(spent, first + b, "only the first sibling's art is baked and counted: {spent}");
|
||||
let (room, spent) = bake_nested(&mut d, &group, 0);
|
||||
let room = room.unwrap_or_else(|| panic!("the siblings are baked"));
|
||||
assert!((0..16).all(|i| baked(find(&room, 1000 + i))), "every sibling is baked");
|
||||
assert_eq!(spent, 16 * b);
|
||||
}
|
||||
|
||||
/// An instance inside another instance's art whose own art holds a reshaped instance counts that
|
||||
/// instance's baked art once: a budget of exactly the outer art's baked objects bakes both, and
|
||||
/// with one object less the art baked and dropped still counts.
|
||||
#[test]
|
||||
fn nested_reshape_counts_successful_descendants_once() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Inner", gradient_copies(800));
|
||||
let square = Node::path(NodeId(803), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(offset_instance(802, "Inner")), Arc::new(square)]));
|
||||
let outer = offset_instance(900, "Outer");
|
||||
let (all, spent) = bake_nested(&mut d, &outer, 0);
|
||||
let all = all.unwrap_or_else(|| panic!("the outer instance is baked"));
|
||||
assert!(baked(find(&all, 802)), "the inner instance is baked: {all:?}");
|
||||
let total = all.count() as u64;
|
||||
assert_eq!(spent, total);
|
||||
let max = crate::SYMBOL_ART_MAX_NODES;
|
||||
let (exact, spent) = bake_nested(&mut d, &outer, max - total);
|
||||
let exact = exact.unwrap_or_else(|| panic!("{total} objects fit in {total}"));
|
||||
assert!(baked(find(&exact, 802)), "the inner instance is baked too");
|
||||
assert_eq!(spent, max);
|
||||
let (short, spent) = bake_nested(&mut d, &outer, max - total + 1);
|
||||
assert!(short.as_ref().is_none_or(|m| !baked(find(m, 802))), "with one object less, not both are baked");
|
||||
assert!(spent > max, "the art baked and dropped counts: {spent}");
|
||||
assert!(spent <= max - total + 1 + 2 * total, "at most the outer and the inner art are dropped: {spent}");
|
||||
}
|
||||
@@ -321,6 +321,22 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option<Paint>) {
|
||||
(base, transparent.then_some(mask))
|
||||
}
|
||||
|
||||
/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient
|
||||
/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the
|
||||
/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement.
|
||||
/// An opaque gradient is returned as [`opaque_paint`] returns it.
|
||||
pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option<Paint>) {
|
||||
let (base, mask) = opaque_paint(paint);
|
||||
if mask.is_none() || !matches!(paint, Paint::Gradient(_)) {
|
||||
return (base, mask);
|
||||
}
|
||||
let mut pinned = paint.clone();
|
||||
if let Paint::Gradient(g) = &mut pinned {
|
||||
g.pin(bounds().inflate(1.0, 1.0));
|
||||
}
|
||||
opaque_paint(&pinned)
|
||||
}
|
||||
|
||||
fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
|
||||
@@ -631,7 +631,9 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
/// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid
|
||||
/// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless
|
||||
/// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order
|
||||
/// with the faces of other solids.
|
||||
/// with the faces of other solids. Under colored lights a gradient with transparent stops is drawn
|
||||
/// opaque under one mask of its transparency, placed once on all the facets when it has no
|
||||
/// placement of its own ([`crate::lighting::opaque_surface_paint`]).
|
||||
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node {
|
||||
if !faces && composites_facets(&facets, paint, colored) {
|
||||
let mut group = crate::lighting::solid_surface(n.id, &facets, paint);
|
||||
@@ -640,7 +642,7 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
|
||||
return group;
|
||||
}
|
||||
// Preserve existing white-light paints and alpha composition exactly.
|
||||
let (opaque, mask) = if colored { crate::lighting::opaque_paint(paint) } else { (paint.clone(), None) };
|
||||
let (opaque, mask) = if colored { crate::lighting::opaque_surface_paint(paint, || facets_bounds(&facets)) } else { (paint.clone(), None) };
|
||||
let paint = &opaque;
|
||||
let children = facets
|
||||
.into_iter()
|
||||
@@ -677,6 +679,11 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
|
||||
group
|
||||
}
|
||||
|
||||
/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any).
|
||||
pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect {
|
||||
facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO)
|
||||
}
|
||||
|
||||
/// The width of the stroke of a facet's own paint that closes the seams between `face` and its
|
||||
/// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than
|
||||
/// the stroke, and its stroke would then paint over its neighbors.
|
||||
|
||||
@@ -245,7 +245,8 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
|
||||
/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`]
|
||||
/// draws it). A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its own transparency, so the shading follows the gradient's coverage.
|
||||
/// its own transparency, so the shading follows the gradient's coverage; without a placement of its
|
||||
/// own, it is placed once on all the faces ([`crate::lighting::opaque_surface_paint`]).
|
||||
///
|
||||
/// With `mapped`, a face that carries mapped art is a group of the face and that art, which the
|
||||
/// surface's opacity mask covers too. Shade Artwork gives the art its face's tone and highlight,
|
||||
@@ -268,7 +269,7 @@ pub(crate) fn surface(
|
||||
let shade = shading_color(p);
|
||||
let preserve = preserves_spot_colors(p);
|
||||
let wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) };
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) };
|
||||
let paint = &paint;
|
||||
// The mapped art of each facet, and whether the faces themselves are left out. Art past the
|
||||
// limits is left out, and the faces draw.
|
||||
|
||||
@@ -1961,6 +1961,57 @@ fn classic_shading_keeps_a_gradients_transparency() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient without a placement and with a transparent stop, under colored lights or classic
|
||||
/// shading, is placed once for the whole surface: every face's color and the surface's opacity mask
|
||||
/// share one placement, so the color and transparency ramps line up across the faces. A gradient
|
||||
/// placed in the document keeps its placement.
|
||||
#[test]
|
||||
fn a_transparent_unplaced_gradient_has_one_placement_for_color_and_mask() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
// The source's stops carry an unusual midpoint, so its color and mask copies can be told from
|
||||
// the light ramps.
|
||||
const MARK: f32 = 0.37;
|
||||
let mut first = GradientStop::new(0.0, RED);
|
||||
first.midpoint = MARK;
|
||||
let mut end = GradientStop::new(1.0, Color::BLACK);
|
||||
end.opacity = 0.25;
|
||||
let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![first, end]));
|
||||
let placed = GradientGeom { start: Point::new(90.0, 100.0), end: Point::new(230.0, 140.0), aspect: 1.0, focal: None };
|
||||
// The placement of each copy of the source gradient: its own, else its fit on the path it fills.
|
||||
fn placements(n: &Node, out: &mut Vec<GradientGeom>) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(mask) = &c.extras().mask {
|
||||
placements(&mask.art, out);
|
||||
}
|
||||
let bounds = c.path_data().and_then(|p| p.bounds()).unwrap_or(Rect::ZERO);
|
||||
for item in &c.appearance.items {
|
||||
if let Paint::Gradient(g) = paint_ref(item)
|
||||
&& g.gradient.stops.first().is_some_and(|s| s.midpoint == MARK)
|
||||
{
|
||||
out.push(g.resolve(bounds));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let lit = json!({"lights": [{"color": "#ff8080"}]});
|
||||
for (id, params) in [(EXTRUDE, lit.clone()), (INFLATE, lit.clone()), (ROTATE, lit), (CLASSIC_EXTRUDE, json!({}))] {
|
||||
for geom in [None, Some(placed)] {
|
||||
let mut n = square_node();
|
||||
n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }))))];
|
||||
n.appearance.effects.push(fx(id, params.clone()));
|
||||
let art = solid_art(&n).unwrap_or_else(|| panic!("{id}"));
|
||||
let mut masks = 0;
|
||||
art.walk(&mut |c| masks += usize::from(c.extras().mask.is_some()));
|
||||
assert!(masks > 0, "{id}: the surface carries the gradient's transparency as a mask");
|
||||
let mut found = vec![];
|
||||
placements(&art, &mut found);
|
||||
assert!(found.len() > 2, "{id}: the faces' colors and the mask");
|
||||
let expected = geom.unwrap_or(found[0]);
|
||||
assert!(found.iter().all(|g| *g == expected), "{id} {geom:?}: {found:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group member in a gradient with transparent stops keeps the shared back-to-front order of
|
||||
/// every member's faces: its faces go in runs that carry its opacity mask, and the other member's
|
||||
/// faces are drawn between them where they are in front of some and behind others. Here a square
|
||||
|
||||
@@ -53,7 +53,7 @@ heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], op
|
||||
flate2 = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# The XML parts of Word documents placed as type (place/docx.rs).
|
||||
roxmltree = "0.21"
|
||||
craft-xml = { workspace = true }
|
||||
# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs).
|
||||
cfb = "0.15"
|
||||
kurbo = { workspace = true }
|
||||
|
||||
@@ -98,6 +98,8 @@ pub(crate) mod symboledit;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
mod textedit;
|
||||
mod xmlattrs;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
|
||||
@@ -446,7 +446,7 @@ pub(crate) fn rows_per_target(d: &Document, of: Option<NodeId>, ids: &[NodeId],
|
||||
}
|
||||
|
||||
/// Whether the `target` param asks for the contents of groups and layers (see the module docs).
|
||||
fn targets_contents(p: &Value) -> Result<bool> {
|
||||
pub(crate) fn targets_contents(p: &Value) -> Result<bool> {
|
||||
match p.get("target") {
|
||||
None | Some(Value::Null) => Ok(false),
|
||||
Some(v) => match v.as_str() {
|
||||
@@ -508,6 +508,20 @@ pub(crate) fn drop_design_art(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId>
|
||||
ids
|
||||
}
|
||||
|
||||
/// [`drop_design_art`] for an edit of the `item` rows of `ids` (`fill`: fill rows): an explicit `item` that a design's
|
||||
/// art has no row of that kind for is still an error of `cmd`, as on any other object.
|
||||
pub(crate) fn drop_design_art_rows(s: &Session, ids: Vec<NodeId>, item: ItemTarget, fill: bool, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
for (id, it) in ids.iter().zip(item.per_target(s, &ids)) {
|
||||
if let (Some(it), Some(n)) = (it, d.node(*id))
|
||||
&& super::graph::is_design_art(d, *id)
|
||||
{
|
||||
it.resolve(&n.appearance, fill, cmd)?;
|
||||
}
|
||||
}
|
||||
Ok(drop_design_art(d, ids))
|
||||
}
|
||||
|
||||
/// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that
|
||||
/// [`super::graph::is_design_art`] accepts.
|
||||
pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
@@ -720,7 +734,10 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
|
||||
let holder = match reference_of(s, p, item, cmd)? {
|
||||
Some(of) => Some(of),
|
||||
None => {
|
||||
let ids = drop_design_art(d, appearance_targets(s, p)?);
|
||||
let all = appearance_targets(s, p)?;
|
||||
// The art of a graph design is left out, unless it is all there is: the item is then a row of that art.
|
||||
let kept = drop_design_art(d, all.clone());
|
||||
let ids = if kept.is_empty() { all } else { kept };
|
||||
ids.get(item.anchor(s, &ids)).copied()
|
||||
}
|
||||
};
|
||||
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
|
||||
@@ -1043,10 +1043,13 @@ impl Imported {
|
||||
self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone());
|
||||
}
|
||||
}
|
||||
/// Point a pasted copy at the document's resources.
|
||||
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
|
||||
/// other darkness take the contrast a redraw sets there.
|
||||
pub(crate) fn apply(&self, n: &mut Node) {
|
||||
if self.relinks {
|
||||
let shades = super::super::graph::wedge_shades(n);
|
||||
self.relink.node(n);
|
||||
super::super::graph::follow_wedge_shades(n, &shades);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +221,8 @@ pub(crate) struct Recolor<'a> {
|
||||
patterns: HashMap<String, Option<String>>,
|
||||
new_images: Vec<(String, ImageBlob)>,
|
||||
new_patterns: Vec<PatternDef>,
|
||||
/// Objects inside the recolored ones that keep their colors, with everything inside them.
|
||||
skip: HashSet<NodeId>,
|
||||
changed: usize,
|
||||
}
|
||||
|
||||
@@ -236,6 +238,7 @@ impl<'a> Recolor<'a> {
|
||||
patterns: HashMap::new(),
|
||||
new_images: vec![],
|
||||
new_patterns: vec![],
|
||||
skip: HashSet::new(),
|
||||
changed: 0,
|
||||
}
|
||||
}
|
||||
@@ -254,7 +257,7 @@ impl<'a> Recolor<'a> {
|
||||
|
||||
/// A pass that maps colors as this one does, with nothing recolored yet.
|
||||
fn again(&self) -> Self {
|
||||
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) }
|
||||
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, skip: self.skip.clone(), ..Self::new(self.scope, self.f) }
|
||||
}
|
||||
|
||||
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
|
||||
@@ -440,12 +443,20 @@ impl ColorVisitor for Visit<'_, '_> {
|
||||
fn image(&mut self, key: &str) -> Option<String> {
|
||||
self.pass.image(self.d, key)
|
||||
}
|
||||
fn enters(&mut self, n: &Node) -> bool {
|
||||
!self.pass.skip.contains(&n.id)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f))
|
||||
}
|
||||
|
||||
/// [`recolor`] that leaves the objects `skip` inside the recolored ones, and everything inside them, as they are.
|
||||
pub(crate) fn recolor_except(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, skip: HashSet<NodeId>) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor { skip, ..Recolor::new(Scope::of(p, cmd)?, f) })
|
||||
}
|
||||
|
||||
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
|
||||
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) })
|
||||
|
||||
@@ -117,11 +117,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
|
||||
// eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a
|
||||
// loop shorter than the reach is not all corners, while a square's or a triangle's corners still are.
|
||||
let mut spans = [reach, 2.0 * reach];
|
||||
// The lengths along the path ahead and back, measured once when an anchor needs them.
|
||||
let (mut ahead, mut back) = (None, None);
|
||||
if closed {
|
||||
let mut total = 0.0;
|
||||
for i in 0..n {
|
||||
total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1;
|
||||
}
|
||||
let total = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)).first().map_or(0.0, |lens| lens.iter().take(n).sum());
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
return corners;
|
||||
}
|
||||
@@ -137,8 +136,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
|
||||
if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) {
|
||||
continue;
|
||||
}
|
||||
let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue };
|
||||
let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue };
|
||||
let back = back.get_or_insert_with(|| walk_blocks(anchors, closed, false, reach));
|
||||
let [Some(back_near), Some(back_far)] = spans.map(|r| point_along(anchors, closed, (i, false), r, back, reach)) else { continue };
|
||||
let ahead = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach));
|
||||
let [Some(ahead_near), Some(ahead_far)] = spans.map(|r| point_along(anchors, closed, (i, true), r, ahead, reach)) else { continue };
|
||||
*flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])]
|
||||
.into_iter()
|
||||
.all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG));
|
||||
@@ -146,9 +147,54 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
|
||||
corners
|
||||
}
|
||||
|
||||
/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each
|
||||
/// anchor on a path of very many very short segments.
|
||||
const MAX_CORNER_WALK: usize = 256;
|
||||
/// The lengths [`walk`] measures along the segments of `anchors`, in the order a walk ahead
|
||||
/// (`forward`) or back passes them, twice round, starting at the first anchor ahead or the last
|
||||
/// anchor back, and added up in blocks: element `l` holds the lengths of each run of 2^`l`
|
||||
/// segments that starts at a multiple of 2^`l`. Each block adds up only its own segments, so a short
|
||||
/// stretch keeps its length next to very long ones. The segment past an open path's end has no
|
||||
/// length.
|
||||
fn walk_blocks(anchors: &[Anchor], closed: bool, forward: bool, reach: f64) -> Vec<Vec<f64>> {
|
||||
let n = anchors.len();
|
||||
let lens: Vec<f64> =
|
||||
(0..n).map(|k| walk(anchors, closed, (if forward { k } else { n - 1 - k }, forward), [f64::INFINITY; 2], reach, 1).1).collect();
|
||||
let mut blocks = vec![(0..2 * n).map(|k| lens[k % n]).collect::<Vec<f64>>()];
|
||||
while let Some(last) = blocks.last().filter(|b| b.len() > 1) {
|
||||
let next = last.as_chunks::<2>().0.iter().map(|[a, b]| a + b).collect();
|
||||
blocks.push(next);
|
||||
}
|
||||
blocks
|
||||
}
|
||||
|
||||
/// The point `dist` along the path `anchors` from anchor `from.0`, ahead when `from.1` and back
|
||||
/// otherwise, as [`walk`] finds it: an open path's end for a distance beyond the end, and `None`
|
||||
/// when a length is not a number or is too large to add. The walk skips whole blocks of `blocks`
|
||||
/// ([`walk_blocks`] in the same direction) that end no more than `dist` along the path, so a path of
|
||||
/// very many short segments is not walked one segment at a time from each anchor.
|
||||
fn point_along(anchors: &[Anchor], closed: bool, from: (usize, bool), dist: f64, blocks: &[Vec<f64>], reach: f64) -> Option<Point> {
|
||||
let (n, (i, forward)) = (anchors.len(), from);
|
||||
let start = if forward { i } else { n - 1 - i };
|
||||
let end = start
|
||||
+ if closed {
|
||||
n
|
||||
} else if forward {
|
||||
n - 1 - i
|
||||
} else {
|
||||
i
|
||||
};
|
||||
let (mut pos, mut gone) = (start, 0.0);
|
||||
// The largest block that starts at `pos`, stays within the walk and ends within `dist`, until
|
||||
// none does; a block whose length is not a number is never skipped.
|
||||
while let Some((size, len)) = blocks.iter().enumerate().rev().find_map(|(l, lens)| {
|
||||
let size = 1usize << l;
|
||||
let len = lens.get(pos >> l).copied()?;
|
||||
(pos % size == 0 && pos + size <= end && gone + len <= dist).then_some((size, len))
|
||||
}) {
|
||||
pos += size;
|
||||
gone += len;
|
||||
}
|
||||
let at = if forward { pos % n } else { n - 1 - pos % n };
|
||||
walk(anchors, closed, (at, forward), [(dist - gone).max(0.0); 2], reach, n).0[0]
|
||||
}
|
||||
|
||||
/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise,
|
||||
/// past no more than `segments` segments, measured along the lines between each curved segment's
|
||||
@@ -1099,11 +1145,12 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach
|
||||
/// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments
|
||||
/// than it measures before it gets that far, its top is not one, as the path turns by about 51°
|
||||
/// over that reach.
|
||||
/// of 10 pt, and of 300 pt, where twice the reach passes the bump's 566 segments on each side, its
|
||||
/// top is a corner, and with a reach of 1,000 pt its top is not one, as the path turns by about 51°
|
||||
/// over that reach. The turns into and between 1 pt segments that follow two segments 1e16 pt long
|
||||
/// are corners too.
|
||||
#[test]
|
||||
fn a_corner_is_not_kept_where_the_reach_is_not_measured() {
|
||||
fn a_bump_of_many_short_segments_is_a_corner_where_it_turns_over_the_reach() {
|
||||
let side = 400.0 * std::f64::consts::SQRT_2;
|
||||
let steps = side.ceil() as usize;
|
||||
let mut pts = vec![(-3000.0, 0.0)];
|
||||
@@ -1120,6 +1167,10 @@ mod tests {
|
||||
let top = steps + 1;
|
||||
assert_eq!(anchors[top].p, Point::new(0.0, 400.0));
|
||||
assert!(smooth_corners(&anchors, false, 10.0)[top]);
|
||||
assert!(smooth_corners(&anchors, false, 300.0)[top]);
|
||||
let long = polyline(&[(0.0, 0.0), (1e16, 0.0), (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 2.0)]);
|
||||
let corners = smooth_corners(&long, false, 0.5);
|
||||
assert!(corners[2] && corners[3] && corners[4], "{corners:?}");
|
||||
assert!(!smooth_corners(&anchors, false, 1000.0)[top]);
|
||||
}
|
||||
|
||||
|
||||
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Offset)
|
||||
),
|
||||
|
||||
@@ -978,15 +978,18 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
|
||||
/// id): those made from its own fills and strokes, or with `all` every member. The other members
|
||||
/// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are
|
||||
/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a
|
||||
/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they
|
||||
/// have before that. Returns what each of those other members' expansions lists, by the member's
|
||||
/// new id.
|
||||
/// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids
|
||||
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
m: &mut Node,
|
||||
all: bool,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
let id = m.id;
|
||||
@@ -1002,9 +1005,23 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes));
|
||||
listed = Some(expand_in_place(d, c, brushes, skip));
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
c.walk(&mut |n| was.push(n.id));
|
||||
}
|
||||
fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default());
|
||||
if !was.is_empty() {
|
||||
// A copy of an object `skip` lists is left as it is too.
|
||||
let mut at = 0;
|
||||
c.walk(&mut |n| {
|
||||
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
|
||||
kept.push(n.id);
|
||||
}
|
||||
at += 1;
|
||||
});
|
||||
}
|
||||
if let Some(listed) = listed {
|
||||
expanded.insert(c.id, listed);
|
||||
}
|
||||
@@ -1058,9 +1075,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
type Listed = (NodeId, usize);
|
||||
|
||||
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec<Listed> {
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
|
||||
let mut listed = vec![];
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) {
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
|
||||
*c = e;
|
||||
}
|
||||
listed
|
||||
@@ -1084,9 +1101,16 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
|
||||
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
|
||||
/// transparency.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
|
||||
expand_node_except(d, id, brushes, &[], out);
|
||||
}
|
||||
|
||||
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
|
||||
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
|
||||
/// copies of it that such an effect makes are left as they are too.
|
||||
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
|
||||
let Some(n) = d.node(id).cloned() else { return };
|
||||
let mut listed = vec![];
|
||||
let m = expanded_node(d, n, brushes, &mut listed);
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed);
|
||||
out.extend(listed.into_iter().map(|(id, _)| id));
|
||||
if let Some(mut m) = m {
|
||||
// Art made from type takes its emoji's pixels into the document.
|
||||
@@ -1099,10 +1123,10 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b
|
||||
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does.
|
||||
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<Listed>) -> Option<Node> {
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
|
||||
let id = n.id;
|
||||
if !expandable(&n) {
|
||||
if skip.contains(&id) || !expandable(&n) {
|
||||
return None;
|
||||
}
|
||||
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
|
||||
@@ -1139,7 +1163,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
expanded = expand_in_place(d, c, brushes);
|
||||
expanded = expand_in_place(d, c, brushes, skip);
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1169,6 +1193,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
|
||||
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
|
||||
let mut members = std::collections::HashMap::new();
|
||||
// New ids of the copies of objects `skip` lists among those members.
|
||||
let mut kept = vec![];
|
||||
let expanded = match image {
|
||||
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
|
||||
// keeps it as its only member).
|
||||
@@ -1180,7 +1206,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art);
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
|
||||
m
|
||||
})
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
@@ -1201,7 +1227,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget);
|
||||
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
|
||||
m
|
||||
})
|
||||
};
|
||||
@@ -1223,6 +1249,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
}
|
||||
if container {
|
||||
let skip = if kept.is_empty() { std::borrow::Cow::Borrowed(skip) } else { std::borrow::Cow::Owned([skip, &kept].concat()) };
|
||||
// The place of each member in the walk of `n`: after `n` and the members before it.
|
||||
let mut at = 1;
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
@@ -1235,7 +1262,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
match members.remove(&c.id) {
|
||||
Some(listed) => out.extend(listed),
|
||||
None => {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
|
||||
*c = Arc::new(e);
|
||||
changed = true;
|
||||
}
|
||||
@@ -1280,9 +1307,20 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// geometry it hasn't changed.
|
||||
if vectorcraft_plugins::safe_mode::active() {
|
||||
// A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a
|
||||
// series.
|
||||
// series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it
|
||||
// with that group: an effect of the group's own, or a raster effect of one of its fills or strokes (the group
|
||||
// then becomes an image of all of it).
|
||||
let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots);
|
||||
let designs = super::appearance::design_art_in(&d, &roots);
|
||||
let draws_members = |g: &Node| g.appearance.effects.iter().any(|e| e.visible) || !rasterfx::raster_fx(g).is_empty();
|
||||
let designs: Vec<NodeId> = super::appearance::design_art_in(&d, &roots)
|
||||
.into_iter()
|
||||
.filter(|art| {
|
||||
!d.ancestry(*art).is_some_and(|up| {
|
||||
let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len());
|
||||
up.get(from..up.len().saturating_sub(1)).is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(draws_members))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !designs.is_empty() {
|
||||
let view = d.to_mut();
|
||||
for id in designs {
|
||||
@@ -1313,16 +1351,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = vec![];
|
||||
let threaded = super::threads::frames(d);
|
||||
for id in &roots {
|
||||
expand_node(d, *id, &brushes, &mut out);
|
||||
}
|
||||
for id in &designs {
|
||||
if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) {
|
||||
*slot = was.clone();
|
||||
}
|
||||
}
|
||||
if !designs.is_empty() {
|
||||
// A mark that expands into a group stays listed: only what lies in the restored art is left out.
|
||||
out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a))));
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out);
|
||||
}
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was replaced stays where it was, no longer linked.
|
||||
|
||||
@@ -149,7 +149,9 @@ pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
|
||||
/// and symbol editing layers never, opacity masks not with SVG Tiny 1.2, and objects with effects
|
||||
/// SVG has no filters for as the images the file draws of them), of the art the file draws for each
|
||||
/// placed document, and of the symbols, patterns and brushes that art uses; with
|
||||
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
|
||||
/// and each data set's image. The error names no file or folder.
|
||||
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
|
||||
@@ -162,21 +164,27 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
|
||||
// layers kept: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden) = match super::svg::options_map(p) {
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
|
||||
// layers kept and SVG 1.1: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
|
||||
Ok(m) => {
|
||||
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
|
||||
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
|
||||
let tiny = m.get("profile").and_then(Value::as_str) == Some("tiny12");
|
||||
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"), tiny)
|
||||
}
|
||||
Err(_) => (true, true, true),
|
||||
Err(_) => (true, true, true, false),
|
||||
};
|
||||
// The opacity-mask and symbol editing layers are never written.
|
||||
let d = &*d.without_edit_modes();
|
||||
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
|
||||
if preserve && crate::cmd::links::names_hidden_file(d, base)
|
||||
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
|
||||
{
|
||||
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden, tiny);
|
||||
// The SVG draws the objects with effects it has no filters for as images of them, as the
|
||||
// encoder and the clipboard prepare them.
|
||||
let drawing_names = || {
|
||||
let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(d, !tiny);
|
||||
let d = flat.as_ref().unwrap_or(d);
|
||||
names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
|
||||
};
|
||||
if preserve && crate::cmd::links::names_hidden_file(d, base) || names(d) && drawing_names() {
|
||||
return Err(bad(cmd, IMAGE_OUTSIDE));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -894,12 +894,19 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
return Some(format!("an image of {w} × {h} pixels is too large to draw"));
|
||||
}
|
||||
let d = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?;
|
||||
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let format = reader.format()?;
|
||||
let d = reader.into_decoder().ok()?;
|
||||
let (w, h) = d.dimensions();
|
||||
// The allowance also counts the pixels as RGBA: an image of fewer than 4 bytes a pixel (gray,
|
||||
// gray with alpha, RGB) takes more than the decoder counts (#1717).
|
||||
let rgba_over = u64::from(w) * u64::from(h) > MAX_RASTER_ALLOC / 4;
|
||||
(rgba_over || d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
|
||||
let samples_over = d.total_bytes() > MAX_RASTER_ALLOC;
|
||||
// The renderer can stream a non-interlaced PNG a row at a time when those buffers fit. Its
|
||||
// full decoded byte count can exceed the allowance even though drawing it at native size is
|
||||
// safe; use the renderer's decision for that case instead of warning from total_bytes alone.
|
||||
let png_streams_at_size = samples_over && format == image::ImageFormat::Png && vectorcraft_render::reduced_size(bytes) == Some((w, h));
|
||||
(rgba_over || (samples_over && !png_streams_at_size)).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
|
||||
}
|
||||
|
||||
/// What Open, Place and the Links panel say of encoded image `bytes` that [`too_large_note`] is
|
||||
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destinatio
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -87,8 +87,9 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
|
||||
if count > MAX_SLICES {
|
||||
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
|
||||
}
|
||||
let one_after_another = records_one_after_another(Reader::new(r.rest()), count, *budget);
|
||||
let mut out = vec![];
|
||||
for _ in 0..count {
|
||||
for i in 0..count {
|
||||
// The ID and group ID.
|
||||
r.take(8)?;
|
||||
let origin = r.u32()?;
|
||||
@@ -116,9 +117,10 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
|
||||
format!("#{red:02x}{green:02x}{blue:02x}")
|
||||
};
|
||||
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
|
||||
// doesn't start one is the next slice. A descriptor read that uses up the budget is an
|
||||
// error.
|
||||
if r.rest().starts_with(&16u32.to_be_bytes()) {
|
||||
// doesn't start one is the next slice. When the records follow one another, only the
|
||||
// last one may be followed by a descriptor. A descriptor read that uses up the budget is
|
||||
// an error.
|
||||
if (!one_after_another || i + 1 == count) && r.rest().starts_with(&16u32.to_be_bytes()) {
|
||||
let mut ahead = Reader::new(r.rest());
|
||||
ahead.u32()?;
|
||||
match descriptor(&mut ahead, 0, budget) {
|
||||
@@ -139,6 +141,37 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Whether `r` holds `count` version 6 records one after another, followed by nothing or by one
|
||||
/// descriptor (version 16) that reads within `budget`, as ag-psd writes them. A record whose ID is
|
||||
/// 16 then isn't taken for a descriptor. Otherwise each record may be followed by a descriptor.
|
||||
fn records_one_after_another(mut r: Reader<'_>, count: usize, mut budget: usize) -> bool {
|
||||
if !(0..count).all(|_| skip_record(&mut r).is_ok()) {
|
||||
return false;
|
||||
}
|
||||
r.rest().is_empty() || (r.rest().starts_with(&16u32.to_be_bytes()) && r.u32().is_ok() && descriptor(&mut r, 0, &mut budget).is_ok())
|
||||
}
|
||||
|
||||
/// Reads past the version 6 record `r` starts with, in the layout [`version_6`] reads. Its strings
|
||||
/// are checked and read past without being decoded.
|
||||
fn skip_record(r: &mut Reader<'_>) -> Result<(), String> {
|
||||
// The ID and group ID.
|
||||
r.take(8)?;
|
||||
if r.u32()? == 1 {
|
||||
r.take(4)?;
|
||||
}
|
||||
units(r)?;
|
||||
// The type and the rectangle.
|
||||
r.take(20)?;
|
||||
for _ in 0..4 {
|
||||
units(r)?;
|
||||
}
|
||||
r.take(1)?;
|
||||
units(r)?;
|
||||
// The alignments and the background color.
|
||||
r.take(12)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
|
||||
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
|
||||
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
|
||||
@@ -221,12 +254,17 @@ fn text_len(n: usize) -> Result<usize, String> {
|
||||
|
||||
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
|
||||
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
|
||||
let n = text_len(r.u32()? as usize)?;
|
||||
let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?;
|
||||
let bytes = units(r)?;
|
||||
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
|
||||
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
|
||||
}
|
||||
|
||||
/// A Unicode string's units, as bytes: a count of UTF-16 units, then the units.
|
||||
fn units<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], String> {
|
||||
let n = text_len(r.u32()? as usize)?;
|
||||
r.take(n.checked_mul(2).ok_or(TRUNCATED)?)
|
||||
}
|
||||
|
||||
/// A descriptor's value, as far as the slices need it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Value {
|
||||
|
||||
@@ -262,6 +262,32 @@ fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
|
||||
assert_eq!(names, ["a", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_6_record_whose_id_is_16_is_a_slice_not_a_descriptor() {
|
||||
// The 16th record has ID 16, group ID 0, origin 2, no name and the Image type: its first 18
|
||||
// bytes also read as a descriptor of version 16 with no items.
|
||||
let records: Vec<S> = (1..=17).map(|id| if id == 16 { user("", [1, 1, 4, 4]) } else { user("a", [0, 0, 5, 5]) }).collect();
|
||||
let descriptor_after = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
|
||||
for trailing in [vec![], descriptor_after] {
|
||||
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let got = slices(&s);
|
||||
assert_eq!(got.len(), 17, "{got:?}");
|
||||
assert_eq!((got[15].0, got[15].1.name.as_str()), (Rect::new(1.0, 1.0, 4.0, 4.0), ""));
|
||||
assert_eq!(got[16].1.name, "a");
|
||||
}
|
||||
// A descriptor after each record whose class ID is four zero bytes, with no items, followed by
|
||||
// records with no strings: the records don't also read one after another.
|
||||
let empty = [ustr(""), 0u32.to_be_bytes().to_vec(), vec![0; 4], 0u32.to_be_bytes().to_vec()].concat();
|
||||
let trailing = [16u32.to_be_bytes().to_vec(), empty].concat();
|
||||
for rect in [[0, 0, 0, 0], [0, 0, 5, 5]] {
|
||||
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&[user("", rect), user("", rect), user("", rect)], &trailing)), json!({}));
|
||||
let w = warnings(&r);
|
||||
assert!(!w.iter().any(|w| w.starts_with("the slices can't be read")), "{w:?}");
|
||||
assert_eq!(slices(&s).len(), if rect[2] > 0 { 3 } else { 0 }, "{w:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_6_descriptors_share_one_budget_of_values() {
|
||||
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
|
||||
|
||||
@@ -185,9 +185,12 @@ impl Sets {
|
||||
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
|
||||
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
|
||||
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that
|
||||
/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps
|
||||
/// only its part above the later box's top, so boxes staggered right and down each meet only the
|
||||
/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]).
|
||||
/// a later box of its group overlaps and ends no further right than keeps only the part the later
|
||||
/// box doesn't cover: its part above the later box's top when the later box starts lower and ends
|
||||
/// no higher than it, and its part below the later box's bottom when the later box starts no lower
|
||||
/// and ends higher than it. The open box's top then moves down in the tree, so boxes staggered right
|
||||
/// and down, or right and up, each meet only the one before. Fails only when cancelled
|
||||
/// ([`vectorcraft_doc::cancel`]).
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
|
||||
Ok(sweep(bounds, None)?.groups())
|
||||
}
|
||||
@@ -206,27 +209,25 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
};
|
||||
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
|
||||
let n = boxes.len();
|
||||
// Each box's place in the tree: by top (then index).
|
||||
let mut by_top: Vec<usize> = (0..n).collect();
|
||||
by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b)));
|
||||
let tops: Vec<f64> = by_top.iter().map(|&k| boxes[k].1.y0).collect();
|
||||
let mut leaf = vec![0usize; n];
|
||||
for (pos, &k) in by_top.iter().enumerate() {
|
||||
leaf[k] = pos;
|
||||
}
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
|
||||
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
|
||||
let size = n.next_power_of_two().max(1);
|
||||
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
|
||||
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
|
||||
let set = |low: &mut [f64], pos: usize, v: f64| {
|
||||
let mut i = pos + size;
|
||||
low[i] = v;
|
||||
while i > 1 {
|
||||
i /= 2;
|
||||
low[i] = low[2 * i].max(low[2 * i + 1]);
|
||||
}
|
||||
// The places an open box's top can be at in the tree: a box's top, or just below a box's
|
||||
// bottom, where a later box cuts it short (`-0.0` as `0.0`).
|
||||
let mut places: Vec<f64> = boxes.iter().flat_map(|(_, b)| [b.y0 + 0.0, b.y1.next_up() + 0.0]).collect();
|
||||
places.sort_by(f64::total_cmp);
|
||||
places.dedup_by(|a, b| a.total_cmp(b).is_eq());
|
||||
let place = |y: f64| {
|
||||
let y = y + 0.0;
|
||||
let p = places.partition_point(|t| t.total_cmp(&y).is_lt());
|
||||
places.get(p).is_some_and(|t| t.total_cmp(&y).is_eq()).then_some(p)
|
||||
};
|
||||
// Each box's part still open, from its top to its bottom, and the place of its top while it
|
||||
// is open.
|
||||
let mut top: Vec<f64> = boxes.iter().map(|(_, b)| b.y0).collect();
|
||||
let mut bottom: Vec<f64> = boxes.iter().map(|(_, b)| b.y1).collect();
|
||||
let mut open: Vec<Option<usize>> = vec![None; n];
|
||||
// The tree of the open boxes without transparency (every box without `see_through`) and the
|
||||
// see-through boxes'.
|
||||
let mut trees = [Open::new(places.len()), Open::new(if see_through.is_some() { places.len() } else { 0 })];
|
||||
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
|
||||
let mut by_left: Vec<usize> = (0..n).collect();
|
||||
by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0));
|
||||
let mut by_right: Vec<usize> = (0..n).collect();
|
||||
@@ -241,7 +242,9 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
while let Some(&c) = by_right.get(closing)
|
||||
&& boxes[c].1.x1 < b.x0
|
||||
{
|
||||
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
|
||||
if let Some(p) = open[c].take() {
|
||||
trees[tree(c)].take(p, c, &bottom);
|
||||
}
|
||||
closing += 1;
|
||||
}
|
||||
// The open boxes it joins with their top at most this bottom and their bottom at least
|
||||
@@ -253,21 +256,32 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
Some(_) if shadows => &[0, 1],
|
||||
Some(_) => &[1],
|
||||
};
|
||||
let below = tops.partition_point(|t| *t <= b.y1);
|
||||
let below = places.partition_point(|t| *t <= b.y1);
|
||||
met.clear();
|
||||
for &t in looks {
|
||||
let tr = &trees[t];
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
stack.push((1, 0, tr.size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
if lo >= below || low[t][node] < b.y0 {
|
||||
if lo >= below || tr.low[node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
// The boxes with their top here, lowest bottom first.
|
||||
for &(_, o) in tr.at[lo].iter().rev() {
|
||||
if bottom[o] < b.y0 {
|
||||
break;
|
||||
}
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
met.push(o);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
@@ -286,30 +300,91 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
let ob = boxes[o].1;
|
||||
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
|
||||
});
|
||||
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
|
||||
// see-through. Likewise, whatever later overlaps the part of an open box at or below this
|
||||
// one's top, when that box ends no further right or lower than this one, overlaps this
|
||||
// one: the open box then keeps only the part above this one's top.
|
||||
let cut = b.y0.next_down();
|
||||
// Whatever overlaps the open part of a box inside this one overlaps this one, and joins it
|
||||
// when this one is see-through. Likewise, whatever later overlaps the part of an open box
|
||||
// this one covers, when that box ends no further right than this one, overlaps this one:
|
||||
// the open box then keeps only the part above this one's top, when this one reaches its
|
||||
// bottom, or only the part below this one's bottom, when this one reaches its top.
|
||||
for &o in &met {
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
let ob = boxes[o].1;
|
||||
if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 {
|
||||
let Some(p) = open[o] else { continue };
|
||||
if !shadows || Some(o) == holder || b.x1 < boxes[o].1.x1 {
|
||||
continue;
|
||||
}
|
||||
if b.y0 <= ob.y0 {
|
||||
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
|
||||
} else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] {
|
||||
set(&mut low[tree(o)], leaf[o], cut);
|
||||
let (t, u) = (top[o], bottom[o]);
|
||||
let tr = &mut trees[tree(o)];
|
||||
if b.y0 <= t && u <= b.y1 {
|
||||
tr.take(p, o, &bottom);
|
||||
open[o] = None;
|
||||
continue;
|
||||
}
|
||||
if holder.is_some() || (b.y1 < u && t < b.y0) {
|
||||
continue;
|
||||
}
|
||||
let (t, u) = if u <= b.y1 { (t, b.y0.next_down()) } else { (b.y1.next_up(), u) };
|
||||
// Every top it can get has a place; one without stays as it is.
|
||||
let Some(q) = place(t) else { continue };
|
||||
tr.take(p, o, &bottom);
|
||||
(top[o], bottom[o]) = (t, u);
|
||||
open[o] = (t <= u).then_some(q);
|
||||
if t <= u {
|
||||
tr.put(q, o, &bottom);
|
||||
}
|
||||
}
|
||||
if holder.is_none() {
|
||||
set(&mut low[tree(k)], leaf[k], b.y1);
|
||||
if holder.is_none()
|
||||
&& let Some(p) = place(b.y0)
|
||||
{
|
||||
open[k] = Some(p);
|
||||
trees[tree(k)].put(p, k, &bottom);
|
||||
}
|
||||
}
|
||||
Ok(sets)
|
||||
}
|
||||
|
||||
/// The open boxes of [`sweep`] by the place of their tops, in a tree that knows the lowest bottom
|
||||
/// below each of its branches.
|
||||
struct Open {
|
||||
size: usize,
|
||||
/// The lowest bottom of the open boxes below each node (−∞: none open).
|
||||
low: Vec<f64>,
|
||||
/// The open boxes at each place, by bottom ([`order`]) and then index.
|
||||
at: Vec<BTreeSet<(i64, usize)>>,
|
||||
}
|
||||
|
||||
impl Open {
|
||||
fn new(places: usize) -> Self {
|
||||
let size = places.next_power_of_two().max(1);
|
||||
Self { size, low: vec![f64::NEG_INFINITY; 2 * size], at: vec![BTreeSet::new(); places] }
|
||||
}
|
||||
|
||||
/// Opens box `k` at place `p`, with its bottom `bottom[k]`.
|
||||
fn put(&mut self, p: usize, k: usize, bottom: &[f64]) {
|
||||
self.at[p].insert((order(bottom[k]), k));
|
||||
self.fix(p, bottom);
|
||||
}
|
||||
|
||||
/// Closes box `k` at place `p`, while its bottom is still `bottom[k]`.
|
||||
fn take(&mut self, p: usize, k: usize, bottom: &[f64]) {
|
||||
self.at[p].remove(&(order(bottom[k]), k));
|
||||
self.fix(p, bottom);
|
||||
}
|
||||
|
||||
fn fix(&mut self, p: usize, bottom: &[f64]) {
|
||||
let mut i = p + self.size;
|
||||
self.low[i] = self.at[p].last().map_or(f64::NEG_INFINITY, |&(_, k)| bottom[k]);
|
||||
while i > 1 {
|
||||
i /= 2;
|
||||
self.low[i] = self.low[2 * i].max(self.low[2 * i + 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as an integer in the same order as [`f64::total_cmp`].
|
||||
fn order(v: f64) -> i64 {
|
||||
let b = v.to_bits() as i64;
|
||||
b ^ (((b >> 63) as u64) >> 1) as i64
|
||||
}
|
||||
|
||||
/// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box
|
||||
/// touches.
|
||||
struct Blocks {
|
||||
@@ -775,6 +850,136 @@ mod tests {
|
||||
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
|
||||
}
|
||||
|
||||
/// `n` boxes of one size, each a little right of and above the one before, all overlapping and
|
||||
/// none inside another.
|
||||
fn staggered_up(n: usize) -> Vec<Option<Rect>> {
|
||||
let w = 2.0 * n as f64;
|
||||
(0..n).map(|i| Some(Rect::new(i as f64, -(i as f64), w + i as f64, w - i as f64))).collect()
|
||||
}
|
||||
|
||||
/// Each box of a stagger right and up meets only the box before it, which keeps only its part
|
||||
/// below the new box's bottom, not every box still open; so does each box of a stagger left and
|
||||
/// down, which the sweep meets right and up.
|
||||
#[test]
|
||||
fn boxes_staggered_up_meet_only_the_box_before() {
|
||||
let n = 512;
|
||||
let bounds = staggered_up(n);
|
||||
let all = vec![(0..n).collect::<Vec<_>>()];
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), every_pair(&bounds));
|
||||
assert_eq!(sets.groups(), all);
|
||||
let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), all);
|
||||
let mut reversed = bounds.clone();
|
||||
reversed.reverse();
|
||||
let mut sets = sweep(&reversed, None).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), all);
|
||||
let mut sets = sweep(&reversed, Some(&vec![true; n])).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), all);
|
||||
}
|
||||
|
||||
/// An open box cut short from above keeps the part a later box would meet without meeting the
|
||||
/// box that cut it: a part below that box, a part further right, or any part when that box is
|
||||
/// opaque or held; a box cut from above and from below keeps its middle.
|
||||
#[test]
|
||||
fn a_box_is_cut_short_from_above_only_where_the_later_box_covers_it() {
|
||||
let k = Rect::new(5.0, -5.0, 15.0, 10.0);
|
||||
let cases = [
|
||||
// Below `k`: the last box overlaps only the bottom of the first.
|
||||
("below", vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 15.0, 9.0, 25.0))], vec![true, true, false]),
|
||||
// Further right than `k`: `k` cuts nothing and the last box overlaps the first.
|
||||
("right", vec![Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(k), Some(Rect::new(17.0, 2.0, 25.0, 4.0))], vec![true, true, false]),
|
||||
// Just below `k`'s bottom, and touching it.
|
||||
(
|
||||
"edge",
|
||||
vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 10.0, 9.0, 12.0)), Some(Rect::new(8.0, 10.5, 9.0, 12.0))],
|
||||
vec![false, true, false, false],
|
||||
),
|
||||
// An opaque `k` doesn't join the opaque last box, which joins the see-through first one.
|
||||
("opaque", vec![Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, -10.0, 7.0, 2.0))], vec![true, false, false]),
|
||||
// A see-through `k` held by a see-through box around it isn't opened and cuts nothing short.
|
||||
(
|
||||
"held",
|
||||
vec![
|
||||
Some(Rect::new(0.0, -6.0, 30.0, 28.0)),
|
||||
Some(Rect::new(1.0, 0.0, 10.0, 20.0)),
|
||||
Some(k),
|
||||
Some(Rect::new(6.0, 11.0, 7.0, 13.0)),
|
||||
Some(Rect::new(6.0, 4.0, 7.0, 6.0)),
|
||||
],
|
||||
vec![true, false, true, false, false],
|
||||
),
|
||||
// Cut from above, then from below: a later box inside what is left joins the first.
|
||||
(
|
||||
"middle",
|
||||
vec![
|
||||
Some(Rect::new(0.0, 0.0, 10.0, 30.0)),
|
||||
Some(Rect::new(2.0, -5.0, 12.0, 10.0)),
|
||||
Some(Rect::new(3.0, 20.0, 13.0, 40.0)),
|
||||
Some(Rect::new(5.0, 15.0, 6.0, 16.0)),
|
||||
Some(Rect::new(5.0, 9.0, 6.0, 10.0)),
|
||||
Some(Rect::new(5.0, 20.0, 6.0, 20.0)),
|
||||
],
|
||||
vec![false, true, true, false, false, false],
|
||||
),
|
||||
// Signed zeros, a point and a box that isn't finite.
|
||||
(
|
||||
"zeros",
|
||||
vec![
|
||||
Some(Rect::new(-0.0, -0.0, 4.0, 8.0)),
|
||||
Some(Rect::new(0.0, -2.0, 6.0, -0.0)),
|
||||
Some(Rect::new(1.0, 0.0, 1.0, 0.0)),
|
||||
Some(Rect::new(2.0, f64::NEG_INFINITY, 3.0, 1.0)),
|
||||
Some(Rect::new(3.0, f64::MAX, 3.0, f64::MAX)),
|
||||
Some(Rect::new(3.5, 0.0, 3.5, 0.0)),
|
||||
],
|
||||
vec![false, true, false, true, true, false],
|
||||
),
|
||||
];
|
||||
for (what, bounds, see) in cases {
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "{what}");
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "{what}, with transparency");
|
||||
let mut sets = sweep(&bounds, Some(&vec![true; bounds.len()])).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair(&bounds), "{what}, all see-through");
|
||||
}
|
||||
}
|
||||
|
||||
/// Boxes stepping right and alternately up and down, so that open boxes are cut short from
|
||||
/// above and from below, of mixed sizes, some see-through, group as comparing every pair groups
|
||||
/// them.
|
||||
#[test]
|
||||
fn boxes_stepping_up_and_down_group_as_comparing_every_pair() {
|
||||
let mut seed = 0x6a09_e667_f3bc_c908u64;
|
||||
let mut next = |m: f64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 1000) as f64 / 1000.0 * m
|
||||
};
|
||||
for round in 0..40 {
|
||||
let n = 10 + round * 3;
|
||||
let mut y = 0.0;
|
||||
let bounds: Vec<Option<Rect>> = (0..n)
|
||||
.map(|i| {
|
||||
let up = if (i / (1 + round % 3)) % 2 == 0 { -1.0 } else { 1.0 };
|
||||
y += up * (next(4.0).floor() + 1.0);
|
||||
let x = i as f64 + next(2.0).floor();
|
||||
let (w, h) = (next(12.0).floor() + 4.0, next(16.0).floor() + 2.0);
|
||||
Some(Rect::new(x, y, x + w, y + h))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
|
||||
let see: Vec<bool> = (0..n).map(|_| next(1.0) < if round % 2 == 0 { 0.5 } else { 0.9 }).collect();
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
|
||||
}
|
||||
}
|
||||
|
||||
/// An open box keeps the part a later box would meet without meeting the box that cut it short:
|
||||
/// a part lower than that box, a part further right, or any part when that box is opaque.
|
||||
#[test]
|
||||
|
||||
@@ -534,7 +534,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
|
||||
// not one for new art.
|
||||
let selected = !ids.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?;
|
||||
// How the gradient lies on a stroke (the panel's Stroke buttons).
|
||||
let mode = match str_param(p, "strokeMode") {
|
||||
None => None,
|
||||
@@ -558,7 +558,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
});
|
||||
let for_default = match p.get("aspect").and_then(Value::as_f64) {
|
||||
Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => {
|
||||
Some(a) if a < 0.0 && selected && default_kind != Some(GradientKind::Conic) => {
|
||||
let mut q = p.clone();
|
||||
q["aspect"] = json!(-a);
|
||||
std::borrow::Cow::Owned(q)
|
||||
@@ -568,7 +568,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A spread for selected gradients leaves a freeform default (which has no ends) as it is.
|
||||
let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad());
|
||||
let for_default = match for_default {
|
||||
q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => {
|
||||
q if spreads && selected && default_kind == Some(GradientKind::Freeform) => {
|
||||
let mut q = q.into_owned();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.remove("spread");
|
||||
@@ -579,8 +579,14 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// Only design art was given or selected: nothing changes, the defaults and the remembered paint included.
|
||||
if selected && ids.is_empty() {
|
||||
// An aligned `item` of the art alone is still checked: a row the art lacks, or that no other object has, is an error.
|
||||
edit_items(s, &ids, item, of, C, "Gradient", !stroke, |_, _| Ok(()))?;
|
||||
return Ok(json!({"ids": []}));
|
||||
}
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &ids);
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| {
|
||||
@@ -770,7 +776,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if targets.is_empty() {
|
||||
return Err(EngineError::Other("nothing selected".into()));
|
||||
}
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
let targets = super::appearance::drop_design_art_rows(s, targets, item, !stroke, C)?;
|
||||
let model = super::paint::new_color_model(s, &Value::Null);
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
|
||||
@@ -49,9 +49,9 @@ use generate::generate;
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
|
||||
label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among,
|
||||
series_marks_in, series_object_opacity_differs, shown_paint,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades,
|
||||
is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
|
||||
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::swatches::walk_with_masks;
|
||||
use vectorcraft_geom::Shape;
|
||||
|
||||
use super::axis::radar_axis;
|
||||
@@ -767,6 +768,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap<NodeId, bool>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included)
|
||||
/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a
|
||||
/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`].
|
||||
pub(crate) fn wedge_shades(n: &Node) -> HashMap<NodeId, Vec<bool>> {
|
||||
let mut out = HashMap::new();
|
||||
walk_with_masks(n, &mut |m| {
|
||||
if let Some(g) = m.extras().graph.as_deref()
|
||||
&& g.kind == GraphKind::Pie
|
||||
&& g.legend
|
||||
&& g.pie_legend_in_wedges
|
||||
&& !g.label_styles.legend_fill_is_own()
|
||||
{
|
||||
out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a
|
||||
/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept
|
||||
/// their darkness keep their labels as they are.
|
||||
pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap<NodeId, Vec<bool>>) {
|
||||
let mut changed = vec![];
|
||||
walk_with_masks(n, &mut |m| {
|
||||
if let Some(before) = was.get(&m.id)
|
||||
&& pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied())
|
||||
{
|
||||
changed.push(m.id);
|
||||
}
|
||||
});
|
||||
if !changed.is_empty() {
|
||||
restore_contrast(n, &changed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw
|
||||
/// sets them on their wedges.
|
||||
fn restore_contrast(n: &mut Node, ids: &[NodeId]) {
|
||||
if ids.contains(&n.id) {
|
||||
let on_dark = match n.extras().graph.as_deref() {
|
||||
Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)),
|
||||
None => HashMap::new(),
|
||||
};
|
||||
set_legend_fills(n, &on_dark);
|
||||
}
|
||||
let holds = |c: &Node| {
|
||||
let mut found = false;
|
||||
walk_with_masks(c, &mut |m| found |= ids.contains(&m.id));
|
||||
found
|
||||
};
|
||||
if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art))
|
||||
&& let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
{
|
||||
restore_contrast(Arc::make_mut(&mut m.art), ids);
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if holds(c) {
|
||||
restore_contrast(Arc::make_mut(c), ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them.
|
||||
fn legend_labels(n: &Node) -> Vec<&Node> {
|
||||
legend_in(n.children().map_or(&[], |c| c.as_slice()))
|
||||
|
||||
@@ -454,7 +454,7 @@ fn an_edit_of_a_graph_designs_art_is_lost_when_the_graph_is_drawn_again() {
|
||||
/// it, and edit the other objects they are given.
|
||||
#[test]
|
||||
fn paint_commands_leave_a_graph_designs_art_out() {
|
||||
let (mut s, _, copy, art, mark) = design_art();
|
||||
let (mut s, graph, copy, art, mark) = design_art();
|
||||
let fill = top_row(&s, art, true);
|
||||
let commands = [
|
||||
("stroke.set", json!({"weight": 5})),
|
||||
@@ -466,6 +466,7 @@ fn paint_commands_leave_a_graph_designs_art_out() {
|
||||
("paint.swap", json!({})),
|
||||
("paint.default", json!({})),
|
||||
("paint.invert", json!({"item": fill, "stroke": false})),
|
||||
("paint.invert", json!({})),
|
||||
];
|
||||
let (copy_was, art_was) = (look(&s, copy), look(&s, art));
|
||||
for (cmd, p) in &commands {
|
||||
@@ -489,6 +490,11 @@ fn paint_commands_leave_a_graph_designs_art_out() {
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
|
||||
assert_eq!(look(&s, art), art_was);
|
||||
// Given the whole graph, Invert recolors the marks and leaves the art.
|
||||
let mark_was = look(&s, mark);
|
||||
s.execute("paint.invert", &json!({"ids": [graph.0]})).unwrap();
|
||||
assert_eq!(look(&s, art), art_was);
|
||||
assert_ne!(look(&s, mark), mark_was);
|
||||
// A freeform gradient point is refused on the art alone.
|
||||
refused_on_design_art(&mut s, "paint.freeform.addPoint", json!({"ids": [art.0], "at": [0, 0]}));
|
||||
}
|
||||
@@ -517,6 +523,182 @@ fn stroke_edits_of_selected_design_art_leave_the_new_art_stroke() {
|
||||
assert_eq!(s.new_art_stroke().gradient_mode, mode, "paint.editGradient");
|
||||
}
|
||||
|
||||
/// With only the art of a graph design given or selected, the gradient, swap, default and recolor commands leave the
|
||||
/// paint for new art and the remembered colors as they are.
|
||||
#[test]
|
||||
fn paint_edits_of_design_art_alone_leave_the_defaults() {
|
||||
let (mut s, _, _, art, _) = design_art();
|
||||
let fill = top_row(&s, art, true);
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
|
||||
let defaults = |s: &Session| format!("{:?}", (&s.paint, s.last_solid, &s.last_gradient, &s.recent_colors));
|
||||
let commands = [
|
||||
("paint.editGradient", json!({"kind": "linear"})),
|
||||
("paint.editGradient", json!({"kind": "radial", "stroke": true})),
|
||||
("paint.swap", json!({})),
|
||||
("paint.default", json!({})),
|
||||
("paint.invert", json!({"item": fill, "stroke": false})),
|
||||
("paint.complement", json!({"item": fill, "stroke": false})),
|
||||
("paint.invert", json!({})),
|
||||
("paint.complement", json!({"stroke": true})),
|
||||
("stroke.set", json!({"weight": 7})),
|
||||
("stroke.weightUp", json!({})),
|
||||
];
|
||||
for (cmd, p) in &commands {
|
||||
let was = defaults(&s);
|
||||
let mut q = p.clone();
|
||||
q["ids"] = json!([art.0]);
|
||||
s.execute(cmd, &q).unwrap();
|
||||
assert_eq!(defaults(&s), was, "{cmd}, given");
|
||||
// Selecting the art makes the defaults take its paint.
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
let was = defaults(&s);
|
||||
s.execute(cmd, p).unwrap();
|
||||
assert_eq!(defaults(&s), was, "{cmd}, selected");
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
}
|
||||
// A bad `item`, `aligned` or `target` is still an error with only design art given.
|
||||
for bad in [
|
||||
json!({"ids": [art.0], "item": "top"}),
|
||||
json!({"ids": [art.0], "item": fill, "aligned": "yes"}),
|
||||
json!({"ids": [art.0], "item": fill, "target": "nowhere"}),
|
||||
json!({"ids": [art.0], "target": "nowhere"}),
|
||||
] {
|
||||
assert!(s.execute("paint.invert", &bad).is_err(), "{bad}");
|
||||
assert!(s.execute("paint.complement", &bad).is_err(), "{bad}");
|
||||
}
|
||||
// So is an `item` the art has no row for, in each command that leaves the art out.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, p) in [
|
||||
("paint.invert", json!({})),
|
||||
("stroke.set", json!({"weight": 2})),
|
||||
("stroke.weightUp", json!({})),
|
||||
("stroke.setAdvanced", json!({"swapArrows": true})),
|
||||
("paint.editGradient", json!({"kind": "linear"})),
|
||||
("paint.setGradientGeom", json!({"start": [0, 0], "end": [50, 50]})),
|
||||
("object.setOverprint", json!({"fill": true})),
|
||||
] {
|
||||
let mut q = p.clone();
|
||||
q["ids"] = json!([art.0]);
|
||||
q["item"] = json!(99);
|
||||
assert!(s.execute(cmd, &q).is_err(), "{cmd}");
|
||||
}
|
||||
// The art's stroke row named without `stroke` is a stroke row: the gradient commands succeed and change nothing.
|
||||
let stroke_row = top_row(&s, art, false);
|
||||
for p in [json!({"kind": "linear"}), json!({"start": [0, 0], "end": [50, 50]})] {
|
||||
let cmd = if p.get("kind").is_some() { "paint.editGradient" } else { "paint.setGradientGeom" };
|
||||
let mut q = p.clone();
|
||||
q["ids"] = json!([art.0]);
|
||||
q["item"] = json!(stroke_row);
|
||||
s.execute(cmd, &q).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
// With nothing selected, the swap still swaps the defaults.
|
||||
let was = defaults(&s);
|
||||
s.execute("paint.swap", &json!({})).unwrap();
|
||||
assert_ne!(defaults(&s), was);
|
||||
}
|
||||
|
||||
/// A spread or a negative aspect for the art of a graph design alone changes nothing, whatever kind of gradient the
|
||||
/// default fill is; a bad value is still an error.
|
||||
#[test]
|
||||
fn gradient_edits_of_design_art_alone_skip_the_default_kind_checks() {
|
||||
let (mut s, _, _, art, _) = design_art();
|
||||
for (default, p) in [("freeform", json!({"spread": "repeat"})), ("linear", json!({"aspect": -50}))] {
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"kind": default})).unwrap();
|
||||
let (was, art_was, steps) = (format!("{:?}", s.paint), look(&s, art), s.doc().unwrap().history.undo.len());
|
||||
let mut q = p.clone();
|
||||
q["ids"] = json!([art.0]);
|
||||
s.execute("paint.editGradient", &q).unwrap_or_else(|e| panic!("{q}: {e}"));
|
||||
assert_eq!(format!("{:?}", s.paint), was, "{default}");
|
||||
assert_eq!(look(&s, art), art_was, "{default}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{default}");
|
||||
}
|
||||
assert!(s.execute("paint.editGradient", &json!({"ids": [art.0], "spread": "sideways"})).is_err());
|
||||
}
|
||||
|
||||
/// Invert given a group around a graph recolors the group's own fill and the series marks, and leaves the art of a
|
||||
/// graph design as it is. With `target: "contents"` the group's own fill stays as it is.
|
||||
#[test]
|
||||
fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() {
|
||||
let (mut s, graph, _, art, mark) = design_art();
|
||||
s.execute("select.set", &json!({"ids": [graph.0]})).unwrap();
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
|
||||
let row = top_row(&s, group, true);
|
||||
s.execute("paint.setFill", &json!({"ids": [group.0], "item": row, "color": "#ff0000"})).unwrap();
|
||||
let own = |s: &Session| format!("{:?}", s.doc().unwrap().doc.node(group).unwrap().appearance.items);
|
||||
let (own_was, art_was, mark_was) = (own(&s), look(&s, art), look(&s, mark));
|
||||
s.execute("paint.invert", &json!({"ids": [group.0]})).unwrap();
|
||||
assert_ne!(own(&s), own_was, "the group's own fill");
|
||||
assert_ne!(look(&s, mark), mark_was);
|
||||
assert_eq!(look(&s, art), art_was);
|
||||
// The color remembered is the group's own new fill, which the Fill proxy shows.
|
||||
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).cloned() else {
|
||||
panic!("the group's fill is not a solid color")
|
||||
};
|
||||
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
|
||||
let (own_was, mark_was) = (own(&s), look(&s, mark));
|
||||
s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap();
|
||||
assert_eq!(own(&s), own_was, "target: contents");
|
||||
assert_ne!(look(&s, mark), mark_was);
|
||||
assert_eq!(look(&s, art), art_was);
|
||||
}
|
||||
|
||||
/// Invert and Complement given a series group that holds only a graph design's art recolor the group's own fill and
|
||||
/// remember that color, as the last color and the newest recent color. With several such groups the color remembered
|
||||
/// is that of the first group whose fill changed.
|
||||
#[test]
|
||||
fn recoloring_a_group_of_design_art_alone_remembers_its_own_fill() {
|
||||
// A fill of its own for `group`, painted `hex` (the color of a rectangle painted with it).
|
||||
let paint_own = |s: &mut Session, group: NodeId, hex: &str| {
|
||||
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
|
||||
let t = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [t.0], "color": hex})).unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let paint = d.node(t).unwrap().proxy_paint_only(false, None).unwrap().clone();
|
||||
d.node_mut(group).unwrap().appearance.fill_at_mut(None).unwrap().paint = paint;
|
||||
};
|
||||
// Series 0's group with its own fill painted `hex`.
|
||||
let painted_series = |hex: &str| {
|
||||
let (mut s, graph, _, art, _) = design_art();
|
||||
let group = series(s.doc().unwrap().doc.node(graph).unwrap(), 0).id;
|
||||
paint_own(&mut s, group, hex);
|
||||
(s, group, art)
|
||||
};
|
||||
for cmd in ["paint.invert", "paint.complement"] {
|
||||
let (mut s, group, art) = painted_series("#ff0000");
|
||||
let fill = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).unwrap().clone();
|
||||
let (art_was, fill_was) = (look(&s, art), fill(&s));
|
||||
s.execute(cmd, &json!({"ids": [group.0]})).unwrap();
|
||||
assert_eq!(look(&s, art), art_was, "{cmd}");
|
||||
assert_ne!(fill(&s), fill_was, "{cmd}: the group's fill is recolored");
|
||||
let Paint::Solid { color, .. } = fill(&s) else { panic!("{cmd}: the group's fill is not a solid color") };
|
||||
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)), "{cmd}");
|
||||
}
|
||||
// A gray fill is its own complement: nothing changes, and the remembered colors stay as they were.
|
||||
let (mut s, group, _) = painted_series("#808080");
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
let remembered = |s: &Session| format!("{:?}", (s.last_solid, &s.recent_colors));
|
||||
let was = remembered(&s);
|
||||
assert_eq!(s.execute("paint.complement", &json!({"ids": [group.0]})).unwrap()["changed"], json!(0));
|
||||
assert_eq!(remembered(&s), was);
|
||||
// Both series groups hold only the design's art: a gray one first and a red one, given together.
|
||||
let (mut s, graph, _, _, _) = design_art();
|
||||
s.execute("graph.column", &json!({"id": graph.0, "seriesIndexes": [1], "design": "Square"})).unwrap();
|
||||
let groups = [0, 1].map(|i| series(s.doc().unwrap().doc.node(graph).unwrap(), i).id);
|
||||
paint_own(&mut s, groups[0], "#808080");
|
||||
paint_own(&mut s, groups[1], "#ff0000");
|
||||
s.execute("paint.complement", &json!({"ids": [groups[0].0, groups[1].0]})).unwrap();
|
||||
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(groups[1]).unwrap().proxy_paint_only(false, None).cloned() else {
|
||||
panic!("the red group's fill is not a solid color")
|
||||
};
|
||||
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
|
||||
}
|
||||
|
||||
/// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects
|
||||
/// sets only theirs.
|
||||
#[test]
|
||||
@@ -596,6 +778,81 @@ fn expand_appearance_leaves_a_graph_designs_art() {
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none_or(|m| m.appearance.effects.is_empty()));
|
||||
}
|
||||
|
||||
/// `effect` with `params`, as `effect.apply` gives it to an object.
|
||||
fn an_effect(s: &mut Session, effect: &str, params: serde_json::Value) -> vectorcraft_doc::Effect {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": effect, "ids": [r], "params": params})).unwrap();
|
||||
s.doc().unwrap().doc.node(NodeId(r)).unwrap().appearance.effects[0].clone()
|
||||
}
|
||||
|
||||
/// Expand Appearance of a graph neither lists the art of a design in a series whose own effect it leaves, nor adds an
|
||||
/// image of that effect to the document.
|
||||
#[test]
|
||||
fn expand_appearance_lists_no_design_art_and_rasterizes_none() {
|
||||
let (mut s, id, copy, _, mark) = design_art();
|
||||
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(copy).unwrap().appearance.effects.push(shadow);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0]})).unwrap();
|
||||
let copy_was = look(&s, copy);
|
||||
let images = |s: &Session| s.doc().unwrap().doc.images.len();
|
||||
let before = images(&s);
|
||||
s.execute("select.set", &json!({"ids": [mark.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let per_mark = images(&s) - before;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let expanded = s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert_eq!(expanded["ids"], json!([mark.0]));
|
||||
assert_eq!(look(&s, copy), copy_was);
|
||||
assert_eq!(images(&s) - before, per_mark, "only the mark's shadow becomes an image");
|
||||
}
|
||||
|
||||
/// A geometry effect of a series group that Expand Appearance bakes moves the art of a design in that series with the
|
||||
/// marks.
|
||||
#[test]
|
||||
fn expand_appearance_moves_design_art_with_its_series_groups_effect() {
|
||||
let (mut s, id, copy, _, _) = design_art();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let group = series(&n, 0).id;
|
||||
let shift = an_effect(&mut s, "distort.transform", json!({"moveH": 50}));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().appearance.effects.push(shift);
|
||||
let left = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
series(&n, 0).children().unwrap()[0].geometric_bounds().unwrap().x0
|
||||
};
|
||||
let was = left(&s);
|
||||
assert_eq!(series(&n, 0).children().unwrap()[0].id, copy);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s));
|
||||
}
|
||||
|
||||
/// The copies that a Transform effect of a series group makes of a design's art keep their own effects when Expand
|
||||
/// Appearance bakes the series group's effect, as the art they copy does.
|
||||
#[test]
|
||||
fn expand_appearance_leaves_the_effects_of_design_art_copies() {
|
||||
let (mut s, id, copy, _, _) = design_art();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let group = series(&n, 0).id;
|
||||
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
|
||||
let copies = an_effect(&mut s, "distort.transform", json!({"moveH": 50, "copies": 2}));
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.node_mut(copy).unwrap().appearance.effects.push(shadow);
|
||||
doc.node_mut(group).unwrap().appearance.effects.push(copies);
|
||||
let shadows = |s: &Session| {
|
||||
let mut count = 0;
|
||||
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |m| count += m.appearance.effects.iter().filter(|e| e.id == "stylize.dropShadow").count());
|
||||
count
|
||||
};
|
||||
let images = |s: &Session| s.doc().unwrap().doc.images.len();
|
||||
let before = images(&s);
|
||||
assert_eq!(shadows(&s), 1);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert_eq!(shadows(&s), 3, "the art and its two copies keep their shadows");
|
||||
assert_eq!(images(&s), before, "no shadow becomes an image");
|
||||
}
|
||||
|
||||
/// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by
|
||||
/// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design.
|
||||
#[test]
|
||||
|
||||
@@ -1314,27 +1314,54 @@ pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
|
||||
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
|
||||
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
|
||||
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
|
||||
/// no other resource. Hidden layers and objects are written only with
|
||||
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
|
||||
/// Always `false` without read roots in force.
|
||||
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
|
||||
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
|
||||
/// no other resource. A placed document's images are those of the art the SVG draws for it. Hidden
|
||||
/// layers and objects are written only with SVG Options › hidden layers kept (`hidden`), in the
|
||||
/// layers and in the symbols, patterns and graph designs alike, and template layers never. SVG Tiny
|
||||
/// 1.2 (`tiny`) writes no opacity masks ([`svg_written`]). Always `false` without read roots in
|
||||
/// force.
|
||||
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool, tiny: bool) -> bool {
|
||||
if crate::file_access::current().is_none() {
|
||||
return false;
|
||||
}
|
||||
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
|
||||
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
|
||||
if !d.has_placed() && !names_hidden_image(d, base, link) {
|
||||
return false;
|
||||
}
|
||||
// The writer draws placed documents' art with the pixels their files hold.
|
||||
let placed = d.with_placed_art();
|
||||
let d = &*placed;
|
||||
let art = d.layers.iter().filter_map(|l| svg_written(d, l, hidden, tiny)).collect();
|
||||
let mut out = super::clipboard::Clipboard::gather(d, art).to_document();
|
||||
let written = |n: &std::sync::Arc<Node>| {
|
||||
let empty = || Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
|
||||
std::sync::Arc::new(svg_written(d, n, hidden, tiny).unwrap_or_else(empty))
|
||||
};
|
||||
for s in &mut out.symbols {
|
||||
s.art = written(&s.art);
|
||||
}
|
||||
for g in &mut out.graph_designs {
|
||||
g.art = written(&g.art);
|
||||
}
|
||||
for p in &mut out.patterns {
|
||||
p.art = p.art.iter().filter_map(|n| svg_written(d, n, hidden, tiny)).map(std::sync::Arc::new).collect();
|
||||
}
|
||||
names_hidden_image(&out, base, link)
|
||||
}
|
||||
|
||||
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
|
||||
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
|
||||
/// Only layers and groups lose members; other objects keep theirs as they are.
|
||||
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
|
||||
/// `n` (an object of `d`) as the SVG writer writes it, or `None` when it writes none of it: a
|
||||
/// hidden layer or object is left out unless `hidden`, a template layer's art always, a disabled
|
||||
/// opacity mask's art, and with SVG Tiny 1.2 (`tiny`) every opacity mask's art. A placed document
|
||||
/// is the art the writer draws for it. Only layers and groups lose members; other objects keep
|
||||
/// theirs as they are.
|
||||
fn svg_written(d: &Document, n: &Node, hidden: bool, tiny: bool) -> Option<Node> {
|
||||
if !(n.visible || hidden) {
|
||||
return None;
|
||||
}
|
||||
if matches!(n.kind, NodeKind::PlacedDocument(_)) {
|
||||
return svg_written(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n), hidden, tiny);
|
||||
}
|
||||
let mut n = n.clone();
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
|
||||
let art = svg_written(&m.art, hidden)?;
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled && !tiny).and_then(|m| {
|
||||
let art = svg_written(d, &m.art, hidden, tiny)?;
|
||||
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
|
||||
});
|
||||
if n.extras().mask.is_some() {
|
||||
@@ -1343,7 +1370,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
|
||||
match &mut n.kind {
|
||||
NodeKind::Layer { template: true, children, .. } => children.clear(),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
|
||||
*children = children.iter().filter_map(|c| svg_written(d, c, hidden, tiny)).map(std::sync::Arc::new).collect();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -126,14 +126,18 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<(bool, bool)>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each kind's item target and objects: (fill?, item, ids).
|
||||
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
|
||||
/// Each kind's item target and objects: (fill?, item, ids). With `edit`, the art of graph designs drawn in graph series
|
||||
/// is left out, and an explicit item that the art left out has no row of that kind for is an error, as when the edit
|
||||
/// resolves it on the other objects. Without it, the art is read with the other objects.
|
||||
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>, edit: bool) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
|
||||
let item = item_target(s, p, cmd)?;
|
||||
kinds
|
||||
.into_iter()
|
||||
.map(|fill| {
|
||||
let it = item.of_kind(s, fill);
|
||||
Ok((fill, it, it.targets(s, p)?))
|
||||
let ids = it.targets(s, p)?;
|
||||
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
|
||||
Ok((fill, it, ids))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -159,12 +163,7 @@ pub(super) type OverprintJob = ((bool, ItemTarget, Vec<NodeId>), bool);
|
||||
/// `object.setOverprint` aims, leaving out the art of graph designs drawn in graph series.
|
||||
pub(super) fn overprint_jobs(s: &Session, p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<OverprintJob>> {
|
||||
let kinds = kinds(p, cmd, keys)?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0))?
|
||||
.into_iter()
|
||||
.map(|(fill, it, ids)| (fill, it, super::appearance::drop_design_art(d, ids)))
|
||||
.zip(kinds.iter().map(|k| k.1))
|
||||
.collect())
|
||||
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0), true)?.into_iter().zip(kinds.iter().map(|k| k.1)).collect())
|
||||
}
|
||||
|
||||
/// Apply `jobs` to `d`, adding the objects changed to `changed`.
|
||||
@@ -203,7 +202,7 @@ fn attributes(s: &Session, p: &Value) -> Result<AttributesInfo> {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut info = AttributesInfo { ids: targets(s, p)?, recent_urls: s.recent_urls.clone(), ..Default::default() };
|
||||
super::attributes::fill_info(d, &mut info);
|
||||
for (fill, item, ids) in aims(s, p, C, [true, false])? {
|
||||
for (fill, item, ids) in aims(s, p, C, [true, false], false)? {
|
||||
let mut all =
|
||||
ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| Some(flags(n, fill, item.resolve(&n.appearance, fill, C).ok()?))).flatten();
|
||||
let same = all.next().and_then(|first| all.all(|b| b == first).then_some(first));
|
||||
|
||||
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Invert",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -982,7 +982,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option<usize>
|
||||
}
|
||||
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
|
||||
let targets = paint_targets(s, p)?;
|
||||
let given = !targets.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
// Only design art was given or selected: nothing changes, the defaults included.
|
||||
if given && ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
@@ -1017,7 +1023,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
|
||||
let targets = paint_targets(s, p)?;
|
||||
let given = !targets.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
// Only design art was given or selected: nothing changes, the defaults included.
|
||||
if given && ids.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
// When every object comes out as it was, the document and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
@@ -1086,10 +1098,26 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
return Ok(json!({ "changed": changed as usize }));
|
||||
}
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
|
||||
// no row for) is still an error.
|
||||
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
|
||||
let of = match item {
|
||||
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
|
||||
ItemTarget::Top => None,
|
||||
};
|
||||
// Read before the check below too: `targets` reads no `target` for the topmost fill or stroke.
|
||||
let contents = super::appearance::targets_contents(p)?;
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
// Only design art was given or selected: nothing changes, the defaults and remembered colors included.
|
||||
if ids.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let (r, shown_at) = match item {
|
||||
ItemTarget::Item { .. } => {
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
// Only design art was given or selected: nothing changes, the remembered colors included.
|
||||
if targets.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
// The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row.
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it {
|
||||
ItemTarget::Item { index, .. } => Some((id, Some(index))),
|
||||
@@ -1105,9 +1133,56 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
(json!({ "changed": changed }), shown_at)
|
||||
}
|
||||
// The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles.
|
||||
// A given group's own fills and strokes change with the objects inside it, except with `target: "contents"`; other
|
||||
// objects change as their paint targets do (a compound path's member stands for the compound path). Design art
|
||||
// inside a given graph or series group is left out.
|
||||
ItemTarget::Top => {
|
||||
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
|
||||
(super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None)))
|
||||
let mut roots = vec![];
|
||||
for id in &ids {
|
||||
let n = s.doc()?.doc.node(*id);
|
||||
let group =
|
||||
!contents && n.is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape());
|
||||
if group {
|
||||
roots.push(*id);
|
||||
} else {
|
||||
roots.extend(leaf_targets(s, &[*id])?);
|
||||
}
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
roots.retain(|id| seen.insert(*id));
|
||||
let roots = super::appearance::drop_design_art(d, roots);
|
||||
if roots.is_empty() {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let art = super::appearance::design_art_in(d, &roots).into_iter().collect();
|
||||
// The fill or stroke the proxy shows of each group among the roots, before the edit.
|
||||
let own = |d: &Document, id: NodeId| {
|
||||
d.node(id)
|
||||
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
|
||||
.and_then(|n| n.proxy_paint_only(stroke, None))
|
||||
.cloned()
|
||||
};
|
||||
let own_before: std::collections::HashMap<NodeId, Paint> = roots.iter().filter_map(|id| Some((*id, own(d, *id)?))).collect();
|
||||
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>()});
|
||||
let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?;
|
||||
// As the proxy shows a group: its own fill or stroke when the edit changed it, else the first object inside it
|
||||
// that is not design art (which keeps its paint). The first object given that has either shows it.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut shown_at = None;
|
||||
for id in &ids {
|
||||
if let Some(was) = own_before.get(id)
|
||||
&& own(d, *id).as_ref() != Some(was)
|
||||
{
|
||||
shown_at = Some((*id, None));
|
||||
break;
|
||||
}
|
||||
if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() {
|
||||
shown_at = Some((*leaf, None));
|
||||
break;
|
||||
}
|
||||
}
|
||||
(r, shown_at)
|
||||
}
|
||||
};
|
||||
// The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none.
|
||||
|
||||
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character / Paragraph",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent
Line truncated
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tent
Line truncated
|
||||
has_doc,
|
||||
set_format
|
||||
),
|
||||
|
||||
@@ -71,6 +71,8 @@ const MAX_QUEUE: usize = 100;
|
||||
const MAX_THUMBNAIL: f64 = 512.0;
|
||||
/// A text file's natural box (`file.place.info`, the place cursor): a letter page less 1 in margins.
|
||||
const TEXT_FRAME: Rect = Rect::new(0.0, 0.0, 468.0, 648.0);
|
||||
/// An encrypted PDF's box in the place cursor, which reads it without its password: a letter page.
|
||||
const LOCKED_PAGE: Rect = Rect::new(0.0, 0.0, 612.0, 792.0);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -79,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot p
Line truncated
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -106,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load Place Cursor",
|
||||
[],
|
||||
None,
|
||||
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}",
|
||||
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, importSlices?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last; an encrypted PDF, .ai or .ait file stays in the cursor at 612 × 792 pt (VectorCraft's own size) with needsPassword: true and no thumbnail, and a click on it in the app asks for its password (headless, its file.place fails for want of the password) → {count, files: [{name, format, width, height, thumbnailBase64?, needsPassword?}], skipped: [{name, error}]}",
|
||||
has_doc,
|
||||
queue
|
||||
),
|
||||
@@ -988,6 +990,14 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
}
|
||||
Err(e) => {
|
||||
let name = str_param(&q, "path").or(str_param(&q, "name")).map(fileio::file_name).unwrap_or_default();
|
||||
// An encrypted PDF stays, at a size of its own, so that a click in the app can ask
|
||||
// for its password.
|
||||
if let Some(format) = locked_pdf(&q, &e) {
|
||||
let (w, h) = (LOCKED_PAGE.width(), LOCKED_PAGE.height());
|
||||
files.push(json!({ "name": name, "format": format, "width": w, "height": h, "needsPassword": true }));
|
||||
entries.push(json!({ "params": q, "name": name, "width": w, "height": h }));
|
||||
continue;
|
||||
}
|
||||
skipped.push(json!({ "name": name, "error": e.to_string() }));
|
||||
}
|
||||
}
|
||||
@@ -995,6 +1005,22 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
Ok(QueueRead { doc, params: p, entries, files, skipped })
|
||||
}
|
||||
|
||||
/// The format id of the file `q` names when it is a PDF, `.ai` or `.ait` file (a path with one of
|
||||
/// those extensions, as the app's password dialog reads it) that opens only with a password, and
|
||||
/// reading it failed with `e` for want of that password (not for a bad option).
|
||||
fn locked_pdf(q: &Value, e: &EngineError) -> Option<&'static str> {
|
||||
if !e.to_string().contains(&vectorcraft_pdf::PdfError::NeedsPassword.to_string()) {
|
||||
return None;
|
||||
}
|
||||
let src = fileio::source(q, QUEUE).ok()?;
|
||||
if src.path.is_some() && !matches!(fileio::extension(src.name).as_str(), "pdf" | "ai" | "ait") {
|
||||
return None;
|
||||
}
|
||||
let format = fileio::detect(src.name, &src.bytes)?;
|
||||
let locked = matches!(vectorcraft_pdf::open_pdf(&src.bytes, None).map(|_| ()), Err(vectorcraft_pdf::PdfError::NeedsPassword));
|
||||
(matches!(format.id, "pdf" | "ai" | "ait") && locked).then_some(format.id)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// `file.place.queue`'s checks (with no document open, the error `file.place.queue` gives) of
|
||||
/// `params` → what reads the files ([`QueueJob::read`]; on the
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use roxmltree::Node;
|
||||
use craft_xml::{Canonical, Doctype, El, Limits, Names, Options};
|
||||
use vectorcraft_doc::text::Kashida;
|
||||
use vectorcraft_doc::{CharPosition, CharStyle, Justify, ParaDirection, ParaStyle, ScriptMetrics, TextRun};
|
||||
|
||||
@@ -88,6 +88,7 @@ const MAX_RUNS: usize = 100_000;
|
||||
|
||||
/// WordprocessingML's namespaces: Transitional, then Strict.
|
||||
const W: [&str; 2] = ["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"];
|
||||
const DOCX_NS: Canonical<'static> = Canonical::new(&[("w", W[0]), ("w", W[1])]);
|
||||
|
||||
/// Is the file `name` with `bytes` a Word document: a ZIP archive named `.docx`, or one that holds
|
||||
/// `word/document.xml`?
|
||||
@@ -104,7 +105,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> {
|
||||
let main = relationship(&zip, "", "officeDocument", cmd)?.unwrap_or_else(|| "word/document.xml".into());
|
||||
let Some(xml) = part(&zip, &main, cmd)? else { return Err(bad(cmd, "not a Word document: its package has no main document part")) };
|
||||
let doc = parse(&xml, &main, cmd)?;
|
||||
if local(doc.root_element()) != Some("document") {
|
||||
if local(&doc) != Some("document") {
|
||||
return Err(bad(cmd, "not a Word document: its main part is not a WordprocessingML document"));
|
||||
}
|
||||
let folder = main.rfind('/').and_then(|i| main.get(..=i)).unwrap_or_default();
|
||||
@@ -117,7 +118,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> {
|
||||
if let Some(xml) = part(&zip, &styles, cmd)? {
|
||||
r.styles(&parse(&xml, &styles, cmd)?);
|
||||
}
|
||||
if let Some(body) = doc.root_element().children().find(|n| local(*n) == Some("body")) {
|
||||
if let Some(body) = child(&doc, "body") {
|
||||
r.block(body, 0);
|
||||
}
|
||||
r.finish(cmd)
|
||||
@@ -158,57 +159,21 @@ fn part(zip: &Archive, name: &str, cmd: &str) -> Result<Option<String>> {
|
||||
}
|
||||
|
||||
/// The XML of the part `name`.
|
||||
fn parse<'a>(xml: &'a str, name: &str, cmd: &str) -> Result<roxmltree::Document<'a>> {
|
||||
// roxmltree parses nested elements recursively.
|
||||
if nesting(xml) > MAX_NESTING {
|
||||
return Err(bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")));
|
||||
fn parse(xml: &str, name: &str, cmd: &str) -> Result<El> {
|
||||
let opts = Options {
|
||||
names: Names::Canonical(&DOCX_NS),
|
||||
doctype: Doctype::Reject,
|
||||
limits: Limits { max_depth: MAX_NESTING, max_nodes: MAX_NODES as usize, ..Limits::DEFAULT },
|
||||
..Options::default()
|
||||
}
|
||||
let opts = roxmltree::ParsingOptions { nodes_limit: MAX_NODES, ..roxmltree::ParsingOptions::default() };
|
||||
roxmltree::Document::parse_with_options(xml, opts).map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))
|
||||
}
|
||||
|
||||
/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments,
|
||||
/// CDATA sections, processing instructions, declarations and quoted attribute values.
|
||||
pub(crate) fn nesting(xml: &str) -> usize {
|
||||
let b = xml.as_bytes();
|
||||
let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize);
|
||||
// The index just past the first `end` at or after `from` (the end of the text if none).
|
||||
let past = |from: usize, end: &[u8]| {
|
||||
b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len())
|
||||
};
|
||||
while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) {
|
||||
let start = i + at;
|
||||
let rest = b.get(start..).unwrap_or_default();
|
||||
if rest.starts_with(b"<!--") {
|
||||
i = past(start + 4, b"-->");
|
||||
} else if rest.starts_with(b"<![CDATA[") {
|
||||
i = past(start + 9, b"]]>");
|
||||
} else if rest.starts_with(b"<?") {
|
||||
i = past(start + 2, b"?>");
|
||||
} else if rest.starts_with(b"<!") || rest.starts_with(b"</") {
|
||||
depth = depth.saturating_sub(usize::from(rest.starts_with(b"</")));
|
||||
i = past(start + 2, b">");
|
||||
} else {
|
||||
// A start tag: up to its `>` outside quotes; `/>` closes it at once.
|
||||
let mut j = start + 1;
|
||||
let mut quote = None;
|
||||
while let Some(&c) = b.get(j) {
|
||||
match (quote, c) {
|
||||
(None, b'"' | b'\'') => quote = Some(c),
|
||||
(Some(q), _) if c == q => quote = None,
|
||||
(None, b'>') => break,
|
||||
_ => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if b.get(j.saturating_sub(1)) != Some(&b'/') {
|
||||
depth += 1;
|
||||
most = most.max(depth);
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
most
|
||||
.strict();
|
||||
let doc = opts.parse(xml.as_bytes()).map_err(|e| match e {
|
||||
craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")),
|
||||
_ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")),
|
||||
})?;
|
||||
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits)
|
||||
.map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?;
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// The part that the first relationship of part `source` (`""`: the package) whose type ends in
|
||||
@@ -220,11 +185,10 @@ fn relationship(zip: &Archive, source: &str, kind: &str, cmd: &str) -> Result<Op
|
||||
let Some(xml) = part(zip, &rels, cmd)? else { return Ok(None) };
|
||||
let doc = parse(&xml, &rels, cmd)?;
|
||||
let target = doc
|
||||
.root_element()
|
||||
.children()
|
||||
.filter(|n| n.tag_name().name() == "Relationship" && n.attribute("TargetMode") != Some("External"))
|
||||
.find(|n| n.attribute("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind)))
|
||||
.and_then(|n| n.attribute("Target"));
|
||||
.elements()
|
||||
.filter(|n| n.local() == "Relationship" && n.attr("TargetMode") != Some("External"))
|
||||
.find(|n| n.attr("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind)))
|
||||
.and_then(|n| n.attr("Target"));
|
||||
Ok(target.map(|t| resolve(folder, t)))
|
||||
}
|
||||
|
||||
@@ -248,22 +212,22 @@ fn resolve(folder: &str, target: &str) -> String {
|
||||
}
|
||||
|
||||
/// `n`'s local name when it is a WordprocessingML element.
|
||||
fn local<'a>(n: Node<'a, '_>) -> Option<&'a str> {
|
||||
(n.is_element() && n.tag_name().namespace().is_some_and(|ns| W.contains(&ns))).then(|| n.tag_name().name())
|
||||
fn local(n: &El) -> Option<&str> {
|
||||
n.name.strip_prefix("w:")
|
||||
}
|
||||
|
||||
/// `n`'s first WordprocessingML child element named `name`.
|
||||
fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option<Node<'a, 'i>> {
|
||||
n.children().find(|c| local(*c) == Some(name))
|
||||
fn child<'a>(n: &'a El, name: &str) -> Option<&'a El> {
|
||||
n.elements().find(|c| local(c) == Some(name))
|
||||
}
|
||||
|
||||
/// `n`'s WordprocessingML attribute `name`.
|
||||
fn attr<'a>(n: Node<'a, '_>, name: &str) -> Option<&'a str> {
|
||||
n.attributes().find(|a| a.name() == name && a.namespace().is_some_and(|ns| W.contains(&ns))).map(|a| a.value())
|
||||
fn attr<'a>(n: &'a El, name: &str) -> Option<&'a str> {
|
||||
n.attrs.iter().find_map(|(k, v)| k.strip_prefix("w:").filter(|&l| l == name).map(|_| v.as_str()))
|
||||
}
|
||||
|
||||
/// An on/off property (ST_OnOff): on unless `w:val` is `false`, `0` or `off`.
|
||||
fn on(n: Node) -> bool {
|
||||
fn on(n: &El) -> bool {
|
||||
!matches!(attr(n, "val"), Some("false" | "0" | "off"))
|
||||
}
|
||||
|
||||
@@ -280,12 +244,12 @@ fn measure(v: &str, per_pt: f64) -> Option<f64> {
|
||||
}
|
||||
|
||||
/// Twentieths of a point.
|
||||
fn twips(n: Node, name: &str) -> Option<f64> {
|
||||
fn twips(n: &El, name: &str) -> Option<f64> {
|
||||
attr(n, name).and_then(|v| measure(v, 20.0))
|
||||
}
|
||||
|
||||
/// Half points.
|
||||
fn half_points(n: Node) -> Option<f64> {
|
||||
fn half_points(n: &El) -> Option<f64> {
|
||||
attr(n, "val").and_then(|v| measure(v, 2.0))
|
||||
}
|
||||
|
||||
@@ -462,21 +426,21 @@ struct Reader {
|
||||
|
||||
impl Reader {
|
||||
/// The major and minor fonts of a theme part's font scheme.
|
||||
fn theme_fonts(&mut self, doc: &roxmltree::Document) {
|
||||
fn theme_fonts(&mut self, doc: &El) {
|
||||
for (slot, scheme) in self.theme.iter_mut().zip(["majorFont", "minorFont"]) {
|
||||
*slot = doc
|
||||
.descendants()
|
||||
.find(|n| n.tag_name().name() == scheme)
|
||||
.and_then(|n| n.children().find(|c| c.tag_name().name() == "latin"))
|
||||
.and_then(|n| n.attribute("typeface"))
|
||||
*slot = std::iter::once(doc)
|
||||
.chain(doc.descendants())
|
||||
.find(|n| n.local() == scheme)
|
||||
.and_then(|n| n.elements().find(|c| c.local() == "latin"))
|
||||
.and_then(|n| n.attr("typeface"))
|
||||
.map(font_name)
|
||||
.filter(|f| !f.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// The document defaults and the styles of the styles part.
|
||||
fn styles(&mut self, doc: &roxmltree::Document) {
|
||||
for n in doc.root_element().children() {
|
||||
fn styles(&mut self, doc: &El) {
|
||||
for n in doc.elements() {
|
||||
match local(n) {
|
||||
Some("docDefaults") => {
|
||||
let props = |outer: &str, inner: &str| child(n, outer).and_then(|d| child(d, inner));
|
||||
@@ -526,7 +490,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The number of the font a `w:rFonts` element names.
|
||||
fn font(&mut self, n: Node) -> Option<usize> {
|
||||
fn font(&mut self, n: &El) -> Option<usize> {
|
||||
let theme = |v: &str| self.theme.get(usize::from(v.starts_with("minor"))).and_then(Option::as_deref);
|
||||
let name = attr(n, "asciiTheme")
|
||||
.and_then(theme)
|
||||
@@ -549,9 +513,9 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The run properties of a `w:rPr` element.
|
||||
fn run_props(&mut self, rpr: Node) -> RunProps {
|
||||
fn run_props(&mut self, rpr: &El) -> RunProps {
|
||||
let mut p = RunProps::default();
|
||||
for n in rpr.children() {
|
||||
for n in rpr.elements() {
|
||||
match local(n) {
|
||||
Some("rFonts") => p.font = self.font(n),
|
||||
Some("b") => p.bold = Some(on(n)),
|
||||
@@ -594,11 +558,11 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The paragraphs, tables and containers of them that are `n`'s children.
|
||||
fn block(&mut self, n: Node, depth: usize) {
|
||||
fn block(&mut self, n: &El, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
if self.full {
|
||||
return;
|
||||
}
|
||||
@@ -617,7 +581,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A table: each row a paragraph, its cells separated by tabs.
|
||||
fn table(&mut self, tbl: Node, depth: usize) {
|
||||
fn table(&mut self, tbl: &El, depth: usize) {
|
||||
for row in items(tbl, "tr", depth) {
|
||||
for cell in items(row, "tc", depth) {
|
||||
self.flush();
|
||||
@@ -638,7 +602,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A paragraph.
|
||||
fn paragraph(&mut self, p: Node, depth: usize) {
|
||||
fn paragraph(&mut self, p: &El, depth: usize) {
|
||||
self.flush();
|
||||
let ppr = child(p, "pPr");
|
||||
let style = ppr
|
||||
@@ -675,11 +639,11 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The runs of a paragraph, and the containers of runs in it.
|
||||
fn inline(&mut self, n: Node, depth: usize) {
|
||||
fn inline(&mut self, n: &El, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
match local(c) {
|
||||
Some("r") => self.run(c),
|
||||
Some("hyperlink" | "ins" | "moveTo" | "smartTag" | "customXml" | "fldSimple" | "dir" | "bdo") => self.inline(c, depth + 1),
|
||||
@@ -694,7 +658,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A run.
|
||||
fn run(&mut self, r: Node) {
|
||||
fn run(&mut self, r: &El) {
|
||||
let rpr = child(r, "rPr");
|
||||
let mut chars = self.base;
|
||||
let style = rpr
|
||||
@@ -709,11 +673,10 @@ impl Reader {
|
||||
let props = self.run_props(n);
|
||||
chars.apply(&props, false);
|
||||
}
|
||||
for c in r.children() {
|
||||
for c in r.elements() {
|
||||
match local(c) {
|
||||
Some("t") => {
|
||||
// Comments and processing instructions may split the text.
|
||||
for ch in c.children().filter(|n| n.is_text()).filter_map(|n| n.text()).flat_map(str::chars) {
|
||||
for ch in c.text().chars() {
|
||||
self.put(ch, chars);
|
||||
}
|
||||
}
|
||||
@@ -907,9 +870,9 @@ fn font_name(name: &str) -> String {
|
||||
}
|
||||
|
||||
/// The paragraph properties of a `w:pPr` element.
|
||||
fn para_props(ppr: Node) -> ParaProps {
|
||||
fn para_props(ppr: &El) -> ParaProps {
|
||||
let mut p = ParaProps::default();
|
||||
for n in ppr.children() {
|
||||
for n in ppr.elements() {
|
||||
match local(n) {
|
||||
Some("jc") => {
|
||||
p.align = match attr(n, "val") {
|
||||
@@ -945,12 +908,12 @@ fn para_props(ppr: Node) -> ParaProps {
|
||||
}
|
||||
|
||||
/// `n`'s children named `name`, and those inside content controls and custom XML among them.
|
||||
fn items<'a, 'i>(n: Node<'a, 'i>, name: &str, depth: usize) -> Vec<Node<'a, 'i>> {
|
||||
fn items<'a>(n: &'a El, name: &str, depth: usize) -> Vec<&'a El> {
|
||||
let mut out = vec![];
|
||||
if depth > MAX_DEPTH {
|
||||
return out;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
match local(c) {
|
||||
Some(l) if l == name => out.push(c),
|
||||
Some("sdt") => {
|
||||
@@ -979,15 +942,6 @@ mod tests {
|
||||
assert_eq!(measure("wide", 20.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_counts_elements_outside_markup_that_is_not_an_element() {
|
||||
assert_eq!(nesting(r#"<?xml version="1.0"?><a><b x="1>2" y='</c>'><c/></b><!-- <d><e> --><![CDATA[<f><g>]]></a>"#), 2);
|
||||
assert_eq!(nesting("<a><b><c>"), 3, "unclosed elements count");
|
||||
assert_eq!(nesting("</a></b><a>"), 1);
|
||||
assert_eq!(nesting("<a x=\"unterminated"), 1);
|
||||
assert_eq!(nesting(""), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_resolve_against_their_folder() {
|
||||
assert_eq!(resolve("", "word/document.xml"), "word/document.xml");
|
||||
|
||||
@@ -234,8 +234,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let item = item_target(s, p, C)?.of_kind(s, false);
|
||||
let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? };
|
||||
let new_art = no_targets(&ids, p);
|
||||
let given = !ids.is_empty();
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
|
||||
// With only design art, the weight for new art stays as it is too.
|
||||
let only_design_art = given && ids.is_empty();
|
||||
if item == ItemTarget::Top {
|
||||
// Images and symbol instances take no stroke from the panel.
|
||||
let d = &s.doc()?.doc;
|
||||
@@ -329,7 +332,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
// Commit the new-art template only after the complete request is validated
|
||||
// and the selected artwork edit has succeeded.
|
||||
if let Some(w) = change.weight {
|
||||
if let Some(w) = change.weight
|
||||
&& !only_design_art
|
||||
{
|
||||
s.paint.stroke_width = w;
|
||||
}
|
||||
if new_art && let Some(st) = s.new_art_stroke_mut() {
|
||||
@@ -372,7 +377,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
|
||||
}
|
||||
return Ok(json!({"objects": 0}));
|
||||
}
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, c)?;
|
||||
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
|
||||
edit_items(s, &ids, item, None, c, label, false, |n, index| {
|
||||
if index.is_none()
|
||||
@@ -517,7 +522,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = item.targets(s, p)?;
|
||||
let new_art = no_targets(&ids, p);
|
||||
// The art of a graph design in a series keeps the design's stroke.
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
|
||||
let arrows_and_profile = |st: &mut StrokeLayer| {
|
||||
if let Some(sc) = scale {
|
||||
st.arrow_scale = sc;
|
||||
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away in horizontal type, the glyph keeping its shape; 100 sets the ink edge to edge; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes
Line truncated
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a
Line truncated
|
||||
has_doc,
|
||||
set_range_style
|
||||
),
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the
|
||||
//! variables and data sets of a variable library, the XML file of the reference app's Save
|
||||
//! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one.
|
||||
//! `variable.import` (the panel's Import…) runs one of the two readers by the file's extension.
|
||||
//! Agents reach every command through `run_command`, like all engine commands.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -865,6 +866,22 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result<Value> {
|
||||
apply_dataset(s, &name)
|
||||
}
|
||||
|
||||
/// The Variables panel's Import…: a data source file read by its extension, a CSV, TSV or TXT
|
||||
/// file as `dataset.import` reads it and an XML file as `variable.loadLibrary` reads it. The
|
||||
/// result is that command's, with `format` set to `csv` or `xml`.
|
||||
fn variable_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.import";
|
||||
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
|
||||
let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
let (format, mut out) = match ext.as_deref() {
|
||||
Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?),
|
||||
Some("xml") => ("xml", load_library(s, &json!({"path": path}))?),
|
||||
_ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")),
|
||||
};
|
||||
out["format"] = json!(format);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -1057,6 +1074,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
dataset_import
|
||||
),
|
||||
cmd!(
|
||||
"variable.import",
|
||||
"Import…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`",
|
||||
has_doc,
|
||||
variable_import
|
||||
),
|
||||
cmd!(
|
||||
query "dataset.export",
|
||||
"Export Data Sets…",
|
||||
|
||||
@@ -60,8 +60,8 @@ fn library_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> {
|
||||
/// up to [`MAX_LIBRARY_ENTITIES`] entity declarations, each with a name of at most [`MAX_NAME`]
|
||||
/// bytes and a quoted value that holds no `<`, `&` or `%`. Anything else in it is refused, and so is
|
||||
/// a text that the replacements make longer than [`MAX_LIBRARY_BYTES`]. The XML parser then refuses
|
||||
/// any other document type declaration, so [`nesting`](super::place::docx::nesting) counts the
|
||||
/// elements the parser reads.
|
||||
/// any other document type declaration, so its depth and node limits count the elements it
|
||||
/// reads.
|
||||
fn without_doctype(xml: &str, cmd: &str) -> Result<String> {
|
||||
let b = xml.as_bytes();
|
||||
let past = |from: usize, end: &str| xml.get(from..).and_then(|rest| rest.find(end)).map(|at| from + at + end.len());
|
||||
@@ -240,22 +240,25 @@ impl Library {
|
||||
/// type declaration defines are read as [`without_doctype`] says.
|
||||
fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
let xml = without_doctype(xml, cmd)?;
|
||||
// roxmltree parses nested elements recursively.
|
||||
if crate::cmd::place::docx::nesting(&xml) > MAX_LIBRARY_NESTING {
|
||||
return Err(bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")));
|
||||
let opts = craft_xml::Options {
|
||||
names: craft_xml::Names::AsWritten,
|
||||
limits: craft_xml::Limits { max_depth: MAX_LIBRARY_NESTING, max_nodes: MAX_LIBRARY_NODES as usize, ..craft_xml::Limits::DEFAULT },
|
||||
..craft_xml::Options::default()
|
||||
}
|
||||
let opts = roxmltree::ParsingOptions { nodes_limit: MAX_LIBRARY_NODES, ..roxmltree::ParsingOptions::default() };
|
||||
let doc =
|
||||
roxmltree::Document::parse_with_options(&xml, opts).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?;
|
||||
let is = |n: &roxmltree::Node, name: &str| n.is_element() && n.tag_name().name() == name;
|
||||
let Some(root) = doc.descendants().find(|n| is(n, "variableSets")) else {
|
||||
.strict();
|
||||
let doc = opts.parse(xml.as_bytes()).map_err(|e| match e {
|
||||
craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")),
|
||||
_ => bad(cmd, format!("the variable library is not well-formed XML: {e}")),
|
||||
})?;
|
||||
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?;
|
||||
let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else {
|
||||
return Err(bad(cmd, "the file holds no `variableSets` element"));
|
||||
};
|
||||
let sets: Vec<roxmltree::Node> = root.children().filter(|n| is(n, "variableSet")).collect();
|
||||
let sets: Vec<&craft_xml::El> = root.children(craft_xml::Local("variableSet")).collect();
|
||||
let (mut variables, mut kinds, mut refs) = (Vec::new(), BTreeMap::new(), Vec::new());
|
||||
for var in sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "variables")).flat_map(|v| v.children()).filter(|n| is(n, "variable")) {
|
||||
let name = named(var.attribute("varName"), "varName", cmd)?;
|
||||
let trait_name = var.attribute("trait").map(|t| t.chars().take(MAX_NAME).collect::<String>());
|
||||
for var in sets.iter().flat_map(|s| s.children(craft_xml::Local("variables"))).flat_map(|v| v.children(craft_xml::Local("variable"))) {
|
||||
let name = named(var.attr("varName"), "varName", cmd)?;
|
||||
let trait_name = var.attr("trait").map(|t| t.chars().take(MAX_NAME).collect::<String>());
|
||||
let kind = trait_kind(trait_name.as_deref());
|
||||
if kinds.insert(name.clone(), kind).is_some() {
|
||||
return Err(bad(cmd, format!("variable `{name}` is declared twice")));
|
||||
@@ -265,7 +268,7 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
}
|
||||
if kind == VariableKind::Text {
|
||||
// `docRef="id('…')"` names the element of the variable's bound object.
|
||||
let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty());
|
||||
let element = var.attr("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty());
|
||||
if let Some(element) = element {
|
||||
refs.push((name.clone(), element.to_string()));
|
||||
}
|
||||
@@ -276,10 +279,8 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
return Err(bad(cmd, "the variable library declares no variables"));
|
||||
}
|
||||
let (mut datasets, mut seen) = (Vec::new(), BTreeSet::new());
|
||||
for row in
|
||||
sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "sampleDataSets")).flat_map(|d| d.children()).filter(|n| is(n, "sampleDataSet"))
|
||||
{
|
||||
let name = named(row.attribute("dataSetName"), "dataSetName", cmd)?;
|
||||
for row in sets.iter().flat_map(|s| s.children(craft_xml::Local("sampleDataSets"))).flat_map(|d| d.children(craft_xml::Local("sampleDataSet"))) {
|
||||
let name = named(row.attr("dataSetName"), "dataSetName", cmd)?;
|
||||
if !seen.insert(name.clone()) {
|
||||
return Err(bad(cmd, format!("data set `{name}` is declared twice")));
|
||||
}
|
||||
@@ -287,8 +288,8 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
return Err(bad(cmd, format!("the variable library declares more than {MAX_LIBRARY_DATASETS} data sets")));
|
||||
}
|
||||
let (mut values, mut held) = (BTreeMap::new(), BTreeSet::new());
|
||||
for el in row.children().filter(roxmltree::Node::is_element) {
|
||||
let var = el.tag_name().name();
|
||||
for el in row.elements() {
|
||||
let var = el.local();
|
||||
let Some(kind) = kinds.get(var) else {
|
||||
return Err(bad(cmd, format!("data set `{name}` holds a value for `{var}`, which the library doesn't declare")));
|
||||
};
|
||||
@@ -315,12 +316,12 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
/// white space round them, and an element holding only white space gives none. A variable of
|
||||
/// unknown kind takes no value, so what its element holds is passed over. `set` names the data set
|
||||
/// in the errors.
|
||||
fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.tag_name().name()));
|
||||
let text = || if elements(el).next().is_some() { None } else { Some(deep_text(el)) };
|
||||
fn library_value(el: &craft_xml::El, kind: VariableKind, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.local()));
|
||||
let text = || if el.elements().next().is_some() { None } else { Some(el.deep_text()) };
|
||||
match kind {
|
||||
VariableKind::Text => {
|
||||
let paras: Vec<String> = elements(el).filter(|n| n.tag_name().name() == "p").map(deep_text).collect();
|
||||
let paras: Vec<String> = el.children(craft_xml::Local("p")).map(craft_xml::El::deep_text).collect();
|
||||
Ok((!paras.is_empty()).then(|| DataValue::Text(paras.join("\n"))))
|
||||
}
|
||||
VariableKind::Visibility => {
|
||||
@@ -346,16 +347,6 @@ fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str)
|
||||
}
|
||||
}
|
||||
|
||||
/// The elements among `n`'s children.
|
||||
fn elements<'a, 'i>(n: roxmltree::Node<'a, 'i>) -> impl Iterator<Item = roxmltree::Node<'a, 'i>> {
|
||||
n.children().filter(roxmltree::Node::is_element)
|
||||
}
|
||||
|
||||
/// The text of every text node inside `n`, in order.
|
||||
fn deep_text(n: roxmltree::Node) -> String {
|
||||
n.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect()
|
||||
}
|
||||
|
||||
/// The absolute path a library's image value `text` names: a `file:` URL's path (`file:///…`,
|
||||
/// `file://localhost/…` or `file:/…`), its `%XX` escapes decoded (a URL with a host names a share,
|
||||
/// `//host/…`), or `text` itself. `None` unless that is an absolute path: one starting with `/` or
|
||||
@@ -428,29 +419,28 @@ fn library_file(path: &str) -> String {
|
||||
/// series, or when `el` holds only white space, there is no value. Anything else in `el`, more than
|
||||
/// [`MAX_GRAPH_CATEGORIES`] rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), and CSV longer
|
||||
/// than graph values hold, are refused.
|
||||
fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let var = el.tag_name().name();
|
||||
fn graph_value(el: &craft_xml::El, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let var = el.local();
|
||||
let refused = || bad(cmd, format!("data set `{set}` holds a value for `{var}` that isn't a graph's `data` element"));
|
||||
let named = |name: &'static str| move |n: &roxmltree::Node| n.tag_name().name() == name;
|
||||
let mut children = elements(el);
|
||||
let named = |name: &'static str| craft_xml::Local(name);
|
||||
let mut children = el.elements();
|
||||
let data = match (children.next(), children.next()) {
|
||||
(None, _) if deep_text(el).trim_matches(XML_SPACE).is_empty() => return Ok(None),
|
||||
(Some(data), None) if data.tag_name().name() == "data" => data,
|
||||
(None, _) if el.deep_text().trim_matches(XML_SPACE).is_empty() => return Ok(None),
|
||||
(Some(data), None) if data.local() == "data" => data,
|
||||
_ => return Err(refused()),
|
||||
};
|
||||
// Labels keep their white space; numbers are read without it.
|
||||
let series: Vec<String> =
|
||||
elements(data).find(named("propertyRow")).map(|r| elements(r).filter(named("value")).skip(1).map(deep_text).collect()).unwrap_or_default();
|
||||
let rows: Vec<roxmltree::Node> =
|
||||
elements(data).filter(named("values")).flat_map(elements).filter(named("row")).take(MAX_GRAPH_CATEGORIES + 1).collect();
|
||||
data.child(named("propertyRow")).map(|r| r.children(named("value")).skip(1).map(craft_xml::El::deep_text).collect()).unwrap_or_default();
|
||||
let rows: Vec<&craft_xml::El> = data.children(named("values")).flat_map(|v| v.children(named("row"))).take(MAX_GRAPH_CATEGORIES + 1).collect();
|
||||
if rows.is_empty() && series.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let too_many = || bad(cmd, format!("data set `{set}` holds a graph value for `{var}` with {}", graph_limits()));
|
||||
// A row's values after its name.
|
||||
let wide = |row: &roxmltree::Node| {
|
||||
let mut values = elements(*row).filter(named("value")).peekable();
|
||||
let _name = values.next_if(|v| v.attribute("key") == Some("name"));
|
||||
let wide = |row: &&craft_xml::El| {
|
||||
let mut values = row.children(named("value")).peekable();
|
||||
let _name = values.next_if(|v| v.attr("key") == Some("name"));
|
||||
values.count() > MAX_GRAPH_SERIES
|
||||
};
|
||||
if rows.len() > MAX_GRAPH_CATEGORIES || series.len() > MAX_GRAPH_SERIES || rows.iter().any(wide) {
|
||||
@@ -462,12 +452,12 @@ fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result<Option<DataV
|
||||
let read: Vec<(Option<String>, Vec<Option<f64>>)> = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let mut values = elements(*row).filter(named("value")).peekable();
|
||||
let name = values.next_if(|v| v.attribute("key") == Some("name"));
|
||||
labelled |= name.is_some_and(|v| v.attribute("type") == Some("string") || !deep_text(v).is_empty());
|
||||
let name = name.map(deep_text);
|
||||
let number = |v: roxmltree::Node| deep_text(v).trim_matches(XML_SPACE).parse::<f64>().ok().filter(|n| n.is_finite());
|
||||
let numbers = values.map(|v| if v.attribute("type") == Some("string") { None } else { number(v) });
|
||||
let mut values = row.children(named("value")).peekable();
|
||||
let name = values.next_if(|v| v.attr("key") == Some("name"));
|
||||
labelled |= name.is_some_and(|v| v.attr("type") == Some("string") || !v.deep_text().is_empty());
|
||||
let name = name.map(craft_xml::El::deep_text);
|
||||
let number = |v: &craft_xml::El| v.deep_text().trim_matches(XML_SPACE).parse::<f64>().ok().filter(|n| n.is_finite());
|
||||
let numbers = values.map(|v| if v.attr("type") == Some("string") { None } else { number(v) });
|
||||
(name, numbers.collect())
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode.
|
||||
//!
|
||||
//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the
|
||||
//! shared strict reader and remove this second event pass when that dependency is updated.
|
||||
|
||||
/// Check names before canonical/local-name rewriting can collapse distinct attributes.
|
||||
/// The event reader and namespace scope use the same caller-supplied resource caps.
|
||||
pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict();
|
||||
let mut events = opts.events(xml);
|
||||
let mut bindings: Vec<(String, String)> = Vec::new();
|
||||
let mut scopes = Vec::new();
|
||||
while let Some(event) = events.next().map_err(|e| e.to_string())? {
|
||||
match event {
|
||||
craft_xml::Event::Start { attrs, .. } => {
|
||||
scopes.push(bindings.len());
|
||||
let mut raw = BTreeSet::new();
|
||||
for (key, value) in &attrs {
|
||||
if !raw.insert(key.as_str()) {
|
||||
return Err(format!("duplicate attribute `{key}`"));
|
||||
}
|
||||
if let Some(prefix) = key.strip_prefix("xmlns:") {
|
||||
if bindings.len() >= limits.max_attrs {
|
||||
return Err("too many in-scope namespace declarations".into());
|
||||
}
|
||||
bindings.push((prefix.to_string(), value.clone()));
|
||||
}
|
||||
}
|
||||
let mut expanded = BTreeSet::new();
|
||||
for (key, _) in &attrs {
|
||||
if key == "xmlns" || key.starts_with("xmlns:") {
|
||||
continue;
|
||||
}
|
||||
// Default namespaces do not apply to attributes. Preserve undeclared
|
||||
// prefixes for standalone SVG library fragments, as the importer did.
|
||||
let name = match key.split_once(':') {
|
||||
Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local),
|
||||
Some((prefix, local)) => {
|
||||
bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local))
|
||||
}
|
||||
None => ("", key.as_str()),
|
||||
};
|
||||
if !expanded.insert(name) {
|
||||
return Err(format!("duplicate expanded attribute `{key}`"));
|
||||
}
|
||||
}
|
||||
}
|
||||
craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -768,6 +768,84 @@ fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() {
|
||||
assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again");
|
||||
}
|
||||
|
||||
/// A pie pasted into a document whose swatch of the same name is another color takes that color on its linked wedges
|
||||
/// (Merge), and its legend labels in those wedges take the contrast a redraw gives them there: white on a wedge that
|
||||
/// turned dark. Pasting with Add, which keeps the copied color, keeps the labels as they were.
|
||||
#[test]
|
||||
fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() {
|
||||
let mut s = session();
|
||||
let csv = ",North,South\nP,1,1";
|
||||
s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap();
|
||||
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
|
||||
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
|
||||
/// The fill of the legend label of graph `id` that says `name`.
|
||||
fn label(s: &Session, id: NodeId, name: &str) -> Paint {
|
||||
let mut out = None;
|
||||
node(s, id).walk(&mut |n| {
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& t.plain_text() == name
|
||||
{
|
||||
out = Some(t.first_style().fill.clone());
|
||||
}
|
||||
});
|
||||
out.unwrap()
|
||||
}
|
||||
// The North wedge, black when drawn, takes the light Brand swatch, and a redraw sets its label black.
|
||||
let mut wedges = vec![];
|
||||
for c in node(&s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) {
|
||||
c.walk(&mut |m| {
|
||||
if matches!(m.kind, NodeKind::Path { .. }) {
|
||||
wedges.push(m.id.0);
|
||||
}
|
||||
});
|
||||
}
|
||||
assert!(!wedges.is_empty());
|
||||
s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
|
||||
assert_eq!(label(&s, g, "North"), Paint::solid(Color::BLACK), "black on the light wedge");
|
||||
assert_eq!(label(&s, g, "South"), Paint::solid(Color::BLACK));
|
||||
copy(&mut s, &[g]);
|
||||
|
||||
for (cmd, choice, north) in [
|
||||
("edit.pasteWithoutFormatting", "merge", Color::WHITE),
|
||||
("edit.paste", "merge", Color::WHITE),
|
||||
("edit.pasteWithoutFormatting", "add", Color::BLACK),
|
||||
("edit.paste", "add", Color::BLACK),
|
||||
] {
|
||||
new_doc(&mut s);
|
||||
s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap();
|
||||
let p = ids_of(&s.execute(cmd, &json!({"swatchConflict": choice})).unwrap())[0];
|
||||
assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}");
|
||||
assert_eq!(label(&s, p, "South"), Paint::solid(Color::BLACK), "{cmd} {choice}");
|
||||
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
|
||||
assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}: as a redraw sets it");
|
||||
}
|
||||
|
||||
// A copy of the pie in the opacity mask of a rectangle follows the same way.
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
let r = rect(&mut s, 10.0, 10.0, 300.0, 300.0);
|
||||
let art = {
|
||||
let d = doc_mut(&mut s);
|
||||
let pie = d.node(g).unwrap().clone();
|
||||
d.reid(&pie)
|
||||
};
|
||||
doc_mut(&mut s).node_mut(r).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true)));
|
||||
copy(&mut s, &[r]);
|
||||
new_doc(&mut s);
|
||||
s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap();
|
||||
let p = ids_of(&s.execute("edit.paste", &json!({"swatchConflict": "merge"})).unwrap())[0];
|
||||
let mask = node(&s, p).extras().mask.as_deref().unwrap().art.clone();
|
||||
let mut north = None;
|
||||
mask.walk(&mut |n| {
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& t.plain_text() == "North"
|
||||
{
|
||||
north = Some(t.first_style().fill.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask");
|
||||
}
|
||||
|
||||
/// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph
|
||||
/// is pasted without formatting.
|
||||
#[test]
|
||||
|
||||
@@ -2326,6 +2326,39 @@ fn smoothing_keeps_a_corner_between_curves() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Smooth drag over a corner of a path cut into very many short segments keeps it, however many
|
||||
/// segments twice the reach spans: an open path's 90° corner with legs of 2,000 segments 0.05 pt
|
||||
/// long at the default reach, and a corner of a 200 pt square cut into 0.25 pt segments with a 40 pt
|
||||
/// reach.
|
||||
#[test]
|
||||
fn smoothing_keeps_corners_on_a_path_of_many_short_segments() {
|
||||
let mut s = session();
|
||||
let (id, v, drag) = smooth_corner_path(&mut s, 90.0, 2000);
|
||||
smooth_pass(&mut s, &drag);
|
||||
let at = smooth_turn_at(&path(&s, id).subpaths[0], v);
|
||||
assert!(at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the open path's corner is kept: {at:?}");
|
||||
|
||||
let mut s = session();
|
||||
let ends = [Point::new(200.0, 200.0), Point::new(400.0, 200.0), Point::new(400.0, 400.0), Point::new(200.0, 400.0)];
|
||||
let mut anchors = vec![];
|
||||
for k in 0..4 {
|
||||
let (a, b) = (ends[k], ends[(k + 1) % 4]);
|
||||
anchors.extend((0..800).map(|j| {
|
||||
let p = a.lerp(b, f64::from(j) / 800.0);
|
||||
json!({"x": p.x, "y": p.y})
|
||||
}));
|
||||
}
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let v = ends[1];
|
||||
let mut drag: Vec<Point> = (0..8).map(|k| v - kurbo::Vec2::new(40.0 - 5.0 * f64::from(k), 0.0)).collect();
|
||||
drag.extend((0..=8).map(|k| v + kurbo::Vec2::new(0.0, 5.0 * f64::from(k))));
|
||||
let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 40, "fidelity": 2.5})).unwrap();
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
let at = smooth_turn_at(sp, v);
|
||||
assert!(sp.closed && at.is_some_and(|t| (t - 90.0).abs() < 0.01), "the square's corner is kept: {at:?}");
|
||||
}
|
||||
|
||||
/// A corner at the first anchor of the stretch a drag smooths, just out of its reach, keeps its
|
||||
/// place and its turn.
|
||||
#[test]
|
||||
|
||||
@@ -377,14 +377,15 @@ fn annotator_gestures_edit_the_gradient_as_single_undo_steps() {
|
||||
assert_eq!(stops.len(), 3);
|
||||
assert!((stops[1].offset - 0.3).abs() < 1e-6);
|
||||
assert_eq!(s.selected_stop(), Some(1));
|
||||
// Dragging the end handle changes only the end, as one undo step.
|
||||
// Dragging the end handle changes only the length (the end stays on the bar's line), as one
|
||||
// undo step.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
gesture(
|
||||
&mut s,
|
||||
&[(PointerKind::Down, 200.0, 150.0), (PointerKind::Drag, 210.0, 160.0), (PointerKind::Drag, 220.0, 170.0), (PointerKind::Up, 220.0, 170.0)],
|
||||
);
|
||||
let g = fill_geom(&s, id);
|
||||
assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 170.0)));
|
||||
assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 150.0)));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// The selected stop takes Delete ahead of edit.clear; the object stays.
|
||||
|
||||
@@ -2138,3 +2138,141 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read()
|
||||
confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's SVG of a placed document whose art links an image: the file draws that art
|
||||
/// and names the image's file, so a file outside the read roots refuses it and one inside them is
|
||||
/// written. Any output that names no file is written.
|
||||
#[test]
|
||||
fn confined_svg_output_checks_the_images_of_placed_documents() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-placed-away");
|
||||
let home = Folder::new("svg-placed-home");
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
for (photo, outside) in [(away.file("photo.png"), true), (home.file("photo.png"), false)] {
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let src = home.file("src.vectorcraft");
|
||||
let mut inner = session();
|
||||
place(&mut inner, &photo);
|
||||
save(&mut inner, &src);
|
||||
let mut s = session();
|
||||
place(&mut s, &src);
|
||||
let link = json!({"format": "svg", "images": "link"});
|
||||
assert!(svg_text(&s.execute("document.serialize", &link).unwrap()).contains(&photo), "the file names the placed art's image");
|
||||
for format in ["svg", "svgz"] {
|
||||
for images in ["link", "embed"] {
|
||||
let p = json!({"format": format, "images": images});
|
||||
// Embed writes the pixels the placed file holds.
|
||||
let names = svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo);
|
||||
assert_eq!(names, images == "link", "{p}");
|
||||
match confine(roots.as_ref(), || s.execute("document.serialize", &p)) {
|
||||
Ok(r) => assert!(!outside || !svg_text(&r).contains(&photo), "{p}: {}", svg_text(&r)),
|
||||
Err(e) => {
|
||||
assert!(outside && names, "{p}: {e}");
|
||||
assert!(e.to_string().contains("a linked image file is outside the read roots"), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if outside {
|
||||
let e = confine(roots.as_ref(), || s.execute("document.serialize", &link)).unwrap_err().to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots") && !e.contains("photo.png"), "{e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's SVG of a symbol holding a visible rectangle and a hidden linked image outside
|
||||
/// the read roots: the file leaves the hidden image out of the symbol and is written, unless hidden
|
||||
/// layers are kept, which writes the image and refuses the file.
|
||||
#[test]
|
||||
fn confined_svg_output_leaves_hidden_symbol_art_unchecked() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-symbol-hidden-away");
|
||||
let home = Folder::new("svg-symbol-hidden-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("object.hide", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mixed"})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
for format in ["svg", "svgz"] {
|
||||
let p = json!({"format": format, "images": "link"});
|
||||
assert!(!svg_text(&s.execute("document.serialize", &p).unwrap()).contains(&photo), "{p}");
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
|
||||
assert!(!text.contains(&photo), "{p}: {text}");
|
||||
let kept = json!({"format": format, "images": "link", "hiddenLayers": true});
|
||||
assert!(svg_text(&s.execute("document.serialize", &kept).unwrap()).contains(&photo), "{kept}");
|
||||
let e = confine(roots.as_ref(), || s.execute("document.serialize", &kept)).unwrap_err().to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{kept}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's SVG Tiny 1.2 of an object whose opacity mask is a linked image outside the
|
||||
/// read roots: the Tiny file leaves the mask out and is written; SVG 1.1 writes the mask and is
|
||||
/// refused.
|
||||
#[test]
|
||||
fn confined_svg_tiny_output_leaves_opacity_mask_images_unchecked() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-tiny-mask-away");
|
||||
let home = Folder::new("svg-tiny-mask-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [r, a.0]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
for format in ["svg", "svgz"] {
|
||||
let tiny = json!({"format": format, "images": "link", "profile": "tiny12"});
|
||||
assert!(!svg_text(&s.execute("document.serialize", &tiny).unwrap()).contains(&photo), "{tiny}");
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &tiny)).unwrap());
|
||||
assert!(!text.contains(&photo), "{tiny}: {text}");
|
||||
let full = json!({"format": format, "images": "link"});
|
||||
assert!(svg_text(&s.execute("document.serialize", &full).unwrap()).contains(&photo), "{full}");
|
||||
let e = confine(roots.as_ref(), || s.execute("document.serialize", &full)).unwrap_err().to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{full}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's SVG of a linked image outside the read roots, without pixels in the
|
||||
/// document, under Radial Blur: the file and the clipboard draw the rendered image in its place,
|
||||
/// name no file, and are written.
|
||||
#[test]
|
||||
fn confined_svg_output_checks_the_images_drawn_for_pixel_effects() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-flat-away");
|
||||
let home = Folder::new("svg-flat-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [a.0], "params": {"amount": 30, "quality": "draft"}})).unwrap();
|
||||
without_pixels(&mut s, a);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let clip =
|
||||
|s: &mut Session| confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap()["svg"].as_str().unwrap().to_string();
|
||||
assert!(!clip(&mut s).contains(&photo));
|
||||
assert!(confine(roots.as_ref(), || s.clipboard_svg()).is_some_and(|svg| !svg.contains(&photo)));
|
||||
for format in ["svg", "svgz"] {
|
||||
for images in ["link", "embed"] {
|
||||
let p = json!({"format": format, "images": images});
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
|
||||
assert!(!text.contains(&photo), "{p}: {text}");
|
||||
}
|
||||
}
|
||||
// Without the effect, the image names its file.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("effect.remove", &json!({"index": 0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.effects.is_empty());
|
||||
let e = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap_err().to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
|
||||
}
|
||||
@@ -706,3 +706,16 @@ fn a_marker_designs_art_in_a_series_keeps_its_paint() {
|
||||
s.execute("addon.color.fillToStroke", &json!({"ids": [series.id.0]})).unwrap();
|
||||
assert_eq!(design_strokes(&s), before, "the design's art keeps its paint");
|
||||
}
|
||||
|
||||
/// Invert given a member of a compound path inverts the compound path's fill, which the member stands for.
|
||||
#[test]
|
||||
fn invert_of_a_compound_member_inverts_the_compound_path() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s), rect(&mut s));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let comp = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [comp.0], "color": "#ff0000"})).unwrap();
|
||||
let member = node(&s, comp).children().into_iter().flatten().next().unwrap().id;
|
||||
s.execute("paint.invert", &json!({"ids": [member.0]})).unwrap();
|
||||
assert_eq!(node(&s, comp).appearance.fill_paint().color().unwrap().to_hex(), "#00ffff");
|
||||
}
|
||||
@@ -1101,6 +1101,35 @@ fn the_place_queue_skips_an_image_whose_pixels_cant_be_read() {
|
||||
assert_eq!(b.place_queue_read(read).unwrap(), r);
|
||||
}
|
||||
|
||||
/// An encrypted PDF stays in the place cursor's queue, read with the session or apart from it, at
|
||||
/// a letter page's size with `needsPassword`, so that a click in the app can ask for its password;
|
||||
/// headless, a click on it places nothing.
|
||||
#[test]
|
||||
fn the_place_queue_keeps_an_encrypted_pdf() {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
let locked = pdf(&[PdfPage::new(100.0, 50.0, "0 g 0 0 10 10 re f")], Some("pw"));
|
||||
let p = json!({"files": [file("locked.pdf", &locked), file("a.png", &png(40, 20, [9, 9, 9, 255], None))], "thumbnail": 8});
|
||||
let (mut a, mut b) = (session(), session());
|
||||
let r = a.execute("file.place.queue", &p).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
assert_eq!(r["files"][0], json!({"name": "locked.pdf", "format": "pdf", "width": 612.0, "height": 792.0, "needsPassword": true}));
|
||||
assert!(r["files"][1].get("needsPassword").is_none());
|
||||
let read = b.prepare_place_queue(&p).unwrap().read().unwrap();
|
||||
assert_eq!(b.place_queue_read(read).unwrap(), r);
|
||||
let view = ViewInfo::default();
|
||||
assert_eq!(a.tool_options()["name"], "locked.pdf");
|
||||
let _ = a.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), view);
|
||||
let _ = a.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), view);
|
||||
assert_eq!((top_children(&a).len(), a.doc().unwrap().history.undo.len()), (0, 0), "nothing placed without the password");
|
||||
// An encrypted PDF with a bad option is refused for the option, not kept.
|
||||
let e = a.execute("file.place.queue", &json!({"files": [file("locked.pdf", &locked)], "page": 0})).unwrap_err().to_string();
|
||||
assert!(e.contains("page must be a whole number from 1"), "{e}");
|
||||
// A PDF that can't be read for another reason is still skipped.
|
||||
let broken = file("broken.pdf", b"%PDF-1.7\nnot a PDF body\n");
|
||||
let r = a.execute("file.place.queue", &json!({"files": [broken, file("b.png", &png(4, 4, [0; 4], None))]})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"][0]["name"]), (&json!(1), &json!("broken.pdf")), "{r}");
|
||||
}
|
||||
|
||||
/// The place queue's thumbnail of an image is drawn from the pixels its check decoded, so each
|
||||
/// image is decoded once.
|
||||
#[test]
|
||||
|
||||
@@ -468,6 +468,15 @@ fn malformed_docx_fails_cleanly() {
|
||||
assert!(e.contains("not a WordprocessingML document"), "{e}");
|
||||
let e = place(&mut s, "a.docx", &store(&[("word/document.xml", b"<w:document><w:body>")])).unwrap_err();
|
||||
assert!(e.contains("not well-formed XML"), "{e}");
|
||||
for xml in [
|
||||
format!(r#"<w:document xmlns:w="{W_NS}"><w:body><w:p><w:r><w:t>partial text</w:t></w:r></w:p>"#),
|
||||
document("<w:p><w:r><w:t>A&missing;B</w:t></w:r></w:p>"),
|
||||
document("<w:p><w:r><w:t xml:space=\"preserve\" xml:space=\"default\">text</w:t></w:r></w:p>"),
|
||||
document("<w:p xmlns:a=\"urn:test\" xmlns:b=\"urn:test\" a:id=\"1\" b:id=\"2\"><w:r><w:t>text</w:t></w:r></w:p>"),
|
||||
] {
|
||||
let e = place(&mut s, "a.docx", &store(&[("word/document.xml", xml.as_bytes())])).unwrap_err();
|
||||
assert!(e.contains("not well-formed XML"), "{e}");
|
||||
}
|
||||
let e = place(&mut s, "a.docx", &store(&[("word/document.xml", document("<w:p/>").as_bytes())])).unwrap_err();
|
||||
assert!(e.contains("no text to place"), "{e}");
|
||||
// A file whose headers understate what it unpacks to, and one whose headers say it is too large.
|
||||
|
||||
@@ -2420,6 +2420,69 @@ fn a_variable_library_defines_text_variables_and_data_sets() {
|
||||
assert_eq!(s.doc().unwrap().doc.variables.datasets.len(), 2);
|
||||
}
|
||||
|
||||
/// The Variables panel's Import… reads a data source by its extension, in any case: a .csv, .tsv
|
||||
/// or .txt file as Import Data Sets… reads it, and an .xml file as Load Variable Library… reads it.
|
||||
/// Any other extension, or none, is refused before the file is read.
|
||||
#[test]
|
||||
fn variable_import_reads_a_data_source_by_its_extension() {
|
||||
let dir = Folder::new("vars-import");
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "Alice");
|
||||
s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
|
||||
|
||||
for name in ["rows.csv", "rows.TSV", "rows.txt"] {
|
||||
let path = dir.file(name);
|
||||
write(&path, b"Name\nAnn\nBob\n");
|
||||
let r = s.execute("variable.import", &json!({"path": path})).unwrap();
|
||||
assert_eq!((r["format"].clone(), r["names"].clone()), (json!("csv"), json!(["Data Set 1", "Data Set 2"])), "{name}");
|
||||
}
|
||||
s.execute("dataset.select", &json!({"name": "Data Set 2"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "Bob");
|
||||
|
||||
let xml = r#"<variableSets><variableSet><variables><variable varName="Name" trait="textcontent"/></variables><sampleDataSets><sampleDataSet dataSetName="Row 1"><Name><p>Charlie</p></Name></sampleDataSet></sampleDataSets></variableSet></variableSets>"#;
|
||||
let path = dir.file("library.Xml");
|
||||
write(&path, xml.as_bytes());
|
||||
let r = s.execute("variable.import", &json!({"path": path})).unwrap();
|
||||
assert_eq!((r["format"].clone(), r["names"].clone(), r["deleted"].clone()), (json!("xml"), json!(["Row 1"]), json!([])));
|
||||
// The library declares the bound text variable, so its binding stays.
|
||||
s.execute("dataset.select", &json!({"name": "Row 1"})).unwrap();
|
||||
assert_eq!(plain(&s, t), "Charlie");
|
||||
|
||||
// The extension picks the reader: CSV text in an .xml file goes to the library reader, which
|
||||
// refuses it, and a library in a .csv file goes to the CSV reader.
|
||||
let csv_in_xml = dir.file("rows.xml");
|
||||
write(&csv_in_xml, b"Name\nAnn\n");
|
||||
let e = s.execute("variable.import", &json!({"path": csv_in_xml})).unwrap_err().to_string();
|
||||
assert!(e.contains("variable.loadLibrary"), "{e}");
|
||||
let xml_in_csv = dir.file("library.csv");
|
||||
write(&xml_in_csv, xml.as_bytes());
|
||||
let e = s.execute("variable.import", &json!({"path": xml_in_csv})).unwrap_err().to_string();
|
||||
assert!(e.contains("dataset.import"), "{e}");
|
||||
|
||||
// Other extensions, or none, are refused before the file is read, so a missing file gives the
|
||||
// same error; the data sets stay as they were.
|
||||
let refused = "Import reads a data source file ending in .csv, .tsv, .txt or .xml";
|
||||
for (name, exists) in [("rows.json", true), ("rows", true), ("rows.csv.bak", true), ("missing.ai", false)] {
|
||||
let path = dir.file(name);
|
||||
if exists {
|
||||
write(&path, b"Name\nAnn\n");
|
||||
}
|
||||
let e = s.execute("variable.import", &json!({"path": path})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{name}: {e}");
|
||||
}
|
||||
let names: Vec<String> = s.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect();
|
||||
assert_eq!(names, ["Row 1"]);
|
||||
|
||||
// `path` is required, and the command takes no other parameter.
|
||||
for bad in [json!({}), json!({"path": 3})] {
|
||||
let e = s.execute("variable.import", &bad).unwrap_err().to_string();
|
||||
assert!(e.contains("missing `path`"), "{bad}: {e}");
|
||||
}
|
||||
let e = s.execute("variable.import", &json!({"path": dir.file("rows.csv"), "csv": "Name\nX\n"})).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown parameter `csv`"), "{e}");
|
||||
}
|
||||
|
||||
/// Load Variable Library replaces the document's variables and data sets: every variable goes with
|
||||
/// its bindings and values, a variable of another kind with a library variable's name included,
|
||||
/// and every data set goes, the active one included. A text variable the library also declares
|
||||
@@ -2665,6 +2728,11 @@ fn malformed_variable_libraries_are_refused() {
|
||||
let long_graph = format!("<Shown><data><values>{}</values></data></Shown>", row.repeat(2_000));
|
||||
let cases = [
|
||||
("not well-formed XML", "<variableSets><variableSet>".to_string()),
|
||||
("not well-formed XML", ok.replace("<p>x</p>", "<p>A&missing;B</p>")),
|
||||
("not well-formed XML", ok.replace("</variableSets>", "")),
|
||||
("not well-formed XML", ok.replace("varName=\"Name\"", "varName=\"Name\" varName=\"Other\"")),
|
||||
("not well-formed XML", ok.replace("<variable ", "<variable xmlns:a=\"urn:test\" xmlns:b=\"urn:test\" a:id=\"1\" b:id=\"2\" ")),
|
||||
("missing `varName`", ok.replace("varName=\"Name\"", "xmlns:m=\"urn:metadata\" m:varName=\"Name\"")),
|
||||
("no `variableSets` element", "<svg><variables/></svg>".to_string()),
|
||||
("declares no variables", "<variableSets><variableSet><variables/></variableSet></variableSets>".to_string()),
|
||||
("is declared twice", library(&[("Name", "textcontent"), ("Name", "textcontent")], &[])),
|
||||
@@ -3545,6 +3613,17 @@ fn variable_sort_orders_the_list_by_each_column() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_library_attributes_keep_their_namespace() {
|
||||
let mut s = session();
|
||||
let xml = library(&[("Name", "textcontent")], &[("A", &[("Name", &["x"])])])
|
||||
.replace("varName=\"Name\"", "xmlns:m=\"urn:metadata\" m:varName=\"Other\" varName=\"Name\"");
|
||||
let loaded = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
assert_eq!(loaded["variables"], json!(["Name"]));
|
||||
let sets = s.execute("dataset.list", &json!({})).unwrap();
|
||||
assert_eq!(sets["datasets"][0]["values"], json!({"Name": {"text": "x"}}));
|
||||
}
|
||||
|
||||
/// The sort is panel state: it is not an undo step and does not count as a change to save, and
|
||||
/// setting the order the list already has does not redraw anything. A bad `by` or `descending`
|
||||
/// is an error that leaves the order as it was.
|
||||
|
||||
@@ -463,6 +463,69 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() {
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only
|
||||
/// when an effect of the series group draws that art with the group.
|
||||
#[test]
|
||||
fn expand_appearance_in_safe_mode_checks_design_art_its_series_group_draws() {
|
||||
let _f = fresh();
|
||||
let mut s = Session::new();
|
||||
let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.graph", "effect", "{}"), r#"{"objects":[]}"#)).unwrap();
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
|
||||
let graph = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
s.execute("effect.apply", &json!({"effect": "plugin.test.sm.graph", "ids": [r]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "Plug"})).unwrap();
|
||||
s.execute("graph.column", &json!({"id": graph, "seriesIndexes": [0], "design": "Plug"})).unwrap();
|
||||
let series = |s: &Session, index: u32| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(vectorcraft_engine::doc::NodeId(graph)).unwrap();
|
||||
n.children().unwrap().iter().find(|c| c.extras().series_index == Some(index)).unwrap().id
|
||||
};
|
||||
let (art_series, other_series) = (series(&s, 0), series(&s, 1));
|
||||
// A mark in the other series has an effect to expand.
|
||||
let mark = s.doc().unwrap().doc.node(other_series).unwrap().children().unwrap()[0].id;
|
||||
s.execute("effect.apply", &json!({"effect": "distort.puckerBloat", "ids": [mark.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [graph]})).unwrap();
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
safe_mode::set_active(None);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// With a Transform effect on the art's series group, expanding the group draws the art's plug-in effect.
|
||||
let shift = {
|
||||
let t = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "ids": [t], "params": {"moveH": 5}})).unwrap();
|
||||
s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.effects[0].clone()
|
||||
};
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(art_series).unwrap().appearance.effects.push(shift);
|
||||
s.execute("select.set", &json!({"ids": [graph]})).unwrap();
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string();
|
||||
safe_mode::set_active(None);
|
||||
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
|
||||
// With a Gaussian Blur on a fill of the art's series group instead, expanding the group makes an image of it, art included.
|
||||
let blurred_fill = {
|
||||
let t = s.execute("shape.rectangle", &json!({"x": 700, "y": 40, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [t], "item": 0, "params": {"radius": 2}})).unwrap();
|
||||
s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.items[0].clone()
|
||||
};
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let g = d.node_mut(art_series).unwrap();
|
||||
g.appearance.effects.clear();
|
||||
g.appearance.items.push(blurred_fill);
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [graph]})).unwrap();
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
let err = s.execute("effect.expandAppearance", &json!({})).unwrap_err().to_string();
|
||||
safe_mode::set_active(None);
|
||||
assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}");
|
||||
}
|
||||
|
||||
/// In Safe Mode, a plug-in effect on a dimension selected with the art it measures does not stop
|
||||
/// Expand Appearance: the dimension is left as it is, its effect included, and the art expands.
|
||||
#[test]
|
||||
|
||||
@@ -10810,6 +10810,129 @@ fn unreachable_envelope() -> ! {
|
||||
panic!("not an envelope")
|
||||
}
|
||||
|
||||
/// `doc` with its first artboard 20,000.5 points wide: it is written on a large canvas, at 1/10.
|
||||
fn on_large_canvas(mut doc: Document) -> Document {
|
||||
doc.artboards[0].rect = Rect::new(0.0, 0.0, 20_000.5, 100.0);
|
||||
doc
|
||||
}
|
||||
|
||||
/// A route an envelope was read back by: its name, the envelope and the reader's notes.
|
||||
type EnvelopeRoute = (&'static str, Node, Vec<String>);
|
||||
|
||||
/// The envelope `doc` holds alone on its first layer, read back from the editing data alone and
|
||||
/// beside a page that draws as `doc` does ([`read_with_page`]); and the writer's warnings.
|
||||
fn envelope_both_routes(doc: &Document) -> (Vec<EnvelopeRoute>, Vec<String>) {
|
||||
let (alone, warnings, notes) = envelope_back(doc);
|
||||
let (paged, _, page_notes) = read_with_page(doc);
|
||||
assert_eq!(paged.len(), 1, "{paged:#?} {page_notes:?}");
|
||||
(vec![("alone", alone, notes), ("beside its page", (*paged[0]).clone(), page_notes)], warnings)
|
||||
}
|
||||
|
||||
/// On a large canvas, a warp, a mesh and a top object envelope, with Edit Contents off and on, are
|
||||
/// written live at 1/10 and open as the same envelope at their size, from the editing data alone
|
||||
/// and beside the page: contents, Fidelity, Edit Contents, Envelope Options, shape and name as
|
||||
/// saved. Saved again as they opened, they open as the same envelope again.
|
||||
#[test]
|
||||
fn large_canvas_envelope_kinds_round_trip_on_both_ai_routes() {
|
||||
// GUARDS: an envelope on a large canvas was written as its drawn art, with a warning.
|
||||
use vectorcraft_doc::live::EnvelopeOptions;
|
||||
for (name, kind) in live_envelope_kinds() {
|
||||
for editing in [false, true] {
|
||||
let what = format!("{name}, editing {editing}");
|
||||
let doc = on_large_canvas(envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW));
|
||||
let text = program(&doc);
|
||||
assert!(text.contains("%AI24_LargeCanvasScale: 10\n") && text.contains("AIDeformOptionsKey"), "{what}");
|
||||
let (routes, warnings) = envelope_both_routes(&doc);
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}");
|
||||
for (route, back, notes) in routes {
|
||||
let what = format!("{what}, {route}");
|
||||
assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}");
|
||||
let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else {
|
||||
panic!("{what}: {back:#?} {notes:?}")
|
||||
};
|
||||
assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}");
|
||||
assert!(same_envelope_kind(&kind, got), "{what}: {got:?}");
|
||||
assert_eq!(back.name.as_deref(), Some("Bent"), "{what}");
|
||||
let colors: Vec<Option<Color>> = content.iter().map(|c| c.appearance.fill_paint().color()).collect();
|
||||
assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}");
|
||||
let b = content.iter().filter_map(|c| c.visual_bounds()).reduce(|a, b| a.union(b)).unwrap();
|
||||
let want = Rect::new(40.0, 20.0, 160.0, 80.0);
|
||||
assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-2), "{what}: {b:?}");
|
||||
}
|
||||
let (back, _, _) = envelope_back(&doc);
|
||||
let mut again = on_large_canvas(Document::new(200.0, 100.0));
|
||||
let layer = again.layers[0].id;
|
||||
again.insert(Some(layer), usize::MAX, back).unwrap();
|
||||
let (twice, warnings, notes) = envelope_back(&again);
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}");
|
||||
let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") };
|
||||
assert!(same_envelope_kind(&kind, twice), "{what}, saved again: {twice:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On a large canvas, envelopes with Distort Appearance whose stroked contents (at fractional places)
|
||||
/// map from their bounds with their strokes keep that margin, the contents' 8-point strokes and the
|
||||
/// Distort Linear Gradients and Distort Pattern Fills switches, from the editing data alone and
|
||||
/// beside the page.
|
||||
#[test]
|
||||
fn large_canvas_envelope_stroke_margin_round_trips_on_both_ai_routes() {
|
||||
// GUARDS: read from the editing data alone, the saved size was compared at 1/10 with contents at
|
||||
// their size, and the contents' strokes came back at 1/10: the margin was lost.
|
||||
use vectorcraft_doc::live::{EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin};
|
||||
for (name, kind) in live_envelope_kinds() {
|
||||
for editing in [false, true] {
|
||||
let what = format!("{name}, editing {editing}");
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let switches = EnvelopeOptions { distort_linear_gradients: editing, distort_pattern_fills: !editing, ..EnvelopeOptions::NEW };
|
||||
let mut envelope = envelope_node(&mut doc, kind.clone(), 50.0, editing, switches);
|
||||
let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() };
|
||||
for c in content.iter_mut() {
|
||||
let c = Arc::make_mut(c);
|
||||
c.transform(Affine::translate((0.25, 0.375)), true);
|
||||
let fill = c.appearance.fill_paint();
|
||||
c.appearance = Appearance::basic(fill, solid(Color::BLACK), 8.0).into();
|
||||
}
|
||||
let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap();
|
||||
options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap();
|
||||
let want = *options;
|
||||
assert!(want.bounds_margin.iter().all(|m| *m > 0.0), "{what}: {want:?}");
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
|
||||
let (routes, warnings) = envelope_both_routes(&on_large_canvas(doc));
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}");
|
||||
for (route, back, notes) in routes {
|
||||
let what = format!("{what}, {route}");
|
||||
let NodeKind::Envelope { content, options, .. } = &back.kind else { panic!("{what}: {back:#?} {notes:?}") };
|
||||
let margin = options.bounds_margin;
|
||||
assert!(margin.iter().zip(want.bounds_margin).all(|(a, b)| (a - b).abs() < 1e-4), "{what}: {margin:?} {want:?}");
|
||||
assert_eq!(EnvelopeOptions { bounds_margin: want.bounds_margin, ..*options }, want, "{what}");
|
||||
let widths: Vec<f64> = content.iter().filter_map(|c| c.appearance.stroke().map(|s| s.width)).collect();
|
||||
assert!(widths.len() == 2 && widths.iter().all(|w| (w - 8.0).abs() < 1e-4), "{what}: {widths:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On a large canvas a path's stroke weight and dashes, written at 1/10, come back at their size
|
||||
/// from the editing data alone.
|
||||
#[test]
|
||||
fn a_large_canvas_path_keeps_its_stroke_weight_and_dashes_read_alone() {
|
||||
// GUARDS: read from the editing data alone, the stroke's weight, dashes and dash offset came
|
||||
// back at 1/10 while the path came back at its size.
|
||||
let mut doc = on_large_canvas(Document::new(200.0, 100.0));
|
||||
let mut n =
|
||||
Node::path(doc.alloc_id(), shapes::line((20.0, 50.0).into(), (180.0, 50.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 6.0));
|
||||
n.appearance.stroke_mut().unwrap().dash = Some(Dash { pattern: vec![12.0, 4.5], offset: 3.0, align_corners: false });
|
||||
put(&mut doc, n);
|
||||
let back = read_back(&doc);
|
||||
let st = back.layers[0].children().unwrap()[0].appearance.stroke().cloned().unwrap();
|
||||
assert!((st.width - 6.0).abs() < 1e-6, "{st:?}");
|
||||
let dash = st.dash.unwrap();
|
||||
assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 12.0).abs() < 1e-6 && (dash.pattern[1] - 4.5).abs() < 1e-6, "{dash:?}");
|
||||
assert!((dash.offset - 3.0).abs() < 1e-6, "{dash:?}");
|
||||
}
|
||||
|
||||
/// The record is written in the order the reader reads it: on `%_` lines the group holding the
|
||||
/// grid, its dictionary with the options, the contents' block and the kind, then the distorted art
|
||||
/// on plain lines and the plugin's `XP`. While the contents are edited, the group holds them and
|
||||
@@ -10923,7 +11046,10 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() {
|
||||
("fractional fidelity", fractional),
|
||||
("margin kept", margin_kept),
|
||||
];
|
||||
for (what, doc) in cases {
|
||||
// On a large canvas too.
|
||||
let large: Vec<(String, Document)> =
|
||||
cases.iter().map(|(what, doc)| (format!("{what}, on a large canvas"), on_large_canvas(doc.clone()))).collect();
|
||||
for (what, doc) in cases.into_iter().map(|(what, doc)| (what.to_string(), doc)).chain(large) {
|
||||
let text = program(&doc);
|
||||
assert!(!text.contains("AIDeformOptionsKey"), "{what}: {text}");
|
||||
let (back, warnings, _) = envelope_back(&doc);
|
||||
|
||||
@@ -27,7 +27,7 @@ use super::{MAX_NEST, Writer, Xy, hide};
|
||||
use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number};
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes whose type is threaded, has text wrap options or is written as its outlines, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps";
|
||||
|
||||
/// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the
|
||||
/// reader's).
|
||||
@@ -356,15 +356,17 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize,
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Envelope `n`, of transparency `xy`, as a live envelope (see the module's form), outside opacity
|
||||
/// masks' art, pattern tiles, art cut to a clipping object and the layers of a large canvas. Type
|
||||
/// in its contents is written as type, which the reader makes the envelope's contents again.
|
||||
/// masks' art, pattern tiles and art cut to a clipping object. On a large canvas it is written at
|
||||
/// the document's reduced size, its saved box size included, which the reader reads at the
|
||||
/// declared scale. Type in its contents is written as type, which the reader makes the
|
||||
/// envelope's contents again.
|
||||
/// False, writing nothing, where it is written as its art instead: where the reader would open it
|
||||
/// in another shape, or with its type as drawn art (threaded type, type with text wrap options,
|
||||
/// type written as its outlines), or some of it is left out for the object limit
|
||||
/// ([`Self::take_objects`]).
|
||||
pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool {
|
||||
let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false };
|
||||
if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.checks_left == 0 {
|
||||
if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || self.checks_left == 0 {
|
||||
return false;
|
||||
}
|
||||
if content.iter().any(|c| holds_type(c)) && !content.iter().all(|c| type_reads_back(c, self.doc)) {
|
||||
|
||||
@@ -121,11 +121,12 @@ pub(super) fn options(o: &Obj) -> Option<(EnvelopeOptions, f64)> {
|
||||
|
||||
/// The margins of `content` when the size the file saves for it (`AIDeformArtWidthKey`,
|
||||
/// `AIDeformArtHeightKey`) matches its bounds with its strokes within [`SAVED_SIZE_SLACK`] and lies
|
||||
/// nearer them than its geometric bounds. None without that size, or for contents with no width or
|
||||
/// no height.
|
||||
fn saved_margin(o: &Obj, content: &[Arc<Node>]) -> Option<[f32; 4]> {
|
||||
/// nearer them than its geometric bounds. The saved size is in art space, and `scale` takes it to the
|
||||
/// contents' space (a Large Canvas copy read at its declared scale). None without that size, or for
|
||||
/// contents with no width or no height.
|
||||
fn saved_margin(o: &Obj, content: &[Arc<Node>], scale: f64) -> Option<[f32; 4]> {
|
||||
let saved = |key: &str| match o.nums(key).as_slice() {
|
||||
[v] if v.is_finite() => Some(*v),
|
||||
[v] if v.is_finite() => Some(*v * scale).filter(|v| v.is_finite()),
|
||||
_ => None,
|
||||
};
|
||||
let (w, h) = (saved("AIDeformArtWidthKey")?, saved("AIDeformArtHeightKey")?);
|
||||
@@ -508,9 +509,10 @@ fn unwrapped(mut nodes: Vec<Node>) -> Vec<Arc<Node>> {
|
||||
}
|
||||
|
||||
/// The live envelope of dictionary `o`, the group on `%_` lines before it (`before`) and the art
|
||||
/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one.
|
||||
pub(super) fn live(o: &Obj, before: Option<Node>, inner: Vec<Node>) -> Option<NodeKind> {
|
||||
envelope_as(o, before, inner, false)
|
||||
/// in its `AIDeformArtKey` block (`inner`); `None` where they don't make one. `scale` takes sizes in
|
||||
/// art space to the space the art was read into ([`saved_margin`]).
|
||||
pub(super) fn live(o: &Obj, before: Option<Node>, inner: Vec<Node>, scale: f64) -> Option<NodeKind> {
|
||||
envelope_as(o, before, inner, false, scale)
|
||||
}
|
||||
|
||||
/// Is the envelope of dictionary `o` a warp?
|
||||
@@ -521,12 +523,12 @@ fn is_warp(o: &Obj) -> bool {
|
||||
/// [`live`] for a warp, as a mesh envelope on the grid its editing data saves (the mesh that shapes
|
||||
/// it), its points and handles as saved: it draws as that grid does, without the warp's style, bend
|
||||
/// and distortions. `None` for an envelope that isn't a warp, or whose grid doesn't read.
|
||||
fn live_on_saved_grid(o: &Obj, before: Option<Node>, inner: Vec<Node>) -> Option<NodeKind> {
|
||||
envelope_as(o, before, inner, true)
|
||||
fn live_on_saved_grid(o: &Obj, before: Option<Node>, inner: Vec<Node>, scale: f64) -> Option<NodeKind> {
|
||||
envelope_as(o, before, inner, true, scale)
|
||||
}
|
||||
|
||||
/// [`live`], or with `on_grid` [`live_on_saved_grid`].
|
||||
fn envelope_as(o: &Obj, before: Option<Node>, inner: Vec<Node>, on_grid: bool) -> Option<NodeKind> {
|
||||
fn envelope_as(o: &Obj, before: Option<Node>, inner: Vec<Node>, on_grid: bool, scale: f64) -> Option<NodeKind> {
|
||||
let editing = switch(o, "AIDeformEditModeKey")?;
|
||||
let (mut options, fidelity) = options(o)?;
|
||||
let before = before?;
|
||||
@@ -546,7 +548,7 @@ fn envelope_as(o: &Obj, before: Option<Node>, inner: Vec<Node>, on_grid: bool) -
|
||||
return None;
|
||||
}
|
||||
if options.distort_appearance {
|
||||
options.bounds_margin = saved_margin(o, &content).unwrap_or_default();
|
||||
options.bounds_margin = saved_margin(o, &content, scale).unwrap_or_default();
|
||||
}
|
||||
let kind = match (whole(o, "AIDeformStyle")??, on_grid) {
|
||||
(1, false) => warp(o)?,
|
||||
@@ -637,14 +639,15 @@ pub(super) struct WarpedLook {
|
||||
|
||||
/// An envelope of type read with its drawn art: its dictionary, the group on `%_` lines before it
|
||||
/// and the art in its `AIDeformArtKey` block, as [`live`] takes them (their text slots still
|
||||
/// empty), and the id of its drawn art in the document. Type is laid out after the layers are read,
|
||||
/// so it waits for that ([`WarpedType::settle_envelopes`]).
|
||||
/// empty), the id of its drawn art in the document, and the scale [`live`] takes. Type is laid out
|
||||
/// after the layers are read, so it waits for that ([`WarpedType::settle_envelopes`]).
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct TypedEnvelope {
|
||||
pub(super) obj: Obj,
|
||||
pub(super) before: Option<Node>,
|
||||
pub(super) inner: Vec<Node>,
|
||||
pub(super) drawn: NodeId,
|
||||
pub(super) scale: f64,
|
||||
}
|
||||
|
||||
/// Why an envelope of type kept its drawn art.
|
||||
@@ -788,7 +791,7 @@ impl WarpedType {
|
||||
shown: &BTreeSet<NodeId>,
|
||||
waiting: usize,
|
||||
) -> Result<(NodeId, Vec<Node>), TypeKept> {
|
||||
let TypedEnvelope { obj, mut before, mut inner, drawn } = envelope;
|
||||
let TypedEnvelope { obj, mut before, mut inner, drawn, scale } = envelope;
|
||||
let art = doc.node(drawn).cloned().ok_or(TypeKept::Read)?;
|
||||
// The text slots in the contents, in the order the reader put their hidden copies in.
|
||||
let mut slots = vec![];
|
||||
@@ -813,13 +816,13 @@ impl WarpedType {
|
||||
}
|
||||
// A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the
|
||||
// grid the file saves for it: then it opens as a mesh envelope on that grid.
|
||||
let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone()) } else { None };
|
||||
let on_grid = if is_warp(&obj) { live_on_saved_grid(&obj, before.clone(), inner.clone(), scale) } else { None };
|
||||
// With Distort Appearance, a file's envelope may map its type from its glyphs grown by half
|
||||
// their strokes' weight or from the glyphs alone, and for type the size the file saves for
|
||||
// that box is often out of date (not the size of the type there now): each is checked.
|
||||
// After all of those, each is checked mapping from what its type paints, where that box is
|
||||
// another: it is measured only when such a check comes and one is left.
|
||||
let kinds: Vec<NodeKind> = live(&obj, before, inner).into_iter().chain(on_grid).collect();
|
||||
let kinds: Vec<NodeKind> = live(&obj, before, inner, scale).into_iter().chain(on_grid).collect();
|
||||
if kinds.is_empty() {
|
||||
return Err(TypeKept::Read);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ use super::containers::close;
|
||||
use super::document::TEXT_SLOT;
|
||||
use super::raster::{self, Limits, Shape};
|
||||
use super::types::{
|
||||
FLIP, Frame, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE,
|
||||
NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail,
|
||||
FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS,
|
||||
MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail,
|
||||
};
|
||||
use super::{
|
||||
Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node,
|
||||
@@ -224,12 +224,7 @@ impl<'a> Reader<'a> {
|
||||
items.push(AppearanceItem::Fill(FillLayer { overprint: gs.overprint_fill, ..FillLayer::new(fill_paint.unwrap_or(gs.fill.clone())) }));
|
||||
}
|
||||
if stroke {
|
||||
let mut st = StrokeLayer::new(stroke_paint.unwrap_or(gs.stroke.clone()), gs.line_width());
|
||||
st.cap = gs.cap;
|
||||
st.join = gs.join;
|
||||
st.miter_limit = gs.miter;
|
||||
st.dash = gs.dash.clone();
|
||||
st.overprint = gs.overprint_stroke;
|
||||
let st = self.stroke_layer(stroke_paint.unwrap_or(gs.stroke.clone()), &gs);
|
||||
items.push(AppearanceItem::Stroke(st));
|
||||
}
|
||||
let kind = NodeKind::Path { path, rule: gs.rule, live: None, clipping: clip, guide };
|
||||
@@ -330,17 +325,29 @@ impl<'a> Reader<'a> {
|
||||
if !matches!(n.kind, NodeKind::Path { .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
return;
|
||||
}
|
||||
let mut st = StrokeLayer::new(gs.stroke.clone(), gs.line_width());
|
||||
st.cap = gs.cap;
|
||||
st.join = gs.join;
|
||||
st.miter_limit = gs.miter;
|
||||
st.dash = gs.dash.clone();
|
||||
st.overprint = gs.overprint_stroke;
|
||||
let st = self.stroke_layer(gs.stroke.clone(), &gs);
|
||||
let Some(n) = self.frames.last_mut().and_then(|f| f.children.last_mut()) else { return };
|
||||
let mut a = (*n.appearance).clone();
|
||||
a.items.push(AppearanceItem::Stroke(st));
|
||||
n.appearance = a.into();
|
||||
}
|
||||
|
||||
/// A stroke of `paint` with graphics state `gs`'s weight, caps, joins, miter limit, dashes and
|
||||
/// overprint, its weight and dashes at the scale the art is read at ([`Self::space_scale`]).
|
||||
fn stroke_layer(&mut self, paint: Paint, gs: &GState) -> StrokeLayer {
|
||||
let k = self.space_scale();
|
||||
let mut st = StrokeLayer::new(paint, gs.line_width() * k);
|
||||
st.cap = gs.cap;
|
||||
st.join = gs.join;
|
||||
st.miter_limit = gs.miter;
|
||||
st.dash = gs.dash.clone().map(|mut d| {
|
||||
d.scale(k);
|
||||
d
|
||||
});
|
||||
st.overprint = gs.overprint_stroke;
|
||||
st
|
||||
}
|
||||
|
||||
pub(super) fn set_instance(&mut self, i: &Instance) {
|
||||
let mut to_doc = self.space();
|
||||
// In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's
|
||||
|
||||
@@ -885,6 +885,7 @@ impl<'a> Reader<'a> {
|
||||
return;
|
||||
}
|
||||
let Some(p) = self.envelopes.pop() else { return };
|
||||
let scale = self.space_scale();
|
||||
let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last());
|
||||
let Some(drawn) = drawn else {
|
||||
self.warn(crate::import::ai::envelope::drawn_note(p.typed));
|
||||
@@ -894,7 +895,7 @@ impl<'a> Reader<'a> {
|
||||
self.wait_for_type(p);
|
||||
return;
|
||||
}
|
||||
let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten();
|
||||
let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner, scale)).flatten();
|
||||
let Some(kind) = live else {
|
||||
self.warn(crate::import::ai::envelope::DRAWN);
|
||||
return;
|
||||
@@ -982,8 +983,8 @@ impl Reader<'_> {
|
||||
self.warn(crate::import::ai::envelope::TYPE_DRAWN);
|
||||
return;
|
||||
}
|
||||
let drawn = drawn.id;
|
||||
self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn });
|
||||
let (drawn, scale) = (drawn.id, self.space_scale());
|
||||
self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn, scale });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -934,6 +934,13 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times as long [`Self::space`] makes a length in art space: a Large Canvas copy's
|
||||
/// declared scale in the document, and 1 in a pattern's or a symbol's definition.
|
||||
pub(super) fn space_scale(&mut self) -> f64 {
|
||||
let k = self.space().determinant().abs().sqrt();
|
||||
if k.is_finite() && k > 0.0 { k } else { 1.0 }
|
||||
}
|
||||
|
||||
/// The space an image's matrix is in → where the art being read goes: [`Self::space`], and in a
|
||||
/// symbol's art (outside a pattern's definition) the canvas's space turned y up about art space's
|
||||
/// origin there, as an instance's matrix in it is; `None` there without a template box.
|
||||
|
||||
@@ -44,10 +44,15 @@ fn gradient_annotator_end_to_end() {
|
||||
let r = ok(&mut h, "press_key", json!({"key": "Delete"}));
|
||||
assert_eq!(r["handledBy"], "tool", "{r}");
|
||||
assert_eq!(offsets(&gradient(&h)), vec![0.0, 100.0]);
|
||||
// The end handle changes only the end.
|
||||
// The end handle changes only the length: the end stays on the bar's line.
|
||||
let end = json!({"events": [{"kind": "down", "x": 200, "y": 150}, {"kind": "drag", "x": 230, "y": 120}, {"kind": "up", "x": 230, "y": 120}]});
|
||||
ok(&mut h, "pointer_gesture", end);
|
||||
let g = gradient(&h).geom.unwrap();
|
||||
assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(230.0, 150.0)));
|
||||
// Alt-dragged, it changes the length and the angle together.
|
||||
let end = json!({"mods": {"alt": true}, "events": [{"kind": "down", "x": 230, "y": 150}, {"kind": "drag", "x": 230, "y": 120}, {"kind": "up", "x": 230, "y": 120}]});
|
||||
ok(&mut h, "pointer_gesture", end);
|
||||
let g = gradient(&h).geom.unwrap();
|
||||
assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(230.0, 120.0)));
|
||||
// Double-clicking a stop asks for its popover.
|
||||
let dbl = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 100, "y": 160}]}));
|
||||
|
||||
@@ -656,6 +656,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}",
|
||||
),
|
||||
(
|
||||
"window.panel.cycleOptions",
|
||||
"Cycle Display Sizes",
|
||||
"",
|
||||
"{panel} show a panel at its next display size, as the double triangle at the right end of its tab strip does: the sizes are the states of its panel menu's Show/Hide Options (Transparency: options and thumbnails, thumbnails alone, neither), largest first, and the smallest goes back to the largest; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency have them. An unknown panel or one without display sizes is an error and changes nothing. Returns {panel, size: 0 for the largest, sizes: how many it has}",
|
||||
),
|
||||
(
|
||||
"window.panel.float",
|
||||
"Float Panel",
|
||||
|
||||
@@ -33,8 +33,8 @@ smallvec = "1"
|
||||
siphasher = "1"
|
||||
weezl = "0.2"
|
||||
serde = { workspace = true }
|
||||
# The XMP packet that File Info is read from (file_info.rs); the version usvg already uses.
|
||||
roxmltree = "0.21"
|
||||
# The XMP packet that File Info is read from (file_info.rs).
|
||||
craft-xml = { workspace = true }
|
||||
# PDF security (encrypt.rs): pure Rust, MIT OR Apache-2.0, builds for wasm.
|
||||
aes = "0.8"
|
||||
md-5 = { version = "0.10", default-features = false }
|
||||
|
||||
@@ -18,6 +18,10 @@ pub(super) const MAX_PATTERN_DEPTH: u32 = 4;
|
||||
/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`).
|
||||
pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture";
|
||||
|
||||
/// The warning for an image left out because its colors can't be converted as the Output
|
||||
/// settings ask, although it could be written in its own colors.
|
||||
pub(super) const UNCONVERTED: &str = "an image couldn't be converted to the Output destination and is missing from the picture";
|
||||
|
||||
/// The warning for an image whose placement cannot be written.
|
||||
pub(super) const UNWRITABLE_IMAGE: &str = "an image couldn't be written and is missing from the picture";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::exporter::{UNDECODED, UNWRITABLE_IMAGE, q, writable, xf};
|
||||
use super::exporter::{UNCONVERTED, UNDECODED, UNWRITABLE_IMAGE, q, writable, xf};
|
||||
use super::{Arc, BlendMode, Color, Exporter, Image, Node, NodeKind, Paint, Rect, Size, Surface, cmyk, krilla};
|
||||
use krilla::color::device_n::{Colorant, DeviceNSpace, Process};
|
||||
use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace};
|
||||
@@ -126,7 +126,9 @@ impl Exporter<'_> {
|
||||
/// settings say ([`crate::images::recode`], [`crate::images::recode_cmyk`] for CMYK images);
|
||||
/// cached by key (and size when images are resampled). With `interpolate` (and the export's
|
||||
/// own setting), viewers may smooth it. `None`, with [`UNDECODED`] among the warnings, for an
|
||||
/// image that is missing, can't be decoded or is in [`Self::left_out`].
|
||||
/// image that is missing, can't be decoded or is in [`Self::left_out`]; `None`, with
|
||||
/// [`UNCONVERTED`], for one whose colors the Output settings convert but that can only be
|
||||
/// written in its own ([`crate::images::Recoded::unconverted`]).
|
||||
fn load_image(&mut self, im: &vectorcraft_doc::ImageObject, size: (f64, f64), interpolate: bool) -> Option<Image> {
|
||||
let key = im.key.as_str();
|
||||
let c = self.compression;
|
||||
@@ -142,6 +144,7 @@ impl Exporter<'_> {
|
||||
let out = self.out.clone();
|
||||
let profiles = out.source_profiles();
|
||||
let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit });
|
||||
let mut unconverted = false;
|
||||
let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| {
|
||||
let cmyk_image = blob.is_cmyk();
|
||||
if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk {
|
||||
@@ -153,6 +156,12 @@ impl Exporter<'_> {
|
||||
} else {
|
||||
crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles, to_srgb)
|
||||
};
|
||||
if r.unconverted {
|
||||
// The source image would be written in its own colors: it is left out, with a
|
||||
// warning that names the conversion when it could have been written.
|
||||
unconverted = embed(blob, interpolate, self.sixteen_bit, profiles).is_some();
|
||||
return None;
|
||||
}
|
||||
let img = r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles));
|
||||
// An image left out gets the warning below instead.
|
||||
for w in [r.warning, r.note].into_iter().flatten().filter(|_| img.is_some()) {
|
||||
@@ -160,7 +169,9 @@ impl Exporter<'_> {
|
||||
}
|
||||
img
|
||||
});
|
||||
if img.is_none() {
|
||||
if unconverted {
|
||||
self.warn(UNCONVERTED);
|
||||
} else if img.is_none() {
|
||||
self.warn(UNDECODED);
|
||||
}
|
||||
self.images.insert(cache, img.clone());
|
||||
|
||||
+39
-86
@@ -5,7 +5,7 @@
|
||||
|
||||
use craft_pdf::syntax::Pdf;
|
||||
use craft_pdf::syntax::object::{DateTime, Dict, Stream};
|
||||
use roxmltree::Node;
|
||||
use craft_xml::{Canonical, Doctype, El, Limits, Names, Options};
|
||||
|
||||
use crate::import_scan::text_string;
|
||||
|
||||
@@ -15,12 +15,13 @@ const MAX_XMP: usize = 8 << 20;
|
||||
const MAX_NESTING: usize = 256;
|
||||
|
||||
const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
|
||||
const XML: &str = "http://www.w3.org/XML/1998/namespace";
|
||||
pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/";
|
||||
const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use
|
||||
pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use
|
||||
const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use
|
||||
|
||||
const XMP_NAMESPACES: Canonical<'static> = Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF)]);
|
||||
|
||||
/// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FileInfo {
|
||||
@@ -73,39 +74,39 @@ fn packet(pdf: &Pdf) -> Option<Vec<u8>> {
|
||||
}
|
||||
|
||||
/// The File Info fields of an XMP packet; `None` when it isn't XML in UTF-8 or UTF-16, or when its
|
||||
/// elements nest more than [`MAX_NESTING`] deep.
|
||||
/// [`xmp`] of `packet`; `None` when it isn't XML in UTF-8 or UTF-16, or when its elements nest
|
||||
/// more than [`MAX_NESTING`] deep.
|
||||
fn xmp(packet: &[u8]) -> Option<FileInfo> {
|
||||
let text = xml_text(packet)?;
|
||||
// roxmltree parses nested elements recursively.
|
||||
if nesting(&text) > MAX_NESTING {
|
||||
return None;
|
||||
let opts = Options {
|
||||
names: Names::Canonical(&XMP_NAMESPACES),
|
||||
doctype: Doctype::Reject,
|
||||
limits: Limits { max_depth: MAX_NESTING, ..Limits::DEFAULT },
|
||||
..Options::default()
|
||||
}
|
||||
let xml = roxmltree::Document::parse(&text).ok()?;
|
||||
.strict();
|
||||
let root = opts.parse(text.as_bytes()).ok()?;
|
||||
// The resource's own descriptions: those right under `rdf:RDF`, not the ones inside a value.
|
||||
let descriptions: Vec<Node<'_, '_>> = xml
|
||||
.descendants()
|
||||
.filter(|n| n.has_tag_name((RDF, "RDF")))
|
||||
.flat_map(|rdf| rdf.children())
|
||||
.filter(|n| n.has_tag_name((RDF, "Description")))
|
||||
.collect();
|
||||
let get = |ns: &str, name: &str| property(&descriptions, ns, name);
|
||||
let first = |ns: &str, name: &str| get(ns, name).into_iter().next();
|
||||
let creators = get(DC, "creator");
|
||||
let subjects = get(DC, "subject");
|
||||
let descriptions: Vec<&El> =
|
||||
std::iter::once(&root).chain(root.descendants()).filter(|n| n.is("rdf:RDF")).flat_map(|rdf| rdf.children("rdf:Description")).collect();
|
||||
let get = |name: &str| property(&descriptions, name);
|
||||
let first = |name: &str| get(name).into_iter().next();
|
||||
let creators = get("dc:creator");
|
||||
let subjects = get("dc:subject");
|
||||
Some(FileInfo {
|
||||
title: first(DC, "title"),
|
||||
title: first("dc:title"),
|
||||
author: (!creators.is_empty()).then(|| creators.join(", ")),
|
||||
description: first(DC, "description"),
|
||||
keywords: if subjects.is_empty() { first(PDF, "Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) },
|
||||
copyright_notice: first(DC, "rights"),
|
||||
copyright_url: first(XMP_RIGHTS, "WebStatement"),
|
||||
copyrighted: first(XMP_RIGHTS, "Marked").and_then(|m| match m.to_ascii_lowercase().as_str() {
|
||||
description: first("dc:description"),
|
||||
keywords: if subjects.is_empty() { first("pdf:Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) },
|
||||
copyright_notice: first("dc:rights"),
|
||||
copyright_url: first("xmpRights:WebStatement"),
|
||||
copyrighted: first("xmpRights:Marked").and_then(|m| match m.to_ascii_lowercase().as_str() {
|
||||
"true" => Some(true),
|
||||
"false" => Some(false),
|
||||
_ => None,
|
||||
}),
|
||||
created: first(XMP, "CreateDate").and_then(|d| xmp_date(&d)),
|
||||
modified: first(XMP, "ModifyDate").and_then(|d| xmp_date(&d)),
|
||||
created: first("xmp:CreateDate").and_then(|d| xmp_date(&d)),
|
||||
modified: first("xmp:ModifyDate").and_then(|d| xmp_date(&d)),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -123,58 +124,14 @@ fn xml_text(b: &[u8]) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments,
|
||||
/// CDATA sections, processing instructions, declarations and quoted attribute values.
|
||||
fn nesting(xml: &str) -> usize {
|
||||
let b = xml.as_bytes();
|
||||
let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize);
|
||||
// The index just past the first `end` at or after `from` (the end of the text if none).
|
||||
let past = |from: usize, end: &[u8]| {
|
||||
b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len())
|
||||
};
|
||||
while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) {
|
||||
let start = i + at;
|
||||
let rest = b.get(start..).unwrap_or_default();
|
||||
if rest.starts_with(b"<!--") {
|
||||
i = past(start + 4, b"-->");
|
||||
} else if rest.starts_with(b"<![CDATA[") {
|
||||
i = past(start + 9, b"]]>");
|
||||
} else if rest.starts_with(b"<?") {
|
||||
i = past(start + 2, b"?>");
|
||||
} else if rest.starts_with(b"<!") || rest.starts_with(b"</") {
|
||||
depth = depth.saturating_sub(usize::from(rest.starts_with(b"</")));
|
||||
i = past(start + 2, b">");
|
||||
} else {
|
||||
// A start tag: up to its `>` outside quotes; `/>` closes it at once.
|
||||
let mut j = start + 1;
|
||||
let mut quote = None;
|
||||
while let Some(&c) = b.get(j) {
|
||||
match (quote, c) {
|
||||
(None, b'"' | b'\'') => quote = Some(c),
|
||||
(Some(q), _) if c == q => quote = None,
|
||||
(None, b'>') => break,
|
||||
_ => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if b.get(j.saturating_sub(1)) != Some(&b'/') {
|
||||
depth += 1;
|
||||
most = most.max(depth);
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
most
|
||||
}
|
||||
|
||||
/// The values of property `ns` `name` on the first of `descriptions` that gives it: an attribute
|
||||
/// The values of property `name` on the first of `descriptions` that gives it: an attribute
|
||||
/// of the `rdf:Description`, or a property element's items ([`items`]), blank ones left out.
|
||||
fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec<String> {
|
||||
fn property(descriptions: &[&El], name: &str) -> Vec<String> {
|
||||
for d in descriptions {
|
||||
if let Some(v) = d.attribute((ns, name)).map(str::trim).filter(|v| !v.is_empty()) {
|
||||
if let Some(v) = d.attr(name).map(str::trim).filter(|v| !v.is_empty()) {
|
||||
return vec![v.to_string()];
|
||||
}
|
||||
let found = d.children().filter(|c| c.has_tag_name((ns, name))).map(items).find(|v| !v.is_empty());
|
||||
let found = d.children(name).map(items).find(|v| !v.is_empty());
|
||||
if let Some(v) = found {
|
||||
return v;
|
||||
}
|
||||
@@ -185,14 +142,10 @@ fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec<String>
|
||||
/// The items of property element `p`: the `rdf:li` of its `rdf:Seq`, `rdf:Bag` or `rdf:Alt` (the
|
||||
/// `x-default` language item first), else its own value ([`value_of`]); trimmed, blank ones left
|
||||
/// out.
|
||||
fn items(p: Node<'_, '_>) -> Vec<String> {
|
||||
let array = p.children().find(|c| ["Seq", "Bag", "Alt"].into_iter().any(|t| c.has_tag_name((RDF, t))));
|
||||
fn items(p: &El) -> Vec<String> {
|
||||
let array = p.elements().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt"));
|
||||
let mut values: Vec<(bool, String)> = match array {
|
||||
Some(a) => a
|
||||
.children()
|
||||
.filter(|c| c.has_tag_name((RDF, "li")))
|
||||
.map(|li| (li.attribute((XML, "lang")).is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li)))
|
||||
.collect(),
|
||||
Some(a) => a.children("rdf:li").map(|li| (li.attr("xml:lang").is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li))).collect(),
|
||||
None => vec![(false, value_of(p))],
|
||||
};
|
||||
// A stable sort: the `x-default` item first, the others in their order.
|
||||
@@ -203,19 +156,19 @@ fn items(p: Node<'_, '_>) -> Vec<String> {
|
||||
/// The value of element `n`: the URI of its `rdf:resource` attribute (how RDF writes a URI value);
|
||||
/// for a qualified value, its `rdf:value` (an attribute or an element, on `n` or on an
|
||||
/// `rdf:Description` inside it), without the qualifiers; else the text inside it.
|
||||
fn value_of(mut n: Node<'_, '_>) -> String {
|
||||
fn value_of(mut n: &El) -> String {
|
||||
// Each step goes to an element inside `n`, so the loop ends.
|
||||
loop {
|
||||
if let Some(uri) = n.attribute((RDF, "resource")) {
|
||||
if let Some(uri) = n.attr("rdf:resource") {
|
||||
return uri.to_string();
|
||||
}
|
||||
let holder = n.children().find(|c| c.has_tag_name((RDF, "Description"))).unwrap_or(n);
|
||||
if let Some(v) = holder.attribute((RDF, "value")) {
|
||||
let holder = n.child("rdf:Description").unwrap_or(n);
|
||||
if let Some(v) = holder.attr("rdf:value") {
|
||||
return v.to_string();
|
||||
}
|
||||
match holder.children().find(|c| c.has_tag_name((RDF, "value"))) {
|
||||
match holder.child("rdf:value") {
|
||||
Some(v) => n = v,
|
||||
None => return n.descendants().filter(|d| d.is_text()).filter_map(|d| d.text()).collect(),
|
||||
None => return n.deep_text(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+52
-23
@@ -320,6 +320,9 @@ pub(crate) struct Recoded {
|
||||
/// Set when the image's colors are converted to the destination without its ICC profile,
|
||||
/// which can't be read.
|
||||
pub note: Option<&'static str>,
|
||||
/// Set when the colors were to be converted but the image couldn't be decoded within the
|
||||
/// allowance or written with them: the source image, kept as it is, would be in its own colors.
|
||||
pub unconverted: bool,
|
||||
}
|
||||
|
||||
/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB (Convert to
|
||||
@@ -521,7 +524,10 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic
|
||||
/// they carry when `profiles` keeps it ([`SourceProfiles::Keep`]); with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB
|
||||
/// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as
|
||||
/// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be
|
||||
/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB.
|
||||
/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. When
|
||||
/// `convert` was to convert its colors, it is [`Recoded::unconverted`] if its header can't be read
|
||||
/// (it may be in color) or its pixels are beyond the decode allowance; a color image whose pixel
|
||||
/// data can't be read is not.
|
||||
pub(crate) fn recode(
|
||||
bytes: &[u8],
|
||||
size: (f64, f64),
|
||||
@@ -531,7 +537,7 @@ pub(crate) fn recode(
|
||||
profiles: SourceProfiles,
|
||||
to_srgb: Option<ToSrgb>,
|
||||
) -> Recoded {
|
||||
let keep = Recoded { image: None, warning: None, note: None };
|
||||
let keep = Recoded { image: None, warning: None, note: None, unconverted: convert.is_some() };
|
||||
let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep };
|
||||
let jpeg = reader.format() == Some(ImageFormat::Jpeg);
|
||||
let Ok(mut decoder) = reader.into_decoder() else { return keep };
|
||||
@@ -549,23 +555,25 @@ pub(crate) fn recode(
|
||||
note = Some(CONVERTED_AS_SRGB);
|
||||
None
|
||||
}
|
||||
Some((None, _)) => return Recoded { image: None, warning: Some(UNCONVERTED), note: None },
|
||||
Some((None, _)) => return Recoded { image: None, warning: Some(UNCONVERTED), note: None, unconverted: false },
|
||||
None => None,
|
||||
};
|
||||
// Pixels that can't be decoded are kept as they are, with a warning when they were to be
|
||||
// converted.
|
||||
let keep = if source.is_some() { Recoded { image: None, warning: Some(UNDECODED), note: None } } else { keep };
|
||||
let keep = if source.is_some() { Recoded { warning: Some(UNDECODED), ..keep } } else { keep };
|
||||
// What the header declares is decoded within the image allowance, not whatever it asks for.
|
||||
// Grey pixels aren't converted.
|
||||
if decoder.set_limits(limits()).is_err() {
|
||||
return keep;
|
||||
return Recoded { unconverted: convert.is_some() && !grey, ..keep };
|
||||
}
|
||||
let (mut kind, pixels) = if grey {
|
||||
// Only the pixels tell monochrome images from greyscale ones: decoded unless both keep it.
|
||||
let (g, m) = (rule(c, Kind::Gray), rule(c, Kind::Mono));
|
||||
if source.is_none() && kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead {
|
||||
return Recoded { image: None, warning: g.instead, note: None };
|
||||
return Recoded { image: None, warning: g.instead, note: None, unconverted: false };
|
||||
}
|
||||
let Ok(img) = DynamicImage::from_decoder(decoder) else { return keep };
|
||||
// Grey pixels aren't converted.
|
||||
let Ok(img) = DynamicImage::from_decoder(decoder) else { return Recoded { unconverted: false, ..keep } };
|
||||
(if bilevel(&img) { Kind::Mono } else { Kind::Gray }, Some(img))
|
||||
} else {
|
||||
(Kind::Color, None)
|
||||
@@ -573,9 +581,14 @@ pub(crate) fn recode(
|
||||
let mut rule = rule(c, kind);
|
||||
let convert = convert.filter(|_| kind == Kind::Color);
|
||||
if kept(&rule, dims, size, jpeg) && convert.is_none() && source.is_none() {
|
||||
return Recoded { image: None, warning: rule.instead, note: None };
|
||||
return Recoded { image: None, warning: rule.instead, note: None, unconverted: false };
|
||||
}
|
||||
let Some(mut img) = pixels.or_else(|| decoded(bytes)) else { return keep };
|
||||
// Pixels that can't be read can't be written in their own colors either; ones beyond the
|
||||
// allowance can.
|
||||
let mut img = match pixels.map_or_else(|| decoded_within(bytes), Ok) {
|
||||
Ok(img) => img,
|
||||
Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep },
|
||||
};
|
||||
if let Some((p, t)) = &source {
|
||||
let srgb = match into_srgb(img, p, t.intent) {
|
||||
Some(s) => Some(s),
|
||||
@@ -585,7 +598,7 @@ pub(crate) fn recode(
|
||||
note = Some(CONVERTED_AS_SRGB);
|
||||
None
|
||||
}
|
||||
None => return Recoded { image: None, warning: Some(UNCONVERTED), note: None },
|
||||
None => return Recoded { image: None, warning: Some(UNCONVERTED), note: None, unconverted: false },
|
||||
};
|
||||
img = match srgb {
|
||||
Some((srgb, changed)) => {
|
||||
@@ -604,18 +617,19 @@ pub(crate) fn recode(
|
||||
&& let Some(data) = jpeg_data(bytes, profiles == SourceProfiles::Remove)
|
||||
{
|
||||
let image = Image::from_jpeg_with_icc(data.into(), None, interpolate).ok();
|
||||
return Recoded { image, warning: rule.instead, note: None };
|
||||
return Recoded { image, warning: rule.instead, note: None, unconverted: false };
|
||||
}
|
||||
// Not resampled and lossless: written at its own depth.
|
||||
if as_is && jpeg_quality(&rule, jpeg).is_none() {
|
||||
return Recoded { image: from_decoded(srgb, None, interpolate, t.sixteen_bit), warning: rule.instead, note: None };
|
||||
let image = from_decoded(srgb, None, interpolate, t.sixteen_bit);
|
||||
return Recoded { image, warning: rule.instead, note: None, unconverted: false };
|
||||
}
|
||||
srgb
|
||||
}
|
||||
None => {
|
||||
let Some(img) = decoded(bytes) else { return keep };
|
||||
img
|
||||
}
|
||||
None => match decoded_within(bytes) {
|
||||
Ok(img) => img,
|
||||
Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep },
|
||||
},
|
||||
};
|
||||
}
|
||||
// Pixels that keep their colours keep the profile they are in; converted ones are in the
|
||||
@@ -650,7 +664,8 @@ pub(crate) fn recode(
|
||||
to_jpeg(&samples, space, width, height, q, interpolate, icc.as_deref().map(Vec::as_slice))
|
||||
});
|
||||
let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert, icc));
|
||||
Recoded { image, warning: rule.instead, note }
|
||||
let unconverted = image.is_none() && convert.is_some();
|
||||
Recoded { image, warning: rule.instead, note, unconverted }
|
||||
}
|
||||
|
||||
/// A colorized image's coverage (one sample a pixel, `w` × `h`, see
|
||||
@@ -681,6 +696,7 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec<u8>, size: (f64, f64), c
|
||||
/// [`mask_alpha`]) the image is lossless and carries it as its soft mask; `None` then when its
|
||||
/// inks can't be read. When its numbers are kept, the image is tagged as `tag` says, and is
|
||||
/// untagged without a profile; converted pixels are never tagged with it.
|
||||
/// With `convert`, an image whose inks can't be read or written is [`Recoded::unconverted`].
|
||||
pub(crate) fn recode_cmyk(
|
||||
blob: &ImageBlob,
|
||||
size: (f64, f64),
|
||||
@@ -704,16 +720,22 @@ pub(crate) fn recode_cmyk(
|
||||
let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS)
|
||||
.then(|| Image::from_jpeg_with_icc(data.into(), icc.map(|i| i.to_vec().into()), interpolate).ok())
|
||||
.flatten();
|
||||
return Recoded { image, warning: rule.instead, note: None };
|
||||
return Recoded { image, warning: rule.instead, note: None, unconverted: false };
|
||||
}
|
||||
}
|
||||
// Inks that can't be read can't be converted: the image is not to be kept as it is.
|
||||
let unconverted = Recoded { image: None, warning: None, note: None, unconverted: true };
|
||||
let Some(inks) = blob.cmyk() else {
|
||||
return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), note: None };
|
||||
if convert.is_some() {
|
||||
return unconverted;
|
||||
}
|
||||
return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), note: None, unconverted: false };
|
||||
};
|
||||
let (width, height) = sized(&rule, (inks.width, inks.height), size);
|
||||
let (inks, alpha) = match resampled_inks(inks, alpha, &rule, (width, height)) {
|
||||
Ok(r) => r,
|
||||
Err(warning) => return Recoded { image: None, warning, note: None },
|
||||
Err(_) if convert.is_some() => return unconverted,
|
||||
Err(warning) => return Recoded { image: None, warning, note: None, unconverted: false },
|
||||
};
|
||||
let (samples, space) = match convert {
|
||||
Some(p) => p.convert(&inks),
|
||||
@@ -722,7 +744,8 @@ pub(crate) fn recode_cmyk(
|
||||
// JPEG needs opaque pixels.
|
||||
let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate, icc));
|
||||
let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate, icc));
|
||||
Recoded { image, warning: rule.instead, note: None }
|
||||
let unconverted = image.is_none() && convert.is_some();
|
||||
Recoded { image, warning: rule.instead, note: None, unconverted }
|
||||
}
|
||||
|
||||
/// Ink amounts (four bytes a pixel) and their alpha (one byte a pixel), if any.
|
||||
@@ -767,9 +790,15 @@ fn limits() -> image::Limits {
|
||||
|
||||
/// `bytes` decoded within [`limits`]: an image whose header asks for more is not decoded.
|
||||
fn decoded(bytes: &[u8]) -> Option<DynamicImage> {
|
||||
let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
decoded_within(bytes).ok()
|
||||
}
|
||||
|
||||
/// `bytes` decoded like [`decoded`]; on failure, whether the decoder stopped at [`limits`]
|
||||
/// (`true`) rather than at data it can't read (`false`).
|
||||
fn decoded_within(bytes: &[u8]) -> Result<DynamicImage, bool> {
|
||||
let mut r = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| false)?;
|
||||
r.limits(limits());
|
||||
r.decode().ok()
|
||||
r.decode().map_err(|e| matches!(e, image::ImageError::Limits(_)))
|
||||
}
|
||||
|
||||
/// The alpha an opacity mask whose art is greyscale image `blob` alone gives the image of
|
||||
|
||||
@@ -239,6 +239,14 @@ pub fn imports_of(bytes: &[u8]) -> usize {
|
||||
IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The widest bleed of `pages` on each side (`[top, bottom, left, right]`, see [`crate::pages::bleed`]).
|
||||
fn widest_bleed<'p, 'd: 'p>(pages: impl Iterator<Item = &'p craft_pdf::syntax::page::Page<'d>>) -> [f64; 4] {
|
||||
pages.fold([0.0; 4], |widest, page| {
|
||||
let bleed = crate::pages::bleed(page);
|
||||
std::array::from_fn(|i| widest[i].max(bleed[i]))
|
||||
})
|
||||
}
|
||||
|
||||
/// [`read_with_reader_options`] of `original`, the PDF `bytes` read with `reader`.
|
||||
fn read_opened(
|
||||
bytes: &[u8],
|
||||
@@ -286,15 +294,17 @@ fn read_opened(
|
||||
let mut nesting = Nesting::new();
|
||||
// The top-level groups in the order the pages mark them, bottom first.
|
||||
let (mut order, mut known) = (vec![], HashSet::new());
|
||||
// Artboards on the trim boxes have the bleed boxes round them as the document's bleed, so the
|
||||
// art there shows and prints as bleed.
|
||||
if opts.crop == CropTo::Trim {
|
||||
doc.setup.bleed = widest_bleed(picked.iter().filter_map(|&n| pages.get(n)));
|
||||
}
|
||||
// The artboards are the gap apart plus the document's bleed on both sides, which export adds
|
||||
// round every artboard, so no page's bleed reaches into the next artboard.
|
||||
let [_, _, bleed_left, bleed_right] = doc.setup.bleed;
|
||||
let spacing = opts.artboard_gap + bleed_left + bleed_right;
|
||||
for (i, &number) in picked.iter().enumerate() {
|
||||
let Some(page) = pages.get(number) else { continue };
|
||||
// Artboards on the trim boxes have the bleed boxes round them as the document's bleed
|
||||
// (the widest of the pages' on each side), so the art there shows and prints as bleed.
|
||||
if opts.crop == CropTo::Trim {
|
||||
for (side, b) in doc.setup.bleed.iter_mut().zip(crate::pages::bleed(page)) {
|
||||
*side = side.max(b);
|
||||
}
|
||||
}
|
||||
// The chosen box sits at (x, 0); the page draws round it.
|
||||
let (init, frame) = crate::pages::frame(page, opts.crop);
|
||||
let mut ab = Rect::new(x, 0.0, x + frame.width(), frame.height());
|
||||
@@ -371,7 +381,7 @@ fn read_opened(
|
||||
right = right.max(art.x1);
|
||||
ab = art;
|
||||
}
|
||||
x = right + opts.artboard_gap;
|
||||
x = right + spacing;
|
||||
clear = right.max(art_right) + opts.artboard_gap;
|
||||
doc.artboards.push(Artboard {
|
||||
id: i as u32 + 1,
|
||||
|
||||
@@ -134,7 +134,8 @@ impl PdfOptions {
|
||||
pub struct ImportOptions {
|
||||
/// Import at most this many pages (of those picked); `None` = all of them.
|
||||
pub max_pages: Option<usize>,
|
||||
/// Horizontal gap in points between the artboards created for consecutive pages.
|
||||
/// Horizontal gap in points between the artboards created for consecutive pages (on trim
|
||||
/// boxes, plus the document's bleed on both sides).
|
||||
pub artboard_gap: f64,
|
||||
/// 0-based pages to import, in this order; `None` = every page.
|
||||
pub pages: Option<Vec<usize>>,
|
||||
|
||||
@@ -622,6 +622,38 @@ fn a_kept_cmyk_jpeg_declaring_too_many_pixels_is_left_out() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK JPEG whose inks can't be read (it declares more pixels than CMYK images are decoded
|
||||
/// with, though fewer than the writer embeds) is written with its own numbers only when they are
|
||||
/// kept: when the Output settings convert its colors it is left out with a warning, in every
|
||||
/// standard.
|
||||
#[test]
|
||||
fn a_cmyk_jpeg_whose_inks_cant_be_read_is_left_out_when_its_colors_are_converted() {
|
||||
let mut jpg = cmyk_jpeg(&flat([0, 102, 255, 0], 4), 2, 2);
|
||||
// Height and width of the SOF0 segment (after its marker, length and precision): 8200 × 8200.
|
||||
let sof = jpg.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap();
|
||||
jpg[sof + 5..sof + 9].copy_from_slice(&[0x20, 0x08, 0x20, 0x08]);
|
||||
let blob = ImageBlob::new("image/jpeg", jpg);
|
||||
assert!(blob.is_cmyk() && blob.cmyk().is_none());
|
||||
let d = image_doc(blob, 2, 2);
|
||||
let out = export_with_report(&d, &opts(json!({}))).unwrap();
|
||||
let kept = written(&out.bytes);
|
||||
assert!(kept.len() == 1 && kept[0].space == "DeviceCMYK", "kept as it is: {kept:?}");
|
||||
let unconverted = "an image couldn't be converted to the Output destination and is missing from the picture";
|
||||
for s in [
|
||||
json!({"output": {"conversion": "destination", "destination": DEVICE_CMYK}}),
|
||||
json!({"output": {"conversion": "destination", "destination": SRGB}}),
|
||||
json!({"standard": "pdfX1a", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}),
|
||||
json!({"standard": "pdfX4", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}),
|
||||
json!({"standard": "pdfA2b", "output": {"conversion": "destination", "destination": DEVICE_CMYK}}),
|
||||
] {
|
||||
let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}"));
|
||||
assert!(written(&out.bytes).is_empty(), "{s}");
|
||||
assert!(out.warnings.iter().any(|w| w == unconverted), "{s}: {:?}", out.warnings);
|
||||
let other = out.warnings.iter().any(|w| w.contains("couldn't be decoded") || w.contains("written as it is"));
|
||||
assert!(!other, "{s}: {:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// The profile each transparency group of written PDF `bytes` blends in: its ICC-based space's
|
||||
/// profile, or `None` for DeviceCMYK.
|
||||
fn group_profiles(bytes: &[u8]) -> Vec<Option<Vec<u8>>> {
|
||||
|
||||
@@ -270,6 +270,54 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() {
|
||||
assert!(r.image.is_none(), "kept as it is");
|
||||
}
|
||||
|
||||
/// When the Output settings convert colors, a color image beyond the decode allowance can't be
|
||||
/// kept as it is: it is unconverted, and so is one whose header can't be read. A color image
|
||||
/// whose pixel data can't be read (tagged with an ICC profile it is converted from or not) can't
|
||||
/// be written in its own colors either, and is kept as it is, as is a grey one, whose pixels
|
||||
/// aren't converted, and any image without a conversion.
|
||||
#[test]
|
||||
fn a_color_image_beyond_the_allowance_for_a_conversion_is_unconverted() {
|
||||
use vectorcraft_color::cms::{DISPLAY_P3, GENERIC_CMYK, icc_bytes};
|
||||
let d = doc(encoded(colour(), ImageFormat::Png), "image/png");
|
||||
let settings: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})).unwrap();
|
||||
let out = crate::output::ColorOut::new(&d, &settings).unwrap();
|
||||
assert!(out.pixels().is_some());
|
||||
let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: false });
|
||||
assert!(to_srgb.is_some());
|
||||
let c: CompressionSettings = serde_json::from_value(json!({})).unwrap();
|
||||
let half = |mut bytes: Vec<u8>| {
|
||||
bytes.truncate(bytes.len() / 2);
|
||||
bytes
|
||||
};
|
||||
let cut = |img: DynamicImage| half(encoded(img, ImageFormat::Png));
|
||||
let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec();
|
||||
p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]);
|
||||
// `declared_png`'s header declaring RGB pixels (color type 2), with the IHDR chunk's CRC
|
||||
// written again.
|
||||
let mut rgb_declared = declared_png(60_000, 60_000);
|
||||
rgb_declared[25] = 2;
|
||||
let mut crc = flate2::Crc::new();
|
||||
crc.update(&rgb_declared[12..29]);
|
||||
rgb_declared[29..33].copy_from_slice(&crc.sum().to_be_bytes());
|
||||
let cases = [
|
||||
("RGB declaring more than the allowance", rgb_declared, true),
|
||||
("RGB", cut(colour()), false),
|
||||
("tagged RGB", half(tagged(&colour(), &p3, ImageFormat::Png)), false),
|
||||
("unreadable", vec![1, 2, 3], true),
|
||||
("grey", cut(colour().grayscale()), false),
|
||||
("grey declaring more than the allowance", declared_png(60_000, 60_000), false),
|
||||
];
|
||||
for (what, bytes, unconverted) in cases {
|
||||
let r = crate::images::recode(&bytes, (72.0, 72.0), &c, false, out.pixels(), crate::images::SourceProfiles::Keep, to_srgb);
|
||||
assert!(r.image.is_none(), "{what}");
|
||||
assert_eq!(r.unconverted, unconverted, "{what}");
|
||||
assert!(
|
||||
!crate::images::recode(&bytes, (72.0, 72.0), &c, false, None, crate::images::SourceProfiles::Keep, None).unconverted,
|
||||
"{what}, no conversion"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A version 2.1 display ICC profile for colour space `space` (`RGB ` or `GRAY`), `len` bytes in
|
||||
/// all, with an empty tag table, every byte after the tag count different from its neighbors.
|
||||
fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> {
|
||||
|
||||
@@ -91,6 +91,27 @@ fn trim_box_artboards_take_the_bleed_box_round_them_as_the_document_bleed() {
|
||||
assert_eq!((d.artboards[0].rect.width(), d.setup.bleed), (300.0, [0.0; 4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_box_artboards_keep_the_bleed_between_them() {
|
||||
// The second page's bleed box is its trim box: the document's bleed (10 mm, over half the
|
||||
// 36 pt gap) still goes round its artboard.
|
||||
let edge = Some([50.0, 50.0, 250.0, 150.0]);
|
||||
let plain = PdfPage { bleed: edge, trim: edge, ..PdfPage::new(300.0, 200.0, "0 g 50 50 200 100 re f") };
|
||||
let bytes = pdf(&[bled_page(), plain, bled_page()], None);
|
||||
let d = open(&bytes, ImportOptions { crop: CropTo::Trim, ..Default::default() });
|
||||
let starts: Vec<f64> = d.artboards.iter().map(|a| a.rect.x0).collect();
|
||||
let step = 200.0 + 36.0 + 2.0 * BLEED;
|
||||
assert!(near([starts[0], starts[1], starts[2], 0.0], [0.0, step, 2.0 * step, 0.0]), "{starts:?}");
|
||||
// Each artboard's bleed ends 36 pt before the next one's begins.
|
||||
for pair in d.artboards.windows(2) {
|
||||
let (a, b) = (d.setup.bleed_rect(pair[0].rect), d.setup.bleed_rect(pair[1].rect));
|
||||
assert!((b.x0 - a.x1 - 36.0).abs() < 1e-3, "{a:?} {b:?}");
|
||||
}
|
||||
// On the crop boxes there is no bleed, and the artboards are 36 pt apart.
|
||||
let d = open(&bytes, ImportOptions::default());
|
||||
assert_eq!(d.artboards.iter().map(|a| a.rect.x0).collect::<Vec<_>>(), [0.0, 336.0, 672.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_boxes_fall_back_to_the_crop_box_and_boxes_are_clipped_to_the_media_box() {
|
||||
let page = PdfPage { crop: Some([10.0, 10.0, 290.0, 390.0]), art: Some([-50.0, 0.0, 100.0, 100.0]), ..PdfPage::new(300.0, 400.0, "") };
|
||||
|
||||
@@ -19,13 +19,12 @@ vello_cpu = { workspace = true }
|
||||
# Filter types (Gaussian blur, drop shadow) are not re-exported by vello_cpu 0.2.
|
||||
vello_common = { version = "0.2", default-features = false }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
jpeg-encoder = { workspace = true }
|
||||
gif = { workspace = true }
|
||||
# TIFF LZW compression (MIT OR Apache-2.0; already used by the image crate's TIFF reader).
|
||||
weezl = "0.2"
|
||||
# PNG rows read one at a time (MIT OR Apache-2.0; already used by the image crate's PNG reader).
|
||||
png = "0.18"
|
||||
log = { workspace = true }
|
||||
# Combining marks inside a lam-alef cluster (MIT OR Apache-2.0; already used by vectorcraft-text).
|
||||
unicode-general-category = "1"
|
||||
@@ -47,8 +46,7 @@ vectorcraft-plugins = { workspace = true }
|
||||
wat = { workspace = true }
|
||||
# Decoders the export tests read their files back with.
|
||||
image = { workspace = true, features = ["tga"] }
|
||||
tiff = "0.11"
|
||||
# Reads the PSD exports back (MIT OR Apache-2.0).
|
||||
psd = "0.3"
|
||||
craft-tiff = { workspace = true }
|
||||
craft-psd = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -86,8 +86,10 @@ fn gray_and_bilevel_images_store_gray() {
|
||||
assert_eq!(gray(&file), levels);
|
||||
let (mime, file) = img.to_bilevel(150.0).unwrap();
|
||||
assert_eq!(mime, "image/tiff");
|
||||
let mut d = ::tiff::decoder::Decoder::new(std::io::Cursor::new(&file)).unwrap();
|
||||
assert_eq!(d.colortype().unwrap(), ::tiff::ColorType::Gray(1));
|
||||
let tiff = craft_tiff::Tiff::parse(&file).unwrap();
|
||||
let ifd = &tiff.ifds[0];
|
||||
assert_eq!(ifd.u16(craft_tiff::tags::SAMPLES_PER_PIXEL), Some(1));
|
||||
assert_eq!(ifd.value(craft_tiff::tags::BITS_PER_SAMPLE).unwrap().to_u64_vec(), vec![1]);
|
||||
let bw: Vec<u8> = [0u8, 0, 255, 255, 255, 0].iter().flat_map(|&g| [g, 255]).collect();
|
||||
assert_eq!(gray(&file), bw, "from 128 up is white");
|
||||
// Half-covered white over the light grey; a clear pixel is white.
|
||||
|
||||
@@ -144,9 +144,18 @@ fn unpack(mut src: &[u8], out: &mut Vec<u8>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The composite as a reader sees it.
|
||||
/// The stored composite: RGB stays white-matted, with its original alpha.
|
||||
fn merged(f: &[u8]) -> Vec<u8> {
|
||||
::psd::Psd::from_bytes(f).expect("a PSD a reader takes").rgba()
|
||||
let psd = craft_psd::PsdFile::from_bytes(f).expect("a PSD a reader takes");
|
||||
if psd.header.color_mode != craft_psd::ColorMode::Rgb {
|
||||
return psd.composite_rgba8().expect("composite").data;
|
||||
}
|
||||
assert_eq!(psd.header.depth, 8);
|
||||
let samples = psd.decode_merged().expect("stored composite planes");
|
||||
let count = psd.header.width as usize * psd.header.height as usize;
|
||||
(0..count)
|
||||
.flat_map(|i| [samples[i], samples[count + i], samples[2 * count + i], if psd.merged_has_alpha() { samples[3 * count + i] } else { 255 }])
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pixel(px: &[u8], width: usize, x: usize, y: usize) -> [u8; 4] {
|
||||
@@ -168,11 +177,12 @@ fn layers_are_the_top_level_layers_and_the_merged_image_is_the_render() {
|
||||
assert_eq!(p.records[1].rect, [0, 0, 50, 60], "the blue square and the corner");
|
||||
|
||||
// A reader decodes it: the layers, in place, and the merged image.
|
||||
let psd = ::psd::Psd::from_bytes(&file).unwrap();
|
||||
assert_eq!((psd.width(), psd.height(), psd.layers().len()), (100, 60, 2));
|
||||
let red = psd.layer_by_name("Layer 1").unwrap().rgba();
|
||||
assert_eq!(pixel(&red, 100, 20, 20), [255, 0, 0, 255]);
|
||||
assert_eq!(pixel(&red, 100, 50, 45)[3], 0, "the blue square isn't on Layer 1");
|
||||
let psd = craft_psd::PsdFile::from_bytes(&file).unwrap();
|
||||
assert_eq!((psd.header.width, psd.header.height, psd.layers().len()), (100, 60, 2));
|
||||
let layer = psd.iter_layers().find(|l| l.name() == "Layer 1").unwrap();
|
||||
assert_eq!(layer.record.rect, craft_psd::layer::Rect { top: 10, left: 10, bottom: 40, right: 40 });
|
||||
let red = layer.rgba8().unwrap().data;
|
||||
assert_eq!(pixel(&red, 30, 10, 10), [255, 0, 0, 255]);
|
||||
|
||||
// The merged image is the flat render: colours on white where transparent, alpha apart.
|
||||
let img = Renderer::new().render_region_with(&doc, doc.artboards[0].rect, 1.0, &opts(PsdOptions::default()).render_options(RasterFormat::Psd));
|
||||
@@ -200,7 +210,7 @@ fn flat_writes_the_merged_image_alone_on_white() {
|
||||
assert_eq!(o.encode(&img, RasterFormat::Psd).unwrap(), file);
|
||||
let file = export(&doc, &RasterExportOptions { ppi: 150.0, ..o });
|
||||
assert_eq!(u32_at(parse(&file).resources, 12), 150 << 16);
|
||||
assert_eq!(::psd::Psd::from_bytes(&file).unwrap().width(), 208);
|
||||
assert_eq!(craft_psd::PsdFile::from_bytes(&file).unwrap().header.width, 208);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -230,8 +240,11 @@ fn maximum_editability_writes_groups_and_an_object_per_layer() {
|
||||
assert_eq!((p.records[4].opacity, p.records[4].blend, p.records[4].rect), (128, *b"mul ", [20, 30, 50, 60]));
|
||||
assert_eq!((p.records[8].blend, p.records[8].opacity), (*b"pass", 255));
|
||||
assert_eq!(p.records[6].rect, [0, 0, 6, 6]);
|
||||
let psd = ::psd::Psd::from_bytes(&file).unwrap();
|
||||
assert_eq!((psd.layers().len(), psd.groups().len()), (3, 3));
|
||||
let psd = craft_psd::PsdFile::from_bytes(&file).unwrap();
|
||||
let content_layers = psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::Other)).count();
|
||||
let groups =
|
||||
psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::OpenFolder | craft_psd::SectionType::ClosedFolder)).count();
|
||||
assert_eq!((content_layers, groups), (3, 3));
|
||||
assert_eq!(merged(&file), merged(&export(&doc, &opts(PsdOptions::default()))), "the same merged image");
|
||||
|
||||
// Hidden layers: written hidden, drawn as if visible, instead of left out.
|
||||
@@ -300,8 +313,8 @@ fn a_background_colour_is_the_bottom_layer() {
|
||||
let p = parse(&file);
|
||||
assert_eq!((p.channels, p.count), (3, 3), "opaque: no merged alpha");
|
||||
assert_eq!((p.records[0].name.as_str(), p.records[0].rect), ("Background", [0, 0, 60, 100]));
|
||||
let psd = ::psd::Psd::from_bytes(&file).unwrap();
|
||||
assert!(psd.layer_by_name("Background").unwrap().rgba().chunks(4).all(|p| p == [0, 0, 255, 255]));
|
||||
let psd = craft_psd::PsdFile::from_bytes(&file).unwrap();
|
||||
assert!(psd.iter_layers().find(|l| l.name() == "Background").unwrap().rgba8().unwrap().data.chunks(4).all(|p| p == [0, 0, 255, 255]));
|
||||
assert_eq!(pixel(&merged(&file), 100, 5, 50), [0, 0, 255, 255]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
//! TIFF export: byte order, LZW, colour models and samples, resolution, profile, strips.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use tiff::decoder::{Decoder, DecodingResult};
|
||||
use tiff::tags::Tag;
|
||||
use craft_tiff::Tiff;
|
||||
use craft_tiff::tags;
|
||||
|
||||
use super::jpeg::ColorModel;
|
||||
use super::tiff::{self as t, ByteOrder, Compression, Image, Layout, Photometric, TiffOptions};
|
||||
|
||||
fn decoder(file: &[u8]) -> Decoder<Cursor<&[u8]>> {
|
||||
Decoder::new(Cursor::new(file)).expect("a TIFF")
|
||||
fn ifd0(file: &[u8]) -> craft_tiff::Ifd {
|
||||
Tiff::parse(file).expect("a TIFF").ifds.into_iter().next().expect("IFD0")
|
||||
}
|
||||
|
||||
fn tag_u16_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option<Vec<u16>> {
|
||||
ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u16).collect())
|
||||
}
|
||||
|
||||
fn tag_u32_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option<Vec<u32>> {
|
||||
ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u32).collect())
|
||||
}
|
||||
|
||||
fn pixels(file: &[u8]) -> Vec<u8> {
|
||||
match decoder(file).read_image().expect("decodes") {
|
||||
DecodingResult::U8(v) => v,
|
||||
_ => panic!("8-bit samples"),
|
||||
}
|
||||
craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, file).expect("decodes").into_data()
|
||||
}
|
||||
|
||||
/// Straight RGBA: flat areas (as art is) with a transparent corner when `clear`.
|
||||
@@ -46,7 +49,7 @@ fn byte_order_writes_an_ii_or_mm_header() {
|
||||
assert_eq!(&file[..4], magic);
|
||||
let rgb: Vec<u8> = px.chunks(4).flat_map(|p| &p[..3]).copied().collect();
|
||||
assert_eq!(pixels(&file), rgb, "{order:?}");
|
||||
assert_eq!(decoder(&file).get_tag_ascii_string(Tag::Software).unwrap(), "VectorCraft");
|
||||
assert_eq!(ifd0(&file).string(tags::SOFTWARE).as_deref(), Some("VectorCraft"));
|
||||
}
|
||||
for (s, o) in [("little", ByteOrder::Little), ("MM", ByteOrder::Big), ("mac", ByteOrder::Big), ("ii", ByteOrder::Little), ("big", ByteOrder::Big)]
|
||||
{
|
||||
@@ -61,44 +64,51 @@ fn lzw_is_smaller_and_decodes_the_same() {
|
||||
let plain = t::encode_samples(&px, 120, 90, 72.0, &TiffOptions { lzw: false, ..opts(ColorModel::Rgb) }).unwrap();
|
||||
let lzw = t::encode_samples(&px, 120, 90, 72.0, &opts(ColorModel::Rgb)).unwrap();
|
||||
assert!(lzw.len() * 4 < plain.len(), "{} vs {}", lzw.len(), plain.len());
|
||||
assert_eq!(decoder(&lzw).get_tag_unsigned::<u16>(Tag::Compression).unwrap(), 5);
|
||||
assert_eq!(decoder(&plain).get_tag_unsigned::<u16>(Tag::Compression).unwrap(), 1);
|
||||
assert_eq!(ifd0(&lzw).u16(tags::COMPRESSION), Some(5));
|
||||
assert_eq!(ifd0(&plain).u16(tags::COMPRESSION), Some(1));
|
||||
assert_eq!(pixels(&lzw), px, "transparency kept as an alpha channel");
|
||||
assert_eq!(pixels(&plain), px);
|
||||
// The image crate reads it too.
|
||||
let img = image::load_from_memory_with_format(&lzw, image::ImageFormat::Tiff).unwrap().to_rgba8();
|
||||
assert_eq!(img.into_raw(), px);
|
||||
let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &lzw).unwrap();
|
||||
assert_eq!(img.data(), px);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_models_write_their_samples() {
|
||||
let px = art(9, 6, true);
|
||||
let rgba = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap();
|
||||
assert_eq!(decoder(&rgba).colortype().unwrap(), tiff::ColorType::RGBA(8));
|
||||
assert_eq!(decoder(&rgba).get_tag_u16_vec(Tag::ExtraSamples).unwrap(), [2], "unassociated alpha");
|
||||
let rgba_ifd = ifd0(&rgba);
|
||||
assert_eq!(rgba_ifd.u16(tags::PHOTOMETRIC), Some(2));
|
||||
assert_eq!(rgba_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(4));
|
||||
assert_eq!(tag_u16_vec(&rgba_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8, 8, 8, 8].as_slice()));
|
||||
assert_eq!(tag_u16_vec(&rgba_ifd, tags::EXTRA_SAMPLES).as_deref(), Some([2].as_slice()), "unassociated alpha");
|
||||
let opaque = art(9, 6, false);
|
||||
let rgb = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap();
|
||||
assert_eq!(decoder(&rgb).colortype().unwrap(), tiff::ColorType::RGB(8));
|
||||
assert!(decoder(&rgb).find_tag(Tag::ExtraSamples).unwrap().is_none());
|
||||
let rgb_ifd = ifd0(&rgb);
|
||||
assert_eq!(rgb_ifd.u16(tags::PHOTOMETRIC), Some(2));
|
||||
assert_eq!(rgb_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(3));
|
||||
assert!(rgb_ifd.value(tags::EXTRA_SAMPLES).is_none());
|
||||
|
||||
let gray = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap();
|
||||
assert_eq!(decoder(&gray).colortype().unwrap(), tiff::ColorType::Gray(8));
|
||||
assert_eq!(decoder(&gray).get_tag_unsigned::<u16>(Tag::PhotometricInterpretation).unwrap(), 1, "black is zero");
|
||||
let gray_ifd = ifd0(&gray);
|
||||
assert_eq!(gray_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1));
|
||||
assert_eq!(tag_u16_vec(&gray_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8].as_slice()));
|
||||
assert_eq!(gray_ifd.u16(tags::PHOTOMETRIC), Some(1), "black is zero");
|
||||
let g = pixels(&gray);
|
||||
assert_eq!((g[0], g[8]), (super::jpeg::to_gray()([200, 30, 40]), 255), "lightness; white stays white");
|
||||
let on_white = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap();
|
||||
assert_eq!(decoder(&on_white).colortype().unwrap(), tiff::ColorType::Gray(8), "grey has no alpha: few readers take it");
|
||||
let on_white_ifd = ifd0(&on_white);
|
||||
assert_eq!(on_white_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1), "grey has no alpha: few readers take it");
|
||||
assert_eq!(pixels(&on_white)[0], 255, "the transparent corner is white");
|
||||
|
||||
// CMYK: four samples a pixel, ink amounts as given.
|
||||
let inks: Vec<u8> = (0..9 * 6 * 4).map(|i| (i * 7 % 256) as u8).collect();
|
||||
let cmyk = t::encode_samples(&inks, 9, 6, 72.0, &opts(ColorModel::Cmyk)).unwrap();
|
||||
let mut d = decoder(&cmyk);
|
||||
assert_eq!(d.colortype().unwrap(), tiff::ColorType::CMYK(8));
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::SamplesPerPixel).unwrap(), 4);
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::PhotometricInterpretation).unwrap(), 5, "separated");
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::Unknown(332)).unwrap(), 1, "CMYK inks");
|
||||
assert_eq!(pixels(&cmyk), inks);
|
||||
let d = ifd0(&cmyk);
|
||||
assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(4));
|
||||
assert_eq!(d.u16(tags::PHOTOMETRIC), Some(5), "separated");
|
||||
assert_eq!(d.u16(332), Some(1), "CMYK inks");
|
||||
let cmyk_img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &cmyk).unwrap();
|
||||
assert_eq!(cmyk_img.data(), inks);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -106,16 +116,18 @@ fn resolution_tags_and_the_profile() {
|
||||
let px = art(4, 4, false);
|
||||
for (ppi, rational) in [(300.0, (300, 1)), (72.5, (7250, 100))] {
|
||||
let file = t::encode_samples(&px, 4, 4, ppi, &opts(ColorModel::Rgb)).unwrap();
|
||||
let mut d = decoder(&file);
|
||||
for tag in [Tag::XResolution, Tag::YResolution] {
|
||||
assert_eq!(d.get_tag(tag).unwrap(), tiff::decoder::ifd::Value::Rational(rational.0, rational.1));
|
||||
let d = ifd0(&file);
|
||||
for tag in [tags::X_RESOLUTION, tags::Y_RESOLUTION] {
|
||||
let Some(craft_tiff::Value::Rational(v)) = d.value(tag) else { panic!("rational") };
|
||||
assert_eq!(v.as_slice(), &[rational]);
|
||||
}
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::ResolutionUnit).unwrap(), 2, "inches");
|
||||
assert_eq!(d.u16(tags::RESOLUTION_UNIT), Some(2), "inches");
|
||||
}
|
||||
for model in ColorModel::ALL {
|
||||
let src = if model == ColorModel::Cmyk { vec![0; 64] } else { px.clone() };
|
||||
let file = t::encode_samples(&src, 4, 4, 72.0, &TiffOptions { embed_icc: true, ..opts(model) }).unwrap();
|
||||
let icc = decoder(&file).get_tag_u8_vec(Tag::IccProfile).unwrap();
|
||||
let ifd = ifd0(&file);
|
||||
let icc = ifd.bytes(tags::ICC_PROFILE).unwrap();
|
||||
assert_eq!(&icc[36..40], b"acsp", "{model:?}: an ICC profile");
|
||||
let space: &[u8; 4] = match model {
|
||||
ColorModel::Rgb => b"RGB ",
|
||||
@@ -125,7 +137,7 @@ fn resolution_tags_and_the_profile() {
|
||||
assert_eq!(&icc[16..20], space, "{model:?}");
|
||||
}
|
||||
let file = t::encode_samples(&px, 4, 4, 72.0, &opts(ColorModel::Rgb)).unwrap();
|
||||
assert!(decoder(&file).find_tag(Tag::IccProfile).unwrap().is_none());
|
||||
assert!(ifd0(&file).value(tags::ICC_PROFILE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -135,10 +147,10 @@ fn big_images_take_several_strips_in_either_order() {
|
||||
for order in ByteOrder::ALL {
|
||||
for lzw in [false, true] {
|
||||
let file = t::encode_samples(&px, w, h, 72.0, &TiffOptions { lzw, byte_order: order, ..opts(ColorModel::Gray) }).unwrap();
|
||||
let mut d = decoder(&file);
|
||||
let offsets = d.get_tag_u32_vec(Tag::StripOffsets).unwrap();
|
||||
let d = ifd0(&file);
|
||||
let offsets = tag_u32_vec(&d, tags::STRIP_OFFSETS).unwrap();
|
||||
// 300 bytes a row: 27 rows a strip.
|
||||
assert_eq!(d.get_tag_u32(Tag::RowsPerStrip).unwrap(), 27);
|
||||
assert_eq!(d.u32(tags::ROWS_PER_STRIP), Some(27));
|
||||
assert_eq!(offsets.len(), 4);
|
||||
assert!(offsets.iter().all(|o| o % 2 == 0), "strips start on a word");
|
||||
assert_eq!(pixels(&file).len(), (w * h) as usize, "{order:?} lzw {lzw}");
|
||||
@@ -152,11 +164,19 @@ fn packbits_and_bilevel_images_decode() {
|
||||
let rows = [0b1010_1010u8, 0b1100_0000, 0xFF, 0xC0, 0, 0];
|
||||
let image = Image { width: 10, height: 3, data: &rows, photometric: Photometric::WhiteIsZero, samples: 1, bits: 1, alpha: false };
|
||||
let file = t::write(&image, &Layout { byte_order: ByteOrder::Big, compression: Compression::PackBits, ppi: 72.0, icc: None }).unwrap();
|
||||
let mut d = decoder(&file);
|
||||
assert_eq!(d.colortype().unwrap(), tiff::ColorType::Gray(1));
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::Compression).unwrap(), 32773);
|
||||
let d = ifd0(&file);
|
||||
assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(1));
|
||||
assert_eq!(tag_u16_vec(&d, tags::BITS_PER_SAMPLE).as_deref(), Some([1].as_slice()));
|
||||
assert_eq!(d.u16(tags::COMPRESSION), Some(32773));
|
||||
// The decoder turns WhiteIsZero into black-is-zero.
|
||||
assert_eq!(pixels(&file), rows.map(|b| !b));
|
||||
let dec = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &file).unwrap();
|
||||
assert_eq!(dec.width(), 10);
|
||||
assert_eq!(dec.height(), 3);
|
||||
assert_eq!(
|
||||
dec.data(),
|
||||
[0, 255, 0, 255, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
|
||||
"WhiteIsZero samples are inverted and row padding is ignored"
|
||||
);
|
||||
// A buffer that doesn't match the size is refused, not written.
|
||||
let short = Image { data: &rows[..5], ..image };
|
||||
assert!(t::write(&short, &Layout { byte_order: ByteOrder::Little, compression: Compression::None, ppi: 72.0, icc: None }).is_err());
|
||||
|
||||
+173
-32
@@ -258,9 +258,13 @@ fn reduction(bytes: &[u8], allowance: u64) -> Option<Reduction> {
|
||||
return None;
|
||||
}
|
||||
let to = fitted_dims(w, h, allowance)?;
|
||||
// A PNG that isn't interlaced is read a row at a time when the reader's buffers fit the allowance.
|
||||
// A PNG that isn't interlaced or animated (and upright in pre-pixel EXIF) is read a row at a time when the reader's buffers fit the allowance.
|
||||
let row_scratch = if format == image::ImageFormat::Png {
|
||||
png_reader(bytes).filter(|r| !r.info().interlaced).and_then(|r| png_row_scratch(&r)).filter(|&s| s <= allowance)
|
||||
let streamed = craft_image_codecs::PngDecodeRows::new_streaming(bytes, &png_streaming_limits(allowance))
|
||||
.ok()
|
||||
.filter(|dec| dec.streamable())
|
||||
.and_then(|dec| png_row_scratch(&dec.header()));
|
||||
streamed.or_else(|| png_row_scratch_from_header(bytes, w, h, d.total_bytes())).filter(|&s| s <= allowance)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -272,6 +276,13 @@ fn reduction(bytes: &[u8], allowance: u64) -> Option<Reduction> {
|
||||
(rows || d.total_bytes() <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch })
|
||||
}
|
||||
|
||||
/// Streaming retains rows, not the declared full image. Preserve the renderer's source-pixel
|
||||
/// allowance even when RGBA16's declared samples exceed the shared whole-image default budget.
|
||||
/// Row scratch and the reduced pixmap are admitted separately before decoding starts.
|
||||
fn png_streaming_limits(source_pixels: u64) -> craft_image_codecs::Limits {
|
||||
craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: source_pixels, max_alloc: source_pixels.saturating_mul(8) }
|
||||
}
|
||||
|
||||
/// How many rows of an image decoded whole [`reduced_pixmap`] converts to RGBA at a time.
|
||||
const BAND: u32 = 16;
|
||||
|
||||
@@ -283,17 +294,58 @@ const PNG_KEPT_ROWS: u64 = 128 << 10;
|
||||
/// stream buffer grows by.
|
||||
const PNG_WINDOW_AND_STEP: u64 = (32 << 10) + (8 << 10);
|
||||
|
||||
/// The most memory `r` takes in its buffers to read its image a row at a time: the stream buffer
|
||||
/// holds the rows already read up to [`PNG_KEPT_ROWS`] or four rows, whichever is more, the previous
|
||||
/// and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer grows by doubling its reservation,
|
||||
/// and while it grows its old reservation and the new one, up to twice the size it holds, are both
|
||||
/// allocated: three times that size at most. A copy of a stored row and the row given out come on
|
||||
/// top. `None` when a row given out doesn't fit memory.
|
||||
fn png_row_scratch(r: &png::Reader<std::io::Cursor<&[u8]>>) -> Option<u64> {
|
||||
let info = r.info();
|
||||
// A filter byte and the row's samples, in whole bytes.
|
||||
let stored = 1 + (u64::from(info.width) * info.color_type.samples() as u64 * info.bit_depth as u64).div_ceil(8);
|
||||
let out = u64::try_from(r.output_line_size(info.width)?).ok()?;
|
||||
/// The most memory `craft-image-codecs`'s PNG row decoder takes in its buffers to read its image
|
||||
/// a row at a time: the stream buffer holds the rows already read up to [`PNG_KEPT_ROWS`] or four
|
||||
/// rows, whichever is more, the previous and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer
|
||||
/// grows by doubling its reservation, and while it grows its old reservation and the new one, up
|
||||
/// to twice the size it holds, are both allocated: three times that size at most. A copy of a
|
||||
/// stored row and the row given out come on top. `None` when a row given out doesn't fit memory.
|
||||
fn png_row_scratch(hdr: &craft_image_codecs::PngHeader) -> Option<u64> {
|
||||
let out = u64::from(hdr.width).checked_mul(hdr.layout.channels() as u64)?.checked_mul(hdr.sample.bytes() as u64)?;
|
||||
png_row_scratch_for_row(out)
|
||||
}
|
||||
|
||||
/// The row decoder rejects a truncated PNG's tiny IDAT before it can report its header. For a
|
||||
/// size estimate, the image decoder still gives us the declared output bytes; use those only when
|
||||
/// the PNG header says it is a static, non-interlaced image, the format the renderer can stream.
|
||||
fn png_row_scratch_from_header(bytes: &[u8], width: u32, height: u32, total_bytes: u64) -> Option<u64> {
|
||||
const SIG: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
|
||||
if bytes.get(..8)? != SIG || height == 0 || !total_bytes.is_multiple_of(u64::from(height)) {
|
||||
return None;
|
||||
}
|
||||
let mut at = 8usize;
|
||||
let mut header = false;
|
||||
loop {
|
||||
let len = u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?) as usize;
|
||||
let kind = bytes.get(at + 4..at + 8)?;
|
||||
let data_at = at.checked_add(8)?;
|
||||
let end = data_at.checked_add(len)?;
|
||||
let data = bytes.get(data_at..end)?;
|
||||
match kind {
|
||||
b"IHDR" if len == 13 && !header => {
|
||||
header = true;
|
||||
if at != 8
|
||||
|| u32::from_be_bytes(data[..4].try_into().ok()?) != width
|
||||
|| u32::from_be_bytes(data[4..8].try_into().ok()?) != height
|
||||
|| data[12] != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
b"acTL" | b"eXIf" => return None,
|
||||
b"IDAT" if header => {
|
||||
let row = total_bytes / u64::from(height);
|
||||
return row.checked_add(1).and_then(png_row_scratch_for_row);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
at = end.checked_add(4)?; // CRC
|
||||
}
|
||||
}
|
||||
|
||||
fn png_row_scratch_for_row(out: u64) -> Option<u64> {
|
||||
// A filter byte and the row's samples.
|
||||
let stored = 1u64.checked_add(out)?;
|
||||
let kept = (stored * 4).next_multiple_of(64).max(PNG_KEPT_ROWS);
|
||||
let stream = kept + stored * 2 + PNG_WINDOW_AND_STEP;
|
||||
Some(stream * 3 + stored + out)
|
||||
@@ -313,14 +365,6 @@ fn fitted_dims(w: u32, h: u32, allowance: u64) -> Option<(u32, u32)> {
|
||||
(u64::from(nw) * u64::from(nh) * 4 <= allowance).then_some((nw, nh))
|
||||
}
|
||||
|
||||
/// A PNG reader of `bytes` that gives 8-bit gray, gray with alpha, RGB or RGBA rows, with its
|
||||
/// header and the chunks before the pixels read.
|
||||
fn png_reader(bytes: &[u8]) -> Option<png::Reader<std::io::Cursor<&[u8]>>> {
|
||||
let mut d = png::Decoder::new(std::io::Cursor::new(bytes));
|
||||
d.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
d.read_info().ok()
|
||||
}
|
||||
|
||||
/// `bytes` decoded at the size [`reduction`] gives. Each pixel of the result is the mean of the
|
||||
/// image's pixels it covers. [`Undecoded::Unreadable`] when they can't be read, and
|
||||
/// [`Undecoded::NoRoom`] when the result and what reading takes ([`Reduction::scratch`]) don't fit
|
||||
@@ -335,19 +379,64 @@ fn reduced_pixmap(bytes: &[u8], r: &Reduction) -> Result<vello_cpu::Pixmap, Unde
|
||||
|
||||
/// `bytes` read and shrunk as [`reduced_pixmap`] says.
|
||||
fn shrunk(bytes: &[u8], r: &Reduction) -> Option<vello_cpu::Pixmap> {
|
||||
shrunk_with_png_limits(bytes, r, &png_streaming_limits(allowance()))
|
||||
}
|
||||
|
||||
fn shrunk_with_png_limits(bytes: &[u8], r: &Reduction, png_limits: &craft_image_codecs::Limits) -> Option<vello_cpu::Pixmap> {
|
||||
let mut shrink = Shrink::new(r.size, r.to);
|
||||
if r.rows {
|
||||
let mut reader = png_reader(bytes)?;
|
||||
let (color, _) = reader.output_color_type();
|
||||
while let Some(row) = reader.next_row().ok()? {
|
||||
let data = row.data();
|
||||
match color {
|
||||
png::ColorType::Grayscale => shrink.row(data.iter().map(|&g| [g, g, g, 255])),
|
||||
png::ColorType::GrayscaleAlpha => shrink.row(data.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])),
|
||||
png::ColorType::Rgb => shrink.row(data.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])),
|
||||
png::ColorType::Rgba => shrink.row(data.as_chunks::<4>().0.iter().copied()),
|
||||
png::ColorType::Indexed => return None,
|
||||
}
|
||||
use craft_image_codecs::{ChannelLayout, CodecError, Format, PngDecodeRows, SampleType};
|
||||
let mut dec = PngDecodeRows::new_streaming(bytes, png_limits).ok()?;
|
||||
if !dec.streamable() {
|
||||
return None;
|
||||
}
|
||||
let hdr = dec.header();
|
||||
// Yield after each row and stop once all pixels have arrived. The pinned decoder's
|
||||
// first tail batch only locates a text chunk; later batches inflate/retain its value.
|
||||
// Never run those batches: the renderer needs pixels, not ancillary text. Its underlying
|
||||
// PNG reader also ignores text chunks before IDAT, so neither location retains text.
|
||||
for _ in 0..hdr.height {
|
||||
let _extras = dec
|
||||
.step_stream::<CodecError>(1, &mut || false, &mut |_y, row| {
|
||||
match (hdr.layout, hdr.sample) {
|
||||
(ChannelLayout::Gray, SampleType::U8) => shrink.row(row.iter().map(|&g| [g, g, g, 255])),
|
||||
(ChannelLayout::GrayA, SampleType::U8) => shrink.row(row.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])),
|
||||
(ChannelLayout::Rgb, SampleType::U8) => shrink.row(row.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])),
|
||||
(ChannelLayout::Rgba, SampleType::U8) => shrink.row(row.as_chunks::<4>().0.iter().copied()),
|
||||
(ChannelLayout::Gray, SampleType::U16) => shrink.row(row.as_chunks::<2>().0.iter().map(|&g| {
|
||||
let v = (u16::from_ne_bytes(g) >> 8) as u8;
|
||||
[v, v, v, 255]
|
||||
})),
|
||||
(ChannelLayout::GrayA, SampleType::U16) => shrink.row(row.as_chunks::<4>().0.iter().map(|&[g0, g1, a0, a1]| {
|
||||
let g = (u16::from_ne_bytes([g0, g1]) >> 8) as u8;
|
||||
let a = (u16::from_ne_bytes([a0, a1]) >> 8) as u8;
|
||||
[g, g, g, a]
|
||||
})),
|
||||
(ChannelLayout::Rgb, SampleType::U16) => shrink.row(row.as_chunks::<6>().0.iter().map(|&[r0, r1, g0, g1, b0, b1]| {
|
||||
[
|
||||
(u16::from_ne_bytes([r0, r1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([g0, g1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([b0, b1]) >> 8) as u8,
|
||||
255,
|
||||
]
|
||||
})),
|
||||
(ChannelLayout::Rgba, SampleType::U16) => {
|
||||
shrink.row(row.as_chunks::<8>().0.iter().map(|&[r0, r1, g0, g1, b0, b1, a0, a1]| {
|
||||
[
|
||||
(u16::from_ne_bytes([r0, r1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([g0, g1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([b0, b1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([a0, a1]) >> 8) as u8,
|
||||
]
|
||||
}))
|
||||
}
|
||||
_ => {
|
||||
return Err(CodecError::Unsupported { format: Format::Png, reason: "unsupported PNG channel layout".into() });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.ok()?;
|
||||
}
|
||||
} else {
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
@@ -589,6 +678,58 @@ mod tests {
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_header_accepts_rgba16_above_whole_image_default() {
|
||||
// Header-only fixture: opening the stream checks declared size without allocating or
|
||||
// decoding the 1.2 GB canvas. Padding meets the decoder's compressed-size plausibility
|
||||
// bound; no rows are requested from this deliberately incomplete image.
|
||||
let (w, h) = (10_000u32, 15_000u32);
|
||||
let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
let ihdr = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[16, 6, 0, 0, 0]].concat();
|
||||
let mut idat = b"IDAT\x78\x9c".to_vec();
|
||||
idat.resize(1_200_000, 0);
|
||||
for chunk in [&ihdr[..], &idat, b"IEND"] {
|
||||
bytes.extend((chunk.len() as u32 - 4).to_be_bytes());
|
||||
bytes.extend(chunk);
|
||||
let mut crc = flate2::Crc::new();
|
||||
crc.update(chunk);
|
||||
bytes.extend(crc.sum().to_be_bytes());
|
||||
}
|
||||
let default = craft_image_codecs::Limits { max_alloc: 1 << 30, max_pixels: 150_000_000, ..Default::default() };
|
||||
assert!(craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &default).is_err());
|
||||
let rows = craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &png_streaming_limits(150_000_000)).unwrap();
|
||||
assert_eq!((rows.header().width, rows.header().height), (w, h));
|
||||
assert!(rows.streamable());
|
||||
assert!(craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &png_streaming_limits(149_999_999)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_reduction_does_not_retain_text_after_pixels() {
|
||||
let mut bytes = Vec::new();
|
||||
striped(8).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
let mut chunk = b"tEXtComment\0".to_vec();
|
||||
chunk.extend(std::iter::repeat_n(b'x', 1 << 20));
|
||||
// PNG's IEEE CRC over type and payload, kept local to this fixture.
|
||||
let mut crc = u32::MAX;
|
||||
for &byte in &chunk {
|
||||
crc ^= u32::from(byte);
|
||||
for _ in 0..8 {
|
||||
crc = (crc >> 1) ^ (0xedb88320 & 0u32.wrapping_sub(crc & 1));
|
||||
}
|
||||
}
|
||||
let mut tail = ((chunk.len() - 4) as u32).to_be_bytes().to_vec();
|
||||
tail.extend(chunk);
|
||||
tail.extend((!crc).to_be_bytes());
|
||||
bytes.splice(bytes.len() - 12..bytes.len() - 12, tail);
|
||||
let limits = craft_image_codecs::Limits { max_alloc: 1 << 19, ..Default::default() };
|
||||
let mut full = craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &limits).unwrap();
|
||||
assert!(full.step_stream::<craft_image_codecs::CodecError>(1, &mut || true, &mut |_, _| Ok(())).is_err());
|
||||
// The renderer stops after the pixels instead of retaining ancillary text.
|
||||
let reduced = shrunk_with_png_limits(&bytes, &Reduction { size: (8, 1), to: (4, 1), rows: true, scratch: 0 }, &limits).unwrap();
|
||||
assert_eq!((reduced.width(), reduced.height()), (4, 1));
|
||||
assert!(red_at_its_coverage(&reduced));
|
||||
}
|
||||
|
||||
/// Opaque red beside clear black, every other column of a `w` × 1 image.
|
||||
fn striped(w: u32) -> image::RgbaImage {
|
||||
image::RgbaImage::from_fn(w, 1, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) })
|
||||
|
||||
@@ -1883,14 +1883,14 @@ fn a_png_past_the_allowance_draws_at_reduced_size() {
|
||||
assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (300, 300, [200, 40, 40, 255]));
|
||||
// A row is read only while the reader's buffers fit the allowance, counting the stream buffer
|
||||
// three times for the moment it grows. Below 4,096 columns of 16-bit RGBA they take 516,103
|
||||
// bytes and 60 a column: 1,398 columns take 599,983 bytes, within 600,000, and 1,399 columns
|
||||
// take 600,043 and are not decoded (their samples, 8 bytes a pixel, are past it too).
|
||||
// bytes plus 64 bytes a column: 1,310 columns take 599,943 bytes, within 600,000, and 1,311
|
||||
// columns take 600,007 and are not decoded (their samples, 8 bytes a pixel, are past it too).
|
||||
let wide = |w: u32| {
|
||||
let img = image::ImageBuffer::<image::Rgba<u16>, _>::from_pixel(w, 60, image::Rgba([51400, 10280, 10280, 65535]));
|
||||
encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png)
|
||||
};
|
||||
assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1398))), Some((1398, 60)));
|
||||
assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1399))), None);
|
||||
assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1310))), Some((1310, 60)));
|
||||
assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1311))), None);
|
||||
// An image of more pixels than the allowance has bytes is not read: 1,000 × 400 8-bit gray
|
||||
// pixels are drawn at 500 × 200 within 400,000 bytes, and 1,000 × 401 are not.
|
||||
let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(1000, h, image::Luma([90]))), image::ImageFormat::Png);
|
||||
@@ -1938,13 +1938,13 @@ fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() {
|
||||
// Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result
|
||||
// of 15,768 bytes.
|
||||
let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg);
|
||||
// Read a row at a time: 540,103 bytes in the reader's buffers for 400 columns of 16-bit RGBA,
|
||||
// Read a row at a time: 541,703 bytes in the reader's buffers for 400 columns of 16-bit RGBA,
|
||||
// beside a 387 × 387 result of 599,076 bytes.
|
||||
let png = encoded(
|
||||
image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(400, 400, image::Rgba([51400, 10280, 10280, 65535]))),
|
||||
image::ImageFormat::Png,
|
||||
);
|
||||
for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 540_103, (387, 387))] {
|
||||
for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 541_703, (387, 387))] {
|
||||
let failed = decode_failures();
|
||||
let none = with_allowance(allowance, || with_room(room - 1, || paint::decode_pixmap_or_why(bytes)));
|
||||
assert_eq!(none.err(), Some(paint::Undecoded::NoRoom), "not decoded with a byte too few, and tried again later");
|
||||
|
||||
@@ -37,9 +37,25 @@ pub(super) enum StrokePlan {
|
||||
Written(Written),
|
||||
}
|
||||
|
||||
/// Visit `n` and the descendants the writer draws ([`Writer::node_body`]): a hidden layer or object
|
||||
/// and what it holds only with `hidden` (SVG Options › hidden layers kept), and a template layer's
|
||||
/// art never.
|
||||
fn walk_drawn<'a>(n: &'a Node, hidden: bool, f: &mut impl FnMut(&'a Node)) {
|
||||
if !(n.visible || hidden) {
|
||||
return;
|
||||
}
|
||||
f(n);
|
||||
if matches!(n.kind, NodeKind::Layer { template: true, .. }) {
|
||||
return;
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk_drawn(c, hidden, f);
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
pub(super) fn count_colorized_images(&mut self, art: &Node) {
|
||||
art.walk(&mut |n| {
|
||||
walk_drawn(art, self.opts.hidden_layers, &mut |n| {
|
||||
let NodeKind::Image(im) = &n.kind else { return };
|
||||
let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() else { return };
|
||||
let shown = self.doc.shown_image(n, im);
|
||||
@@ -176,7 +192,7 @@ impl Writer<'_> {
|
||||
self.count_colorized_images(art);
|
||||
// Each image's count and its first piece, which shows what they all show.
|
||||
let mut seen: HashMap<(String, u32, u32), (usize, vectorcraft_doc::ImageObject)> = HashMap::new();
|
||||
art.walk(&mut |c| {
|
||||
walk_drawn(art, self.opts.hidden_layers, &mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
let shown = self.doc.shown_image(c, im);
|
||||
let im = &*shown;
|
||||
|
||||
@@ -875,7 +875,8 @@ fn raster(format: image::ImageFormat) -> Option<RasterKind> {
|
||||
/// TIFF) leaves the pixels as stored. Otherwise the pixels are read ([`decoded`],
|
||||
/// [`tiff_pixels`]), turned or flipped as the orientation says, and written as PNG, so usvg sizes
|
||||
/// and fits the image as it is shown, with the resolution the file declares
|
||||
/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn. A CMYK TIFF also
|
||||
/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn, and the ICC profile
|
||||
/// the file carries when its color space is the written samples' (gray or RGB). A CMYK TIFF also
|
||||
/// keeps its inks as a CMYK TIFF ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG
|
||||
/// or TIFF that is turned keeps them turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when
|
||||
/// the pixels can't be read, and for a TIFF with more strips or tiles than the decoder can count
|
||||
@@ -893,7 +894,7 @@ fn shown(bytes: Arc<Vec<u8>>, format: image::ImageFormat) -> Option<Shown> {
|
||||
return Some(Shown { kind, bytes, cmyk: None });
|
||||
}
|
||||
let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff);
|
||||
let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? };
|
||||
let (mut img, icc) = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? };
|
||||
let ppi = vectorcraft_doc::ppi::resolution(&bytes);
|
||||
// The resolution describes the stored pixels; a quarter turn swaps its axes.
|
||||
let quarter = orientation.is_some_and(|o| o.to_exif() >= 5);
|
||||
@@ -906,18 +907,38 @@ fn shown(bytes: Arc<Vec<u8>>, format: image::ImageFormat) -> Option<Shown> {
|
||||
if let Some(orientation) = orientation {
|
||||
img.apply_orientation(orientation);
|
||||
}
|
||||
use image::DynamicImage as D;
|
||||
let img = match img {
|
||||
D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img,
|
||||
D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img,
|
||||
other => D::ImageRgba8(other.into_rgba8()),
|
||||
};
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?;
|
||||
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
|
||||
if let Some(icc) = icc.filter(|icc| png_takes_icc(&img, icc)) {
|
||||
// A profile the encoder doesn't take leaves the image without one.
|
||||
let _ = image::ImageEncoder::set_icc_profile(&mut encoder, icc);
|
||||
}
|
||||
img.write_with_encoder(encoder).ok()?;
|
||||
if let Some(ppi) = shown_ppi {
|
||||
png = vectorcraft_doc::ppi::with_png_resolution(&png, ppi);
|
||||
}
|
||||
Some(Shown { kind: ImageKind::PNG, bytes: Arc::new(png), cmyk })
|
||||
}
|
||||
|
||||
/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples':
|
||||
/// `GRAY` for gray samples, `RGB ` for RGB ones.
|
||||
fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool {
|
||||
let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" };
|
||||
vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want)
|
||||
}
|
||||
|
||||
/// The pixels of encoded image `bytes` (`format` when their bytes don't say), as stored, decoded
|
||||
/// within [`vectorcraft_doc::MAX_RASTER_ALLOC`], counted as decoded and as RGBA, as Open and Place
|
||||
/// decode them; `None` when they can't be.
|
||||
fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<image::DynamicImage> {
|
||||
/// decode them, with the ICC profile their samples are in when the file carries one the decoder
|
||||
/// can read (a TIFF's read by [`vectorcraft_doc::cmyk::tiff_icc_profile`]); `None` when they
|
||||
/// can't be.
|
||||
fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<(image::DynamicImage, Option<Vec<u8>>)> {
|
||||
use image::ImageDecoder as _;
|
||||
let max = vectorcraft_doc::MAX_RASTER_ALLOC;
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
@@ -927,12 +948,16 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<image::DynamicIma
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(max);
|
||||
reader.limits(limits);
|
||||
let decoder = reader.into_decoder().ok()?;
|
||||
let tiff = reader.format() == Some(image::ImageFormat::Tiff);
|
||||
let mut decoder = reader.into_decoder().ok()?;
|
||||
let (w, h) = decoder.dimensions();
|
||||
if decoder.total_bytes() > max || u64::from(w) * u64::from(h) * 4 > max {
|
||||
return None;
|
||||
}
|
||||
image::DynamicImage::from_decoder(decoder).ok()
|
||||
// The image decoder reads a TIFF's tags within the size of its pixels, so a small TIFF's
|
||||
// profile is read by the TIFF decoder itself.
|
||||
let icc = if tiff { vectorcraft_doc::cmyk::tiff_icc_profile(bytes) } else { decoder.icc_profile().ok().flatten() };
|
||||
Some((image::DynamicImage::from_decoder(decoder).ok()?, icc))
|
||||
}
|
||||
|
||||
/// The pixels of TIFF `bytes`, as stored, read as Open and Place read them: a TIFF with extra
|
||||
@@ -940,15 +965,17 @@ fn decoded(bytes: &[u8], format: image::ImageFormat) -> Option<image::DynamicIma
|
||||
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]); a 1-bit TIFF compressed with CCITT Group
|
||||
/// 3 as RGBA ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]); others by [`decoded`], a CMYK TIFF
|
||||
/// that stores one plane per ink with its inks written together first
|
||||
/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]). `None` when they can't be read.
|
||||
fn tiff_pixels(bytes: &[u8]) -> Option<image::DynamicImage> {
|
||||
/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]). Pixels the image decoder reads come with the
|
||||
/// TIFF's ICC profile; the other readers give sRGB pixels, without one. `None` when they can't be
|
||||
/// read.
|
||||
fn tiff_pixels(bytes: &[u8]) -> Option<(image::DynamicImage, Option<Vec<u8>>)> {
|
||||
use image::DynamicImage::ImageRgba8;
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
if let Some(img) = vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false)) {
|
||||
return Some(ImageRgba8(img));
|
||||
return Some((ImageRgba8(img), None));
|
||||
}
|
||||
if let Some(read) = vectorcraft_doc::cmyk::group3_tiff_rgba(bytes) {
|
||||
return read.ok().map(ImageRgba8);
|
||||
return read.ok().map(|img| (ImageRgba8(img), None));
|
||||
}
|
||||
decoded(bytes, image::ImageFormat::Tiff).or_else(|| decoded(&vectorcraft_doc::cmyk::stored_cmyk_tiff(bytes, None)?, image::ImageFormat::Tiff))
|
||||
}
|
||||
|
||||
@@ -243,48 +243,59 @@ impl Importer {
|
||||
if !matches!(kids.get(main), Some(usvg::Node::Path(p)) if p.is_visible()) {
|
||||
return Some(vec![]);
|
||||
}
|
||||
let text::PendingText { name, mut obj, servers, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone();
|
||||
// The scale the type draws at becomes its size (last, below): text space grows by `grow`.
|
||||
let xf = ts * obj.xf;
|
||||
let grow = text::size_scale(&obj, xf);
|
||||
// usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user
|
||||
// space; runs paint in text space.
|
||||
let to_text = Affine::scale(grow) * obj.xf.inverse();
|
||||
let text::PendingText { name, obj, servers, rest, paints, non_scaling, under, .. } = self.slots.texts.get(i)?.clone();
|
||||
let slot_paint = |im: &mut Self, k: usize, m: Affine| match kids.get(main + 1 + k) {
|
||||
Some(usvg::Node::Path(p)) => p.fill().map_or(Paint::None, |f| im.paint(f.paint(), m)),
|
||||
_ => Paint::None,
|
||||
};
|
||||
let resolved: Vec<Paint> = (0..paints).map(|k| slot_paint(self, k, to_text)).collect();
|
||||
let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None);
|
||||
for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) {
|
||||
if let Some(k) = fill {
|
||||
run.style.fill = server(k);
|
||||
// A text split into several objects becomes a group of them, named after the element.
|
||||
let whole = rest.is_empty();
|
||||
let mut skewed = false;
|
||||
let mut nodes = Vec::with_capacity(rest.len() + 1);
|
||||
for (mut obj, servers) in std::iter::once((obj, servers)).chain(rest) {
|
||||
// The scale the type draws at becomes its size (last, below): text space grows by `grow`.
|
||||
let xf = ts * obj.xf;
|
||||
let grow = text::size_scale(&obj, xf);
|
||||
// usvg resolved the `url(#…)` paints (the paths after the main one) in the element's user
|
||||
// space; runs paint in text space.
|
||||
let to_text = Affine::scale(grow) * obj.xf.inverse();
|
||||
let resolved: Vec<Paint> = (0..paints).map(|k| slot_paint(self, k, to_text)).collect();
|
||||
let server = |k: usize| resolved.get(k).cloned().unwrap_or(Paint::None);
|
||||
for (run, (fill, stroke)) in obj.runs.iter_mut().zip(servers) {
|
||||
if let Some(k) = fill {
|
||||
run.style.fill = server(k);
|
||||
}
|
||||
if let Some(k) = stroke {
|
||||
run.style.stroke = server(k);
|
||||
}
|
||||
}
|
||||
if let Some(k) = stroke {
|
||||
run.style.stroke = server(k);
|
||||
obj.xf = xf;
|
||||
skewed |= non_scaling && !vector_effect::unscale_text(&mut obj, self.screen);
|
||||
// A stroke under the characters is the object's own: it paints in the document.
|
||||
let under = under.clone().map(|(mut sl, k)| {
|
||||
if let Some(k) = k {
|
||||
sl.paint = slot_paint(self, k, ts);
|
||||
}
|
||||
let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() };
|
||||
ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() });
|
||||
ap.set_contents_at(1);
|
||||
ap
|
||||
});
|
||||
text::fold_scale(&mut obj, grow);
|
||||
let mut n = self.named(if whole { &name } else { "" }, NodeKind::Text(Box::new(obj)))?;
|
||||
if let Some(ap) = under {
|
||||
n.appearance = ap.into();
|
||||
}
|
||||
nodes.push(Arc::new(n));
|
||||
}
|
||||
obj.xf = xf;
|
||||
if non_scaling && !vector_effect::unscale_text(&mut obj, self.screen) {
|
||||
if skewed {
|
||||
let label = if name.is_empty() || made_up(&name) { "a text".to_string() } else { format!("text '{name}'") };
|
||||
self.warn(format!("non-scaling stroke on {label} approximated: the text is stretched or skewed"));
|
||||
}
|
||||
// A stroke under the characters is the object's own: it paints in the document.
|
||||
let under = under.map(|(mut sl, k)| {
|
||||
if let Some(k) = k {
|
||||
sl.paint = slot_paint(self, k, ts);
|
||||
}
|
||||
let mut ap = Appearance { items: vec![AppearanceItem::Stroke(sl)], ..Default::default() };
|
||||
ap.scale_strokes(if non_scaling { self.screen } else { obj.xf.determinant().abs().sqrt() });
|
||||
ap.set_contents_at(1);
|
||||
ap
|
||||
});
|
||||
text::fold_scale(&mut obj, grow);
|
||||
let mut n = self.named(&name, NodeKind::Text(Box::new(obj)))?;
|
||||
if let Some(ap) = under {
|
||||
n.appearance = ap.into();
|
||||
if whole {
|
||||
return Some(nodes);
|
||||
}
|
||||
Some(vec![Arc::new(n)])
|
||||
Some(vec![Arc::new(self.named(&name, NodeKind::Group { children: nodes, clip: false })?)])
|
||||
}
|
||||
|
||||
fn group_node(&mut self, g: &usvg::Group, acc: Affine) -> Option<Node> {
|
||||
@@ -584,7 +595,8 @@ impl Importer {
|
||||
if p.id().is_empty() || !p.is_visible() || p.fill().is_some_and(|f| f.rule() == usvg::FillRule::EvenOdd) {
|
||||
return None;
|
||||
}
|
||||
let mut obj = self.slots.texts.get(self.slots.find(p)?)?.obj.clone();
|
||||
// A text split into several objects clips by its outlines.
|
||||
let mut obj = self.slots.texts.get(self.slots.find(p)?).filter(|t| t.rest.is_empty())?.obj.clone();
|
||||
obj.xf = m * self.slots.inner(p) * obj.xf;
|
||||
let grow = text::size_scale(&obj, obj.xf);
|
||||
for run in &mut obj.runs {
|
||||
|
||||
+192
-48
@@ -130,6 +130,7 @@ const BIDI_NESTED: &str = "a unicode-bidi embedding inside another imported one
|
||||
const BIDI_TEXT_OVERRIDE: &str = "unicode-bidi override on the text imported as its paragraph direction; directional override is not supported";
|
||||
|
||||
/// One character of a text and the adjustments its position needs.
|
||||
#[derive(Clone)]
|
||||
struct Cell {
|
||||
ch: char,
|
||||
style: CharStyle,
|
||||
@@ -178,6 +179,9 @@ pub(super) struct PendingText {
|
||||
pub obj: TextObject,
|
||||
/// For each run, the index of its fill's and stroke's `url(#…)` paint, if any.
|
||||
pub servers: Vec<(Option<usize>, Option<usize>)>,
|
||||
/// The other point type objects of a text whose absolutely placed characters one object cannot
|
||||
/// put on their x ([`split`]), after `obj` in text order, each with its runs' paint indices.
|
||||
pub rest: Vec<(TextObject, Vec<Key>)>,
|
||||
/// Number of `url(#…)` paints (the placeholder paths after the main one, in order).
|
||||
pub paints: usize,
|
||||
/// `vector-effect="non-scaling-stroke"`: the character strokes keep their width on screen.
|
||||
@@ -233,7 +237,14 @@ impl TextSlots {
|
||||
return Some(bp.clone());
|
||||
}
|
||||
let t = self.texts.get(i)?;
|
||||
let bp = Rc::new(vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath());
|
||||
let mut bp = vectorcraft_text::layout(FontDb::global(), &t.obj).to_bezpath();
|
||||
// The other objects of a split text, in the first one's text space.
|
||||
for (o, _) in &t.rest {
|
||||
let mut more = vectorcraft_text::layout(FontDb::global(), o).to_bezpath();
|
||||
more.apply_affine(t.obj.xf.inverse() * o.xf);
|
||||
bp.extend(more.elements().iter().copied());
|
||||
}
|
||||
let bp = Rc::new(bp);
|
||||
self.outlines.borrow_mut().insert(i, bp.clone());
|
||||
Some(bp)
|
||||
}
|
||||
@@ -534,7 +545,10 @@ fn use_slot(
|
||||
shown.build(style_xml, style_t, &label, &mut found)
|
||||
};
|
||||
let differs = |(text, paints): &(PendingText, Vec<String>)| {
|
||||
slots.texts.get(shared).is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.under != text.under)
|
||||
slots
|
||||
.texts
|
||||
.get(shared)
|
||||
.is_none_or(|old| old.obj != text.obj || old.servers != text.servers || old.rest != text.rest || old.under != text.under)
|
||||
|| inst.paints.get(shared) != Some(paints)
|
||||
};
|
||||
let slot = built.filter(differs).map(|(text, paints)| {
|
||||
@@ -1337,7 +1351,7 @@ impl Ctx {
|
||||
}
|
||||
let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0));
|
||||
let name = t.attribute("id").unwrap_or("").to_string();
|
||||
Some((PendingText { name, obj, servers, paints: 0, non_scaling: false, under: None, marker }, Vec::new()))
|
||||
Some((PendingText { name, obj, servers, rest: vec![], paints: 0, non_scaling: false, under: None, marker }, Vec::new()))
|
||||
}
|
||||
|
||||
/// Read one `<text>`: the pending text and its `url(#…)` paints.
|
||||
@@ -1469,6 +1483,7 @@ impl Ctx {
|
||||
let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default());
|
||||
let mut breaks: Vec<Break> = vec![];
|
||||
let mut para_styles: Vec<ParaStyle> = vec![];
|
||||
let mut rest = vec![];
|
||||
if let Some((tp, followed)) = path {
|
||||
let bp = &followed.path;
|
||||
// Along the path: dx is extra advance, dy shifts off the path.
|
||||
@@ -1549,46 +1564,37 @@ impl Ctx {
|
||||
obj.kind = TextKind::OnPath { path: PathData::from_bezpath(&bp), start: 0.0, end: None };
|
||||
obj.xf = Affine::IDENTITY;
|
||||
} else {
|
||||
let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]);
|
||||
let (justify, left, starts, unplaced) = lines(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, origin.x, &mut breaks);
|
||||
if unplaced > 0 {
|
||||
let whole = cells.clone();
|
||||
let mut ys = vec![];
|
||||
let (b, p, unplaced) = place(&mut cells, &x, &y, &dx, &dy, &anchor_of, &pin, &mut obj, &mut ys);
|
||||
(breaks, para_styles) = (b, p);
|
||||
if !unplaced.is_empty() {
|
||||
// One object cannot put every absolutely placed character on its x: the text becomes
|
||||
// several, the first of them `obj`.
|
||||
let mut pieces = split(&whole, &x, &y, &dx, &dy, &ys, &anchor_of, &pin, unplaced).into_iter();
|
||||
if let Some(first) = pieces.next() {
|
||||
(obj, cells, breaks, para_styles) = (first.obj, first.cells, first.breaks, first.paras);
|
||||
}
|
||||
rest = pieces
|
||||
.map(|mut p| {
|
||||
let servers = finish(&mut p.obj, &p.cells, &p.breaks, p.paras, &pin);
|
||||
(p.obj, servers)
|
||||
})
|
||||
.collect();
|
||||
warnings.push(format!(
|
||||
"{label}: {unplaced} absolutely placed character(s) between characters of the other direction keep their place in the line"
|
||||
"{label}: imported as {} point type objects in a group, since one object cannot put every character on its own x",
|
||||
rest.len() + 1
|
||||
));
|
||||
}
|
||||
obj.para.justify = justify;
|
||||
obj.xf = Affine::translate((finite(left), finite(origin.y)));
|
||||
// Lines anchored differently or at different x (paragraphs aligned or indented
|
||||
// differently): each line's paragraph takes its alignment, and indents that put it
|
||||
// where it was.
|
||||
if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) {
|
||||
for (k, &(_, a, ax)) in starts.iter().enumerate() {
|
||||
let d = finite(ax - left);
|
||||
let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() };
|
||||
match pa.justify {
|
||||
Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d,
|
||||
Justify::Center => pa.right_indent = -2.0 * d,
|
||||
Justify::Right => pa.right_indent = -d,
|
||||
_ => pa.left_indent = d,
|
||||
}
|
||||
let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) };
|
||||
para_styles.extend(std::iter::repeat_n(pa, count));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (runs, servers) = assemble(&cells, &breaks).0;
|
||||
obj.runs = runs;
|
||||
if !para_styles.is_empty() {
|
||||
obj.set_paragraph_styles(para_styles);
|
||||
}
|
||||
pin(&mut obj);
|
||||
keep_reader_anchors(&mut obj);
|
||||
let servers = finish(&mut obj, &cells, &breaks, para_styles, &pin);
|
||||
// The placeholder covers the text (laid out when a paint server needs its bounding box).
|
||||
let b = if paints.is_empty() { obj.bounds() } else { Some(obj.xf.transform_rect_bbox(measure(&obj).bounds)) }.unwrap_or_default();
|
||||
let bounds = |o: &TextObject| if paints.is_empty() { o.bounds() } else { Some(o.xf.transform_rect_bbox(measure(o).bounds)) };
|
||||
let b = rest.iter().filter_map(|(o, _)| bounds(o)).fold(bounds(&obj), |all, b| Some(all.map_or(b, |a| a.union(b)))).unwrap_or_default();
|
||||
let marker = Rect::new(b.x0, b.y0, b.x1.max(b.x0 + 1.0), b.y1.max(b.y0 + 1.0));
|
||||
let name = t.attribute("id").unwrap_or("").to_string();
|
||||
let non_scaling = vector_effect::is_non_scaling(&self.css, t);
|
||||
Some((PendingText { name, obj, servers, paints: paints.len(), non_scaling, under, marker }, paints))
|
||||
Some((PendingText { name, obj, servers, rest, paints: paints.len(), non_scaling, under, marker }, paints))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1683,13 +1689,145 @@ fn leading_tolerance(spacing: f64) -> f64 {
|
||||
0.01_f64.min(spacing.abs() * 1e-3)
|
||||
}
|
||||
|
||||
/// Point type `obj` of `cells` placed by the positioning lists ([`lines`]): sets its justification
|
||||
/// and transform, and returns its line breaks, its paragraph styles and the absolutely placed
|
||||
/// characters kerning cannot put on their x. `ys` takes each character's line baseline and y.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn place(
|
||||
cells: &mut [Cell],
|
||||
x: &[Option<f64>],
|
||||
y: &[Option<f64>],
|
||||
dx: &[f64],
|
||||
dy: &[f64],
|
||||
anchor_of: &dyn Fn(usize) -> f64,
|
||||
pin: &dyn Fn(&mut TextObject),
|
||||
obj: &mut TextObject,
|
||||
ys: &mut Vec<(f64, f64)>,
|
||||
) -> (Vec<Break>, Vec<ParaStyle>, Vec<usize>) {
|
||||
let mut breaks = vec![];
|
||||
let mut para_styles = vec![];
|
||||
let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]);
|
||||
let (justify, left, starts, unplaced) = lines(cells, x, y, dx, dy, anchor_of, pin, origin.x, &mut breaks, ys);
|
||||
obj.para.justify = justify;
|
||||
obj.xf = Affine::translate((finite(left), finite(origin.y)));
|
||||
// Lines anchored differently or at different x (paragraphs aligned or indented
|
||||
// differently): each line's paragraph takes its alignment, and indents that put it
|
||||
// where it was.
|
||||
if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) {
|
||||
for (k, &(_, a, ax)) in starts.iter().enumerate() {
|
||||
let d = finite(ax - left);
|
||||
let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() };
|
||||
match pa.justify {
|
||||
Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d,
|
||||
Justify::Center => pa.right_indent = -2.0 * d,
|
||||
Justify::Right => pa.right_indent = -d,
|
||||
_ => pa.left_indent = d,
|
||||
}
|
||||
let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) };
|
||||
para_styles.extend(std::iter::repeat_n(pa, count));
|
||||
}
|
||||
}
|
||||
(breaks, para_styles, unplaced)
|
||||
}
|
||||
|
||||
/// Gives `obj` the runs of `cells` with `breaks`, its paragraph styles and its paragraph
|
||||
/// directions; returns the paint indices of its runs.
|
||||
fn finish(obj: &mut TextObject, cells: &[Cell], breaks: &[Break], para_styles: Vec<ParaStyle>, pin: &dyn Fn(&mut TextObject)) -> Vec<Key> {
|
||||
let (runs, servers) = assemble(cells, breaks).0;
|
||||
obj.runs = runs;
|
||||
if !para_styles.is_empty() {
|
||||
obj.set_paragraph_styles(para_styles);
|
||||
}
|
||||
pin(obj);
|
||||
keep_reader_anchors(obj);
|
||||
servers
|
||||
}
|
||||
|
||||
/// One point type object of a text [`split`] into several, before [`finish`].
|
||||
struct Piece {
|
||||
obj: TextObject,
|
||||
cells: Vec<Cell>,
|
||||
breaks: Vec<Break>,
|
||||
paras: Vec<ParaStyle>,
|
||||
}
|
||||
|
||||
/// How many times [`split`] cuts a piece before the characters kerning cannot place; a piece that
|
||||
/// still has such characters is then cut before each of its chunks.
|
||||
const MAX_SPLITS: usize = 3;
|
||||
|
||||
/// Point type objects, in text order, that together put every absolutely placed character of
|
||||
/// `cells` (before [`place`] kerned them) on its x. SVG anchors each chunk on its own and reorders
|
||||
/// right-to-left characters only within a chunk (SVG 2 › Text, https://www.w3.org/TR/SVG2/text.html),
|
||||
/// while one object reorders the whole
|
||||
/// line: a left-to-right character drawn right before a right-to-left one has no kerning between
|
||||
/// them. The text is cut before each character `unplaced` lists, and each piece placed again. `ys`
|
||||
/// holds each character's line baseline and y, so that a piece keeps its characters' baselines.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn split(
|
||||
cells: &[Cell],
|
||||
x: &[Option<f64>],
|
||||
y: &[Option<f64>],
|
||||
dx: &[f64],
|
||||
dy: &[f64],
|
||||
ys: &[(f64, f64)],
|
||||
anchor_of: &dyn Fn(usize) -> f64,
|
||||
pin: &dyn Fn(&mut TextObject),
|
||||
unplaced: Vec<usize>,
|
||||
) -> Vec<Piece> {
|
||||
let piece = |r: Range<usize>| {
|
||||
let s = r.start;
|
||||
let mut cells = cells[r.clone()].to_vec();
|
||||
let (base, cur) = ys.get(s).copied().unwrap_or((0.0, 0.0));
|
||||
// The piece starts on its line's baseline, and its first character keeps its own y.
|
||||
cells[0].style.baseline_shift += base - cur;
|
||||
let py: Vec<Option<f64>> = r
|
||||
.clone()
|
||||
.map(|i| match i - s {
|
||||
0 => Some(base),
|
||||
1 => y[i].or(Some(cur)),
|
||||
_ => y[i],
|
||||
})
|
||||
.collect();
|
||||
let mut pdy = dy[r.clone()].to_vec();
|
||||
pdy[0] = 0.0;
|
||||
let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default());
|
||||
let (breaks, paras, unplaced) = place(&mut cells, &x[r.clone()], &py, &dx[r], &pdy, &|j| anchor_of(s + j), pin, &mut obj, &mut vec![]);
|
||||
(Piece { obj, cells, breaks, paras }, unplaced.into_iter().map(|j| s + j).collect::<Vec<_>>())
|
||||
};
|
||||
let mut done = vec![];
|
||||
let mut todo = vec![(0..cells.len(), unplaced, 0)];
|
||||
while let Some((range, failed, round)) = todo.pop() {
|
||||
// Past the last round every chunk of the piece is a piece of its own, and so has no
|
||||
// characters to place.
|
||||
let mut cuts: Vec<usize> = if round < MAX_SPLITS { failed } else { (range.start + 1..range.end).filter(|&i| x[i].is_some()).collect() };
|
||||
cuts.sort_unstable();
|
||||
cuts.dedup();
|
||||
let mut from = range.start;
|
||||
for to in cuts.into_iter().chain([range.end]) {
|
||||
if to <= from || to > range.end {
|
||||
continue;
|
||||
}
|
||||
match piece(from..to) {
|
||||
(p, failed) if failed.is_empty() => done.push((from, p)),
|
||||
(_, failed) => todo.push((from..to, failed, round + 1)),
|
||||
}
|
||||
from = to;
|
||||
}
|
||||
}
|
||||
done.sort_by_key(|p| p.0);
|
||||
done.into_iter().map(|p| p.1).collect()
|
||||
}
|
||||
|
||||
/// A line's first character, alignment (as for [`justify_of`]) and anchor x.
|
||||
type LineStart = (usize, f64, f64);
|
||||
|
||||
/// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the
|
||||
/// justification, the x of the first line's left (or anchor) edge and each line's first
|
||||
/// character, alignment (as for [`justify_of`]) and anchor x. `anchor_of` gives where the chunk
|
||||
/// starting at a character sits on its anchor, and `pin` sets the paragraph directions of the
|
||||
/// text ([`pin_direction`]). When characters are placed on their own, every line is left-aligned
|
||||
/// and its anchor x is its left edge. Also returns how many absolutely placed characters kerning
|
||||
/// cannot put on their x.
|
||||
/// and its anchor x is its left edge. Also returns the absolutely placed characters kerning cannot
|
||||
/// put on their x. `ys` takes each character's line baseline and y.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn lines(
|
||||
cells: &mut [Cell],
|
||||
@@ -1701,10 +1839,13 @@ fn lines(
|
||||
pin: &dyn Fn(&mut TextObject),
|
||||
x0: f64,
|
||||
breaks: &mut Vec<Break>,
|
||||
) -> (Justify, f64, Vec<(usize, f64, f64)>, usize) {
|
||||
ys: &mut Vec<(f64, f64)>,
|
||||
) -> (Justify, f64, Vec<LineStart>, Vec<usize>) {
|
||||
let n = cells.len();
|
||||
let y0 = y[0].unwrap_or(0.0) + dy[0];
|
||||
let (mut base, mut cur) = (y0, y0);
|
||||
ys.clear();
|
||||
ys.push((y0, y0));
|
||||
// Line starts (first character, anchor x) and absolutely placed characters (index, x).
|
||||
let mut lines = vec![(0, x0)];
|
||||
let mut targets: Vec<(usize, f64)> = vec![];
|
||||
@@ -1723,9 +1864,11 @@ fn lines(
|
||||
breaks.push(Break { at: i, count: count as usize, leading: gap / count });
|
||||
lines.push((i, ax + dx[i]));
|
||||
(base, cur) = (ny, ny);
|
||||
ys.push((base, cur));
|
||||
continue;
|
||||
}
|
||||
cur = ny;
|
||||
ys.push((base, cur));
|
||||
match x[i] {
|
||||
Some(ax) => targets.push((i, ax + dx[i])),
|
||||
None => cells[i - 1].kern += dx[i],
|
||||
@@ -1744,7 +1887,7 @@ fn lines(
|
||||
}
|
||||
if targets.is_empty() {
|
||||
let starts = lines.iter().map(|&(s, lx)| (s, anchor_of(s), lx)).collect();
|
||||
return (justify_of(anchor_of(0)), x0, starts, 0);
|
||||
return (justify_of(anchor_of(0)), x0, starts, vec![]);
|
||||
}
|
||||
// Absolutely placed characters: lay the text out left-aligned and kern each one onto its x.
|
||||
// SVG anchors every absolutely placed chunk on its own, so a chunk not anchored at its left
|
||||
@@ -1774,7 +1917,7 @@ fn lines(
|
||||
let mut wants: Vec<(usize, f64)> = vec![];
|
||||
// Absolutely placed characters drawn right next to a placed neighbor with no kerning between
|
||||
// them (a left-to-right character between right-to-left ones): they stay where the layout puts them.
|
||||
let mut unplaced = 0;
|
||||
let mut unplaced = vec![];
|
||||
// Kerning changes shaping (pair kerning is off for manually kerned characters): repeat until
|
||||
// every character sits on its x.
|
||||
for round in 0..4 {
|
||||
@@ -1811,7 +1954,7 @@ fn lines(
|
||||
// character's horizontal scale, so each correction is divided by it.
|
||||
let mut worst = 0.0f64;
|
||||
let mut from = 0;
|
||||
unplaced = 0;
|
||||
unplaced.clear();
|
||||
while from < wants.len() {
|
||||
let l = line_of(wants[from].0);
|
||||
let to = from + wants[from..].partition_point(|&(i, _)| line_of(i) == l);
|
||||
@@ -1831,35 +1974,35 @@ fn lines(
|
||||
.filter_map(|&(i, _)| (lines[l].0..i).rev().find_map(|j| pens[j]).map(|k| (2 * k.rank + if k.rtl { 1 } else { 3 }, i - 1)))
|
||||
.collect();
|
||||
cuts.sort_unstable();
|
||||
let mut points: Vec<(usize, f64, f64)> =
|
||||
on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want))).collect();
|
||||
let mut points: Vec<(usize, f64, f64, usize)> =
|
||||
on_line.iter().filter_map(|&(i, want)| pens[i].map(|p| (2 * p.rank + 2, p.start, want, i))).collect();
|
||||
points.sort_by_key(|p| p.0);
|
||||
// The character kerned at the first cut between places `a` and `b`.
|
||||
let cut = |a: usize, b: usize| cuts.get(cuts.partition_point(|c| c.0 <= a)).filter(|c| c.0 < b).map(|c| c.1);
|
||||
let split = points.partition_point(|p| p.0 < home);
|
||||
// Drawn right of the line's first chunk: kerning moves the character away from it.
|
||||
let (mut prev, mut moved) = (home, 0.0);
|
||||
for &(place, start, want) in &points[split..] {
|
||||
for &(place, start, want, i) in &points[split..] {
|
||||
if let Some(k) = cut(prev, place) {
|
||||
let d = want - (start - p0 + moved);
|
||||
cells[k].kern += d / spacing_scale(&cells[k].style, false);
|
||||
moved += d;
|
||||
worst = worst.max(d.abs());
|
||||
} else {
|
||||
unplaced += 1;
|
||||
unplaced.push(i);
|
||||
}
|
||||
prev = place;
|
||||
}
|
||||
// Drawn left of it: kerning moves the chunk (and what lies between) away from the character.
|
||||
(prev, moved) = (home, 0.0);
|
||||
for &(place, start, want) in points[..split].iter().rev() {
|
||||
for &(place, start, want, i) in points[..split].iter().rev() {
|
||||
if let Some(k) = cut(place, prev) {
|
||||
let d = start - p0 - moved - want;
|
||||
cells[k].kern += d / spacing_scale(&cells[k].style, false);
|
||||
moved += d;
|
||||
worst = worst.max(d.abs());
|
||||
} else {
|
||||
unplaced += 1;
|
||||
unplaced.push(i);
|
||||
}
|
||||
prev = place;
|
||||
}
|
||||
@@ -2064,7 +2207,8 @@ fn pens(lay: &TextLayout, bytes: &[usize], cells: &[Cell]) -> Vec<Option<Pen>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
type Key = (Option<usize>, Option<usize>);
|
||||
/// The indices of a run's fill and stroke `url(#…)` paints.
|
||||
pub(super) type Key = (Option<usize>, Option<usize>);
|
||||
type Runs = (Vec<TextRun>, Vec<Key>);
|
||||
|
||||
/// Runs (and their paint indices) from the characters, with `breaks` inserted; also the byte offset
|
||||
|
||||
@@ -125,6 +125,20 @@ fn a_text_clip_path_with_a_clip_rule_or_a_clip_of_its_own_clips_by_its_outlines(
|
||||
assert_eq!(shapes[0].1, vectorcraft_geom::FillRule::EvenOdd);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_imported_as_several_objects_clips_by_all_their_outlines() {
|
||||
// One object cannot put ג on its x, so the text is several objects; the clip outlines all of them.
|
||||
let d = open(
|
||||
r##"<clipPath id="c"><text x="100 160 220" y="80" direction="rtl" font-size="20">אbג</text></clipPath>
|
||||
<rect width="400" height="300" clip-path="url(#c)"/>"##,
|
||||
);
|
||||
let (clip, _) = clip_group(&top(&d)[0]);
|
||||
assert!(!matches!(clip.kind, NodeKind::Text(_)), "{:?}", clip.kind);
|
||||
let b = clip_bounds(clip);
|
||||
// ג ends at 220, the first object at 160.
|
||||
assert!(b.x1 > 200.0 && b.x1 <= 220.0 + 1e-6 && b.x0 < 100.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tspans_and_type_on_a_path_clip_too() {
|
||||
let d = open(
|
||||
|
||||
@@ -362,6 +362,133 @@ fn a_cmyk_tiff_keeps_its_resolution_turned_or_not() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color
|
||||
/// space `space`; the bytes after the header differ from place to place.
|
||||
fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> {
|
||||
let mut icc: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
|
||||
icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes());
|
||||
icc[12..16].copy_from_slice(b"mntr");
|
||||
icc[16..20].copy_from_slice(space);
|
||||
icc[36..40].copy_from_slice(b"acsp");
|
||||
icc
|
||||
}
|
||||
|
||||
/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first
|
||||
/// directory copied to the end of the file with the tag added in order.
|
||||
fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec<u8> {
|
||||
let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap();
|
||||
let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]]));
|
||||
let mut entries: Vec<Vec<u8>> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect();
|
||||
let mut out = tiff.to_vec();
|
||||
if out.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
let data = u32::try_from(out.len()).unwrap();
|
||||
out.extend(icc);
|
||||
if out.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n);
|
||||
let count = u32::try_from(icc.len()).unwrap();
|
||||
entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat());
|
||||
let ifd = u32::try_from(out.len()).unwrap();
|
||||
out[4..8].copy_from_slice(&ifd.to_le_bytes());
|
||||
out.extend(u16::try_from(n + 1).unwrap().to_le_bytes());
|
||||
out.extend(entries.concat());
|
||||
out.extend([0; 4]);
|
||||
out
|
||||
}
|
||||
|
||||
/// A little-endian EXIF block (a TIFF header and one directory) giving Orientation `orientation`.
|
||||
fn exif_block(orientation: u16) -> Vec<u8> {
|
||||
let o = orientation.to_le_bytes();
|
||||
[b"II".as_slice(), &[0x2a, 0, 8, 0, 0, 0], &[1, 0], &[0x12, 0x01, 3, 0, 1, 0, 0, 0, o[0], o[1], 0, 0], &[0, 0, 0, 0]].concat()
|
||||
}
|
||||
|
||||
/// The ICC profile and the bits per sample of the PNG `im` is stored as.
|
||||
fn stored_icc(d: &Document, im: &ImageObject) -> (Option<Vec<u8>>, u16) {
|
||||
use image::ImageDecoder as _;
|
||||
let blob = &d.images[&im.key];
|
||||
assert_eq!(blob.mime, "image/png");
|
||||
let mut dec = image::codecs::png::PngDecoder::new(std::io::Cursor::new(blob.bytes.as_slice())).unwrap();
|
||||
let color = dec.original_color_type();
|
||||
(dec.icc_profile().unwrap(), color.bits_per_pixel() / u16::from(color.channel_count()))
|
||||
}
|
||||
|
||||
/// A raster that import writes again as PNG keeps the gray or RGB ICC profile its file carries,
|
||||
/// byte for byte, linked and as a data URL: a TIFF, turned or not, and a turned PNG and JPEG, with
|
||||
/// 16-bit samples kept at 16 bits and the resolution kept beside the profile. A profile of another
|
||||
/// color space than the written samples', one too short to be a profile, and one on a TIFF whose
|
||||
/// pixels are read as RGBA by its own reader are left out, and the image still imports.
|
||||
#[test]
|
||||
fn a_raster_written_again_as_png_keeps_its_icc_profile() {
|
||||
use image::{DynamicImage, ImageEncoder as _};
|
||||
let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400));
|
||||
let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13])));
|
||||
let gray8 = DynamicImage::ImageLuma8(image::GrayImage::from_fn(3, 2, |x, y| image::Luma([u8::try_from(x * 80 + y * 7).unwrap()])));
|
||||
let rgb16 = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(3, 2, |x, y| {
|
||||
let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap();
|
||||
image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v])
|
||||
}));
|
||||
let tiff_of = |img: &DynamicImage, icc: &[u8]| {
|
||||
let mut out = Vec::new();
|
||||
let mut enc = image::codecs::tiff::TiffEncoder::new(std::io::Cursor::new(&mut out));
|
||||
enc.set_icc_profile(icc.to_vec()).unwrap();
|
||||
img.write_with_encoder(enc).unwrap();
|
||||
out
|
||||
};
|
||||
let png = {
|
||||
let mut out = Vec::new();
|
||||
let mut enc = image::codecs::png::PngEncoder::new(&mut out);
|
||||
enc.set_icc_profile(rgb_icc.clone()).unwrap();
|
||||
enc.set_exif_metadata(exif_block(6)).unwrap();
|
||||
rgb16.write_with_encoder(enc).unwrap();
|
||||
out
|
||||
};
|
||||
let jpg = {
|
||||
let mut out = Vec::new();
|
||||
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95);
|
||||
enc.set_icc_profile(rgb_icc.clone()).unwrap();
|
||||
rgb8.write_with_encoder(enc).unwrap();
|
||||
let exif = [b"Exif\0\0".as_slice(), &exif_block(6)].concat();
|
||||
let mut turned = out[..2].to_vec();
|
||||
turned.extend([0xff, 0xe1]);
|
||||
turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
|
||||
turned.extend(&exif);
|
||||
turned.extend(&out[2..]);
|
||||
turned
|
||||
};
|
||||
let gray = [0, 0, 255, 255, 0, 0, 255, 255];
|
||||
let turned_gray = tiff_with_icc(&tiff_at(4, 2, 1, &gray, 6, Some((300, 150))), &gray_icc);
|
||||
let gray_alpha = [0, 255, 0, 255, 255, 255, 255, 255, 0, 255, 0, 255, 255, 255, 255, 255];
|
||||
// (what, file, the ICC profile to keep, bits per sample, resolution)
|
||||
type Case<'a> = (&'a str, Vec<u8>, Option<&'a [u8]>, u16, Option<(f64, f64)>);
|
||||
let cases: Vec<Case> = vec![
|
||||
("RGB TIFF", tiff_of(&rgb8, &rgb_icc), Some(&rgb_icc), 8, None),
|
||||
("gray TIFF", tiff_of(&gray8, &gray_icc), Some(&gray_icc), 8, None),
|
||||
("16-bit RGB TIFF", tiff_of(&rgb16, &rgb_icc), Some(&rgb_icc), 16, None),
|
||||
("gray TIFF, orientation 6, with a resolution", turned_gray, Some(&gray_icc), 8, Some((150.0, 300.0))),
|
||||
("16-bit RGB PNG, orientation 6", png, Some(&rgb_icc), 16, None),
|
||||
("JPEG, orientation 6", jpg, Some(&rgb_icc), 8, None),
|
||||
("RGB TIFF with a gray profile", tiff_of(&rgb8, &gray_icc), None, 8, None),
|
||||
("gray TIFF with an RGB profile", tiff_of(&gray8, &rgb_icc), None, 8, None),
|
||||
("RGB TIFF with a CMYK profile", tiff_of(&rgb8, &cmyk_icc), None, 8, None),
|
||||
("RGB TIFF with a profile too short to be one", tiff_of(&rgb8, &rgb_icc[..40]), None, 8, None),
|
||||
("gray TIFF with alpha, read as RGBA", tiff_with_icc(&tiff(4, 2, 2, &gray_alpha, 1), &rgb_icc), None, 8, None),
|
||||
];
|
||||
let dir = folder("icc");
|
||||
for (what, file, icc, bits, ppi) in cases {
|
||||
std::fs::write(dir.join("photo.img"), &file).unwrap();
|
||||
let data = format!("data:;base64,{}", base64_encode(&file));
|
||||
for href in ["photo.img", data.as_str()] {
|
||||
let what = format!("{what}, {}", &href[..href.len().min(12)]);
|
||||
let (d, im) = import_one(&format!(r#"<image href="{href}" width="20" height="40"/>"#), Some(&dir));
|
||||
assert_eq!(stored_icc(&d, &im), (icc.map(<[u8]>::to_vec), bits), "{what}");
|
||||
assert_eq!(stored_ppi(&d, &im), ppi, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A turned JPEG that a linked SVG file links to is turned too.
|
||||
#[test]
|
||||
fn a_turned_jpeg_linked_from_a_linked_svg_file_imports_upright() {
|
||||
|
||||
@@ -974,7 +974,7 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() {
|
||||
vec![(0..2, 20.0), (3..4, 100.0), (4..5, 160.0)],
|
||||
),
|
||||
];
|
||||
let unplaced = |w: &[String]| w.iter().any(|w| w.contains("absolutely placed"));
|
||||
let unplaced = |w: &[String]| w.iter().any(|w| w.contains("point type objects"));
|
||||
for (body, share, chunks) in cases {
|
||||
let (d, w) = import_with_report(&svg(&body)).unwrap();
|
||||
assert!(!unplaced(&w), "{body}: {w:?}");
|
||||
@@ -988,12 +988,82 @@ fn absolutely_placed_right_to_left_characters_sit_on_their_own_x() {
|
||||
assert!(close(left, want, 0.05), "{body}: the chunk {bytes:?} spans {left}..{right}, so it does not start at {want}");
|
||||
}
|
||||
}
|
||||
// A left-to-right character between right-to-left ones is drawn right next to the one after
|
||||
// it, with no kerning between them: that one keeps its place in the line, and a warning says so.
|
||||
let (d, w) = import_with_report(&svg(r#"<text x="100 160 220" y="80" direction="rtl" font-size="20">אbג</text>"#)).unwrap();
|
||||
assert!(unplaced(&w), "{w:?}");
|
||||
let (left, right) = chunk_edges(only_text(&d), 2..3);
|
||||
assert!(close(right, 160.0, 0.05), "b spans {left}..{right}");
|
||||
}
|
||||
|
||||
/// The document-space edges of character `ch`, in whichever text of `d` holds it (as
|
||||
/// [`chunk_edges`] measures them), and the y it is drawn at (its baseline moved by its baseline
|
||||
/// shift).
|
||||
fn char_edges(d: &Document, ch: char) -> (f64, f64, f64) {
|
||||
let t = texts(d).into_iter().find(|t| t.plain_text().contains(ch)).unwrap_or_else(|| panic!("no text holds {ch}"));
|
||||
let at = t.plain_text().find(ch).unwrap();
|
||||
let (left, right) = chunk_edges(t, at..at + ch.len_utf8());
|
||||
let shift = t.runs.iter().find(|r| r.text.contains(ch)).unwrap().style.baseline_shift;
|
||||
let y = layout(FontDb::global(), t).glyphs.iter().find(|g| g.byte == at).map(|g| (t.xf * g.origin).y).unwrap() - shift;
|
||||
(left, right, y)
|
||||
}
|
||||
|
||||
/// SVG 2 › Text (https://www.w3.org/TR/SVG2/text.html): each absolute position starts a chunk,
|
||||
/// and bidi reordering happens only within a chunk. A left-to-right character drawn right before a
|
||||
/// right-to-left one has no kerning between them in one text object, so such a text imports as a
|
||||
/// group of point type objects, each character on its own x.
|
||||
#[test]
|
||||
fn absolutely_placed_characters_one_object_cannot_place_import_as_a_group() {
|
||||
// (markup, the characters of its objects in order, each character with the x its right edge
|
||||
// sits on and its baseline)
|
||||
type Case = (&'static str, &'static str, Vec<(char, f64, f64)>);
|
||||
let cases: Vec<Case> = vec![
|
||||
(
|
||||
r#"<text id="t" x="100 160 220" y="80" direction="rtl" font-size="20">אbג</text>"#,
|
||||
"אbג",
|
||||
vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0)],
|
||||
),
|
||||
(
|
||||
r#"<text id="t" x="100 160 220 280" y="80" direction="rtl" font-size="20">אbגd</text>"#,
|
||||
"אbגd",
|
||||
vec![('א', 100.0, 80.0), ('b', 160.0, 80.0), ('ג', 220.0, 80.0), ('d', 280.0, 80.0)],
|
||||
),
|
||||
// x values that decrease.
|
||||
(
|
||||
r#"<text id="t" x="220 160 100" y="80" direction="rtl" font-size="20">אbג</text>"#,
|
||||
"אbג",
|
||||
vec![('א', 220.0, 80.0), ('b', 160.0, 80.0), ('ג', 100.0, 80.0)],
|
||||
),
|
||||
// On a second line, and with a baseline of its own.
|
||||
(
|
||||
r#"<text id="t" direction="rtl" font-size="20"><tspan x="40" y="40">אב</tspan><tspan x="100 160 220" y="80 80 90">גbד</tspan></text>"#,
|
||||
"אבגbד",
|
||||
vec![('א', 40.0, 40.0), ('ג', 100.0, 80.0), ('b', 160.0, 80.0), ('ד', 220.0, 90.0)],
|
||||
),
|
||||
];
|
||||
for (body, text, chars) in cases {
|
||||
let (d, w) = import_with_report(&svg(body)).unwrap();
|
||||
assert!(w.iter().any(|w| w.contains("point type objects in a group")), "{body}: {w:?}");
|
||||
let top = d.layers[0].children().unwrap();
|
||||
assert_eq!(top.len(), 1, "{body}: {top:?}");
|
||||
assert_eq!(top[0].name.as_deref(), Some("t"), "{body}: the group takes the element's id");
|
||||
let NodeKind::Group { children, clip: false } = &top[0].kind else { panic!("{body}: {:?}", top[0].kind) };
|
||||
assert!(children.len() > 1 && children.iter().all(|c| matches!(c.kind, NodeKind::Text(_))), "{body}: {children:?}");
|
||||
let all: String = texts(&d).iter().map(|t| t.plain_text().replace('\n', "")).collect();
|
||||
assert_eq!(all, text, "{body}: every character once, in order");
|
||||
for (ch, x, y) in chars {
|
||||
let (left, right, base) = char_edges(&d, ch);
|
||||
assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}");
|
||||
assert!(close(base, y, 1e-6), "{body}: {ch} sits on {base}, not {y}");
|
||||
}
|
||||
}
|
||||
// Placed characters one object can place stay one object, also when their x values decrease.
|
||||
for (body, chars) in [
|
||||
(r#"<text x="100 160 220" y="80" direction="rtl" font-size="20">אbc</text>"#, [('א', 100.0), ('b', 160.0), ('c', 220.0)]),
|
||||
(r#"<text x="220 160 100" y="80" direction="rtl" font-size="20">אבג</text>"#, [('א', 220.0), ('ב', 160.0), ('ג', 100.0)]),
|
||||
] {
|
||||
let (d, w) = import_with_report(&svg(body)).unwrap();
|
||||
assert!(!w.iter().any(|w| w.contains("point type objects")), "{body}: {w:?}");
|
||||
only_text(&d);
|
||||
for (ch, x) in chars {
|
||||
let (left, right, _) = char_edges(&d, ch);
|
||||
assert!(close(right, x, 0.05), "{body}: {ch} spans {left}..{right}, not ending at {x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -118,6 +118,49 @@ fn opaque_pixels_stay_opaque_where_warp_pieces_overlap() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Pieces the file leaves out share no image: with Images set to Link, the warp pieces of a linked
|
||||
/// image that are hidden, or sit in hidden clip groups, put no `<image>` naming its file in the
|
||||
/// defs unless hidden layers are kept. Visible pieces share one.
|
||||
#[test]
|
||||
fn hidden_warp_pieces_share_no_image() {
|
||||
let path = "/away/photo.png";
|
||||
let svg = |d: &Document, hidden_layers: bool| {
|
||||
let opts = ExportOptions { images: vectorcraft_svg::ImageMode::Link, hidden_layers, ..ExportOptions::default() };
|
||||
export_full(d, &opts, None).svg
|
||||
};
|
||||
// Every image in `n` linked to `path`.
|
||||
fn link(n: &mut Node, path: &str) {
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new(path));
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
link(std::sync::Arc::make_mut(c), path);
|
||||
}
|
||||
}
|
||||
for masked in [false, true] {
|
||||
// Hide every image (`ancestor` false), or every clip group holding one (`ancestor` true).
|
||||
for ancestor in [false, true] {
|
||||
let mut d = warped_pixels(&|p| p, masked, [255, 0, 0, 255], |_| {});
|
||||
let layer = std::sync::Arc::make_mut(&mut d.layers[0]);
|
||||
let g = std::sync::Arc::make_mut(&mut layer.children_mut().unwrap()[0]);
|
||||
link(g, path);
|
||||
let visible = d.clone();
|
||||
assert_eq!(svg(&visible, false).matches(path).count(), 1, "masked {masked}: the pieces share one image");
|
||||
let layer = std::sync::Arc::make_mut(&mut d.layers[0]);
|
||||
let g = std::sync::Arc::make_mut(&mut layer.children_mut().unwrap()[0]);
|
||||
for piece in g.children_mut().unwrap() {
|
||||
let piece = std::sync::Arc::make_mut(piece);
|
||||
match piece.children_mut() {
|
||||
Some(kids) if !ancestor => std::sync::Arc::make_mut(&mut kids[1]).visible = false,
|
||||
_ => piece.visible = false,
|
||||
}
|
||||
}
|
||||
assert!(!svg(&d, false).contains(path), "masked {masked}, ancestor {ancestor}: {}", svg(&d, false));
|
||||
assert_eq!(svg(&d, true).matches(path).count(), 1, "masked {masked}, ancestor {ancestor}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pieces of an opaque image are drawn one over another without knockout masks; a colorize paint
|
||||
/// draws a gray image's light pixels partly transparent, so its pieces take them.
|
||||
#[test]
|
||||
|
||||
@@ -258,18 +258,43 @@ impl Ctx<'_> {
|
||||
// of the glyph before it takes no cell of its own: it turns with that glyph (`emit`).
|
||||
for i in 0..v.len() {
|
||||
let continues = continues_cluster(i.checked_sub(1).and_then(|p| v.get(p)), v.get(i));
|
||||
let Some(g) = v.get_mut(i).filter(|g| g.adv > 0.0 && !continues && stands_upright(g)) else { continue };
|
||||
let extra = upright_cell(g) - g.face.advance(g.gid) * g.sx;
|
||||
if continues || !v.get(i).is_some_and(stands_upright) {
|
||||
continue;
|
||||
}
|
||||
// Tsume measured the cluster across its glyphs' widths when it was shaped: an
|
||||
// upright glyph's blank space runs down its cell, so that is taken back first.
|
||||
let measured_down = v.get(i).is_some_and(|g| g.tcy.is_none());
|
||||
if measured_down {
|
||||
let end = (i + 1..v.len()).find(|&j| !continues_cluster(v.get(j - 1), v.get(j))).unwrap_or(v.len());
|
||||
let tsume = v.get(end - 1).map_or(0.0, |g| g.tsume);
|
||||
for g in v.get_mut(i..end).unwrap_or_default() {
|
||||
g.dx += g.tsume_shift;
|
||||
g.tsume_shift = 0.0;
|
||||
}
|
||||
if let Some(g) = v.get_mut(end - 1) {
|
||||
g.adv += tsume;
|
||||
g.tsume = 0.0;
|
||||
}
|
||||
}
|
||||
let Some(g) = v.get_mut(i).filter(|g| g.adv > 0.0) else { continue };
|
||||
let cell = upright_cell(g);
|
||||
let extra = cell - g.face.advance(g.gid) * g.sx;
|
||||
g.dx += extra * 0.5;
|
||||
g.adv += extra;
|
||||
// Proportional Metrics: `vpal` (and the vertical kerning with it) moves it and
|
||||
// changes its length down the column, in fonts with vertical metrics (else the cell
|
||||
// stays as it is, #966).
|
||||
let mut length = cell;
|
||||
if let Some(a) = g.vpal.filter(|_| g.tcy.is_none() && g.face.vertical_glyph(g.gid).is_some()) {
|
||||
g.dx += a.dx;
|
||||
g.dy += a.dy;
|
||||
g.adv += a.advance;
|
||||
g.proportional = a.proportional;
|
||||
length += a.advance;
|
||||
}
|
||||
let st = style(g);
|
||||
if measured_down && st.tsume > 0.0 {
|
||||
self.tighten_upright(g, cell, length, st.size, st.tsume);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -286,6 +311,25 @@ impl Ctx<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tsume `tsume` on upright glyph `g` in vertical type, in type of size `em`, its cell `cell`
|
||||
/// long down the column and `length` long with the Proportional Metrics change to it: its share
|
||||
/// of the blank space above and below what it paints, inside that length, comes out of its
|
||||
/// advance, and it is drawn the share above it earlier, keeping its shape. A combining mark in
|
||||
/// its cluster moves with it. A glyph that paints nothing keeps its place and length.
|
||||
fn tighten_upright(&self, g: &mut SGlyph, cell: f64, length: f64, em: f64, tsume: f64) {
|
||||
let Some(b) = crate::shape::painted_box(self.db, g) else { return };
|
||||
// The glyph turns about the center of its cell, which is `upright_centre` above the
|
||||
// baseline: a point of it in font units (y down) lands that far below the center, down the
|
||||
// column from the top of the cell.
|
||||
let centre = cell * 0.5 + upright_centre(g, cell, em) + g.dy;
|
||||
let (a, z) = (centre + b.y0 * g.sy, centre + b.y1 * g.sy);
|
||||
let Some((above, below)) = crate::shape::tsume_shares((a.min(z), a.max(z)), length, tsume) else { return };
|
||||
g.kern_shift -= above;
|
||||
g.tsume_shift = above;
|
||||
g.adv -= above + below;
|
||||
g.tsume = above + below;
|
||||
}
|
||||
|
||||
/// Bullets and numbered lists: put marker `text` (the bullet, or the number and its period;
|
||||
/// [`list_markers`]) of list paragraph `pr` (attributes `para`, right to left when `rtl`)
|
||||
/// before its glyphs `sg` and return how many glyphs went in (none for a paragraph without a
|
||||
|
||||
+45
-28
@@ -598,7 +598,7 @@ pub(crate) fn shape_runs(
|
||||
// Synthesized Small Caps shape lowercase letters separately (as smaller capitals).
|
||||
let small_caps = st.small_caps.is_some() && !st.all_caps;
|
||||
// Split into segments by font coverage (and case, for Small Caps).
|
||||
let mut seg = Segment { range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) };
|
||||
let mut seg = Segment { db, range: a..a, runs, source_runs, st, face: primary.clone(), small: false, level: level_at(a) };
|
||||
let mut cache: std::collections::HashMap<&str, Arc<FontFace>> = std::collections::HashMap::new();
|
||||
let mut script = Script::Common;
|
||||
// A grapheme cluster (a letter and its marks, an emoji sequence) is set in one face.
|
||||
@@ -1354,6 +1354,7 @@ fn inline_glyph(
|
||||
/// alike ([`shapes_alike`]).
|
||||
#[derive(Clone)]
|
||||
struct Segment<'a> {
|
||||
db: &'a FontDb,
|
||||
range: Range<usize>,
|
||||
/// All the runs, and the indices of those the piece's shaping span takes in.
|
||||
runs: &'a [(Range<usize>, &'a CharStyle)],
|
||||
@@ -1413,7 +1414,7 @@ fn is_mark(c: char) -> bool {
|
||||
/// SS). A cluster that would take in characters of runs with different drawing attributes (a
|
||||
/// ligature, a base with its marks) is not formed, except for paint-only harakat differences.
|
||||
fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFeatures, out: &mut Vec<SGlyph>) {
|
||||
let Segment { range, runs, source_runs, st, face, small, level } = seg;
|
||||
let Segment { db, range, runs, source_runs, st, face, small, level } = seg;
|
||||
let (range, small) = (range.clone(), *small);
|
||||
// The source runs the segment's bytes lie in (a span can hold many segments).
|
||||
let span = runs.get(source_runs.clone()).unwrap_or_default();
|
||||
@@ -1507,8 +1508,8 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
}
|
||||
ranged
|
||||
};
|
||||
// Horizontal type with Tsume on any of the segment's characters.
|
||||
let tsume_here = !feats.vertical && runs.get(source_runs.clone()).unwrap_or_default().iter().any(|(_, s)| s.tsume > 0.0);
|
||||
// Tsume on any of the segment's characters.
|
||||
let tsume_here = runs.get(source_runs.clone()).unwrap_or_default().iter().any(|(_, s)| s.tsume > 0.0);
|
||||
// Shape the segment as if all of it were in `st`, with the features `more` on top.
|
||||
let shape_in = |st: &CharStyle, more: &[Feature]| {
|
||||
// A BCP 47 tag is short ASCII; anything else (a file may hold anything) is shaped without one.
|
||||
@@ -1888,10 +1889,11 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
hyphen_language: crate::hyphen::Language::from_tag(gst.language.as_deref()),
|
||||
});
|
||||
// Tsume takes its share of the blank space beside the cluster's ink once the cluster is
|
||||
// complete, in horizontal type.
|
||||
if last_in_cluster && !invisible && !feats.vertical && gst.tsume > 0.0 {
|
||||
// complete, along the line. In vertical type a glyph that stands upright is measured down
|
||||
// the column instead, once its cell is known ([`crate::layout`]).
|
||||
if last_in_cluster && !invisible && gst.tsume > 0.0 {
|
||||
let first = out.iter().rposition(|g| g.byte != cl).map_or(0, |i| i + 1);
|
||||
tighten(out.get_mut(first..).unwrap_or_default(), own, gst.tsume);
|
||||
tighten(db, out.get_mut(first..).unwrap_or_default(), own, gst.tsume);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1902,25 +1904,20 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
/// and its ink, on each side, comes out of the cluster's advance, and its glyphs are drawn the
|
||||
/// left side's share earlier ([`SGlyph::tsume`] and [`SGlyph::tsume_shift`] hold both, for Optical
|
||||
/// kerning to measure the pair without them). A cluster without ink, such as a space, or with a
|
||||
/// width that is not positive, keeps its place and width.
|
||||
fn tighten(glyphs: &mut [SGlyph], own: f64, tsume: f64) {
|
||||
/// width that is not positive, keeps its place and width. The ink is what the glyph paints
|
||||
/// ([`painted_box`]): its color art or bitmap when it has one, else its outline.
|
||||
fn tighten(db: &FontDb, glyphs: &mut [SGlyph], own: f64, tsume: f64) {
|
||||
let Some(last) = glyphs.len().checked_sub(1) else { return };
|
||||
let share = if tsume.is_nan() { 0.0 } else { tsume.clamp(0.0, MAX_TSUME) / 100.0 };
|
||||
let (mut pen, mut ink): (f64, Option<(f64, f64)>) = (0.0, None);
|
||||
for (i, g) in glyphs.iter().enumerate() {
|
||||
if let Some((a, b)) = ink_across(&g.face, g.gid) {
|
||||
let (a, b) = (pen + g.dx + a * g.sx, pen + g.dx + b * g.sx);
|
||||
if let Some(b) = painted_box(db, g) {
|
||||
let (a, b) = (pen + g.dx + b.x0 * g.sx, pen + g.dx + b.x1 * g.sx);
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
ink = Some(ink.map_or((lo, hi), |(l, h)| (l.min(lo), h.max(hi))));
|
||||
}
|
||||
pen += if i == last { own } else { g.adv };
|
||||
}
|
||||
let Some((lo, hi)) = ink.filter(|(lo, hi)| lo.is_finite() && hi.is_finite()) else { return };
|
||||
if !(pen.is_finite() && pen > 0.0) {
|
||||
return;
|
||||
}
|
||||
let left = lo.clamp(0.0, pen) * share;
|
||||
let right = (pen - hi).clamp(0.0, pen) * share;
|
||||
let Some((left, right)) = ink.and_then(|ink| tsume_shares(ink, pen, tsume)) else { return };
|
||||
for g in glyphs.iter_mut() {
|
||||
g.dx -= left;
|
||||
g.tsume_shift = left;
|
||||
@@ -1931,18 +1928,38 @@ fn tighten(glyphs: &mut [SGlyph], own: f64, tsume: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The left and right edges of glyph `gid`'s outline in `face`, in font units; `None` for a glyph
|
||||
/// without an outline (a space, or a bitmap or color glyph without one).
|
||||
fn ink_across(face: &FontFace, gid: u32) -> Option<(f64, f64)> {
|
||||
let font = face.skrifa()?;
|
||||
let glyph = font.outline_glyphs().get(skrifa::GlyphId::new(gid))?;
|
||||
let mut pen = crate::fontdb::FlipPen(kurbo::BezPath::new());
|
||||
glyph.draw(skrifa::outline::DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen).ok()?;
|
||||
if pen.0.elements().is_empty() {
|
||||
/// What Tsume `tsume` (percent) takes off before and after ink running from `lo` to `hi` along a
|
||||
/// cell running from 0 to `length`: its share of the blank space on each side, inside the cell.
|
||||
/// `None` when the ink or the cell is not finite, or the cell's length is not positive.
|
||||
pub(crate) fn tsume_shares((lo, hi): (f64, f64), length: f64, tsume: f64) -> Option<(f64, f64)> {
|
||||
let share = if tsume.is_nan() { 0.0 } else { tsume.clamp(0.0, MAX_TSUME) / 100.0 };
|
||||
if !(lo.is_finite() && hi.is_finite() && length.is_finite() && length > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let b = pen.0.bounding_box();
|
||||
Some((b.x0, b.x1))
|
||||
Some((lo.clamp(0.0, length) * share, (length - hi).clamp(0.0, length) * share))
|
||||
}
|
||||
|
||||
/// The box of what glyph `g` paints, in font units (y down, as outlines are), as the layout draws
|
||||
/// it: its COLR or SVG art, else its color bitmap, else its outline. `None` for a glyph that paints
|
||||
/// nothing: a space, a control or format character, or art, an image or an outline that is empty
|
||||
/// or not finite.
|
||||
pub(crate) fn painted_box(db: &FontDb, g: &SGlyph) -> Option<kurbo::Rect> {
|
||||
if g.inline.is_some() || g.is_soft_hyphen() || g.ch.is_control() || g.ch == '\u{2028}' || crate::justify::is_format_control(g.ch) {
|
||||
return None;
|
||||
}
|
||||
let image_box = |image: &crate::GlyphImage| image.xf.transform_rect_bbox(image.rect());
|
||||
let b = match db.glyph_colour(&g.face, g.gid, vectorcraft_doc::color::Color::BLACK, None) {
|
||||
Some(crate::colr::ColourContent::Art(art)) => art.geometric_bounds(),
|
||||
Some(crate::colr::ColourContent::Image(image)) => Some(image_box(&image)),
|
||||
None => match db.glyph_image(&g.face, g.gid) {
|
||||
Some(image) => Some(image_box(&image)),
|
||||
None => {
|
||||
let outline = db.outline(&g.face, g.gid);
|
||||
(!outline.elements().is_empty()).then(|| outline.bounding_box())
|
||||
}
|
||||
},
|
||||
};
|
||||
b.filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && (b.width() > 0.0 || b.height() > 0.0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Tsume (`CharStyle::tsume`): the share of the blank space on each side of a character's ink,
|
||||
//! inside its own width, that horizontal type takes away, the glyph keeping its shape.
|
||||
//! inside its own width (in vertical type, down an upright character's cell), that is taken away,
|
||||
//! the glyph keeping its shape.
|
||||
use super::{area, db, point, style};
|
||||
use crate::*;
|
||||
use kurbo::Shape;
|
||||
@@ -150,13 +151,134 @@ fn justification_keeps_the_tsume() {
|
||||
assert!(gap(<) < gap(&lp) - 1.0, "{} {}", gap(&lp), gap(<));
|
||||
}
|
||||
|
||||
fn vertical(text: &str, st: CharStyle) -> TextObject {
|
||||
let mut t = point(text, st);
|
||||
t.xf = Affine::IDENTITY;
|
||||
t.vertical = true;
|
||||
t
|
||||
}
|
||||
|
||||
/// The box of what glyph `byte` paints: its outline, its bitmap or its color art.
|
||||
fn painted(l: &TextLayout, byte: usize) -> Rect {
|
||||
let g = l.glyphs.iter().find(|g| g.byte == byte).unwrap();
|
||||
let image = g.placed_image().map(|(image, xf)| xf.transform_rect_bbox(image.rect()));
|
||||
let colour = g.colour.as_ref().and_then(|c| c.geometric_bounds()).map(|b| g.xf.transform_rect_bbox(b));
|
||||
image.or(colour).unwrap_or_else(|| g.outline.bounding_box())
|
||||
}
|
||||
|
||||
/// Where glyph `byte`'s cell starts down a vertical column.
|
||||
fn cell_top(l: &TextLayout, byte: usize) -> f64 {
|
||||
l.glyphs.iter().find(|g| g.byte == byte).map(|g| g.origin.y).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_type_keeps_its_spacing() {
|
||||
for text in ["§§", "ab"] {
|
||||
let mut plain = point(text, style(20.0));
|
||||
plain.xf = Affine::IDENTITY;
|
||||
plain.vertical = true;
|
||||
let centers = |t: &TextObject| layout(db(), t).glyphs.iter().map(|g| g.outline.bounding_box().center()).collect::<Vec<_>>();
|
||||
assert_eq!(centers(&with(&plain, 0, |s| s.tsume = 100.0)), centers(&plain), "{text}");
|
||||
fn upright_glyphs_take_their_share_of_the_space_above_and_below_their_ink() {
|
||||
use crate::test_fonts::{VERTICAL_FAMILY, vertical_font};
|
||||
// The bundled font without vertical metrics (a cell of one em), and with them: § 1.4 em down
|
||||
// the column from its vertical origin, given by VORG or by its top side bearing.
|
||||
for vorg in [None, Some(false), Some(true)] {
|
||||
let fonts = FontDb::with_font_dirs(vec![]);
|
||||
let mut st = style(20.0);
|
||||
if let Some(vorg) = vorg {
|
||||
fonts.add_font(vertical_font(vorg).unwrap());
|
||||
st.font_family = VERTICAL_FAMILY.into();
|
||||
}
|
||||
let plain = vertical("§§§", st.clone());
|
||||
let lp = layout(&fonts, &plain);
|
||||
let (before, after) = (painted(&lp, 2).y0 - cell_top(&lp, 2), cell_top(&lp, 4) - painted(&lp, 2).y1);
|
||||
assert!(before > 1.0 && after > 1.0, "{vorg:?}: {before} {after}");
|
||||
for tsume in [25.0, 100.0] {
|
||||
let share = tsume / 100.0;
|
||||
let lt = layout(&fonts, &with(&plain, 2, |s| s.tsume = tsume));
|
||||
// The middle § moves up by its share of the space above its ink, and the § after it by
|
||||
// the share of the space above and below it; the first stays, and the glyph keeps its
|
||||
// shape.
|
||||
let moved = (painted(<, 2).y0 - painted(&lp, 2).y0, painted(<, 4).y0 - painted(&lp, 4).y0);
|
||||
assert!((moved.0 + before * share).abs() < 1e-6, "{vorg:?} {tsume}: {moved:?}");
|
||||
assert!((moved.1 + (before + after) * share).abs() < 1e-6, "{vorg:?} {tsume}: {moved:?}");
|
||||
assert!((painted(<, 2).height() - painted(&lp, 2).height()).abs() < 1e-6);
|
||||
assert!((painted(<, 2).center().x - painted(&lp, 2).center().x).abs() < 1e-6, "it stays on the column's center line");
|
||||
assert!((painted(<, 0).y0 - painted(&lp, 0).y0).abs() < 1e-9);
|
||||
}
|
||||
// At 100% the ink runs edge to edge down the column.
|
||||
let lt = layout(&fonts, &with(&plain, 2, |s| s.tsume = 100.0));
|
||||
assert!((painted(<, 2).y0 - cell_top(&lp, 2)).abs() < 1e-6 && (cell_top(<, 4) - painted(<, 2).y1).abs() < 1e-6, "{vorg:?}");
|
||||
// A space keeps its length down the column.
|
||||
let spaced = vertical("§ §", st);
|
||||
let tops = |t: &TextObject| layout(&fonts, t).glyphs.iter().map(|g| g.origin.y).collect::<Vec<_>>();
|
||||
assert_eq!(tops(&with(&spaced, 2, |s| s.tsume = 100.0)), tops(&spaced), "{vorg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letters_on_their_side_take_the_tsume_of_horizontal_type() {
|
||||
// In vertical type a letter lies on its side: its space before and after its ink runs down
|
||||
// the column, as far as it runs along a horizontal line.
|
||||
let (across, down) = (point("HOH", style(20.0)), vertical("HOH", style(20.0)));
|
||||
let moves_along = |t: &TextObject, vertical: bool| {
|
||||
let (lp, lt) = (layout(db(), t), layout(db(), &with(t, 1, |s| s.tsume = 100.0)));
|
||||
[1, 2].map(|i| if vertical { painted(<, i).y0 - painted(&lp, i).y0 } else { painted(<, i).x0 - painted(&lp, i).x0 })
|
||||
};
|
||||
let (h, v) = (moves_along(&across, false), moves_along(&down, true));
|
||||
assert!(h[1] < -1.0 && near(&v, &h), "{h:?} {v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsume_inside_a_tate_chu_yoko_block_keeps_its_cell() {
|
||||
// Two digits are set across the column as one block one em long; Tsume closes them up across
|
||||
// it, and the letter after the block keeps its place.
|
||||
let plain = vertical("H12H", style(20.0));
|
||||
let tight = with(&with(&plain, 1, |s| s.tsume = 100.0), 2, |s| s.tsume = 100.0);
|
||||
let (lp, lt) = (layout(db(), &plain), layout(db(), &tight));
|
||||
let side_by_side = (painted(&lp, 1).center().y - painted(&lp, 2).center().y).abs();
|
||||
assert!(side_by_side < 1.0, "the digits stand side by side across the column: {side_by_side}");
|
||||
let apart = |l: &TextLayout| (painted(l, 2).center().x - painted(l, 1).center().x).abs();
|
||||
assert!(apart(<) < apart(&lp) - 1.0, "{} {}", apart(&lp), apart(<));
|
||||
assert!((painted(<, 3).y0 - painted(&lp, 3).y0).abs() < 1e-9);
|
||||
assert!((painted(<, 1).width() - painted(&lp, 1).width()).abs() < 1e-6, "the digits keep their size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upright_glyphs_on_a_vertical_path_take_the_tsume_of_point_type() {
|
||||
use vectorcraft_doc::TextKind;
|
||||
use vectorcraft_geom::PathData;
|
||||
let point_type = vertical("§§§", style(20.0));
|
||||
let mut on_path = point_type.clone();
|
||||
on_path.kind =
|
||||
TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (0.0, 3000.0)).to_path(0.1)), start: 0.0, end: None };
|
||||
let moved = |t: &TextObject| {
|
||||
let (lp, lt) = (layout(db(), t), layout(db(), &with(t, 2, |s| s.tsume = 100.0)));
|
||||
[2, 4].map(|i| painted(<, i).y0 - painted(&lp, i).y0)
|
||||
};
|
||||
let (p, path) = (moved(&point_type), moved(&on_path));
|
||||
assert!(p[1] < -1.0 && near(&path, &p), "{p:?} {path:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmap_and_color_glyphs_measure_what_they_paint() {
|
||||
use crate::test_fonts::{COLOUR_CHAR, colour_bitmap_family, colour_bitmap_font, colr_family, colr_font};
|
||||
// Each font keeps the base outline of its color glyph; the image or art drawn in its place is
|
||||
// what Tsume measures.
|
||||
let fonts = [
|
||||
(colour_bitmap_font(true), colour_bitmap_family(true)),
|
||||
(colour_bitmap_font(false), colour_bitmap_family(false)),
|
||||
(colr_font(false), colr_family(false)),
|
||||
(colr_font(true), colr_family(true)),
|
||||
];
|
||||
for (font, family) in fonts {
|
||||
let fonts = FontDb::with_font_dirs(vec![]);
|
||||
fonts.add_font(font.expect("the test font builds"));
|
||||
let plain = point(&format!("{COLOUR_CHAR}H"), CharStyle { font_family: family.into(), ..style(100.0) });
|
||||
let lp = layout(&fonts, &plain);
|
||||
let g = &lp.glyphs[0];
|
||||
assert!(g.image.is_some() || g.colour.is_some(), "{family}");
|
||||
let (start, end) = (g.origin.x, lp.glyphs[1].origin.x);
|
||||
let p = painted(&lp, 0);
|
||||
let width = end - start;
|
||||
let (left, right) = ((p.x0 - start).clamp(0.0, width), (end - p.x1).clamp(0.0, width));
|
||||
let lt = layout(&fonts, &with(&plain, 0, |s| s.tsume = 100.0));
|
||||
let moved = (painted(<, 0).x0 - p.x0, lt.glyphs[1].origin.x - end);
|
||||
assert!((moved.0 + left).abs() < 1e-6 && (moved.1 + left + right).abs() < 1e-6, "{family}: {moved:?} {left} {right}");
|
||||
assert!((painted(<, 0).width() - p.width()).abs() < 1e-6, "{family}");
|
||||
}
|
||||
}
|
||||
@@ -190,6 +190,10 @@ pub struct GestureTool {
|
||||
/// Which way the pen leaned at the last point of the stroke where it leaned 1° or more from
|
||||
/// upright ([`super::pen_bearing`]), for the Eraser's tip outline.
|
||||
bearing: Option<f64>,
|
||||
/// `bearing` as it was at each of `poses`, for the outline of the area the Eraser's drag covers.
|
||||
bearings: Vec<Option<f64>>,
|
||||
/// The first of `bearings` that the pen gave: the release gives it to the points before it.
|
||||
first_bearing: Option<f64>,
|
||||
/// The length of the stroke, in points.
|
||||
length: f64,
|
||||
/// The outline of the area a Blob Brush or Eraser drag covers, as far as it is built
|
||||
@@ -878,6 +882,8 @@ impl GestureTool {
|
||||
tip_at: None,
|
||||
light: false,
|
||||
bearing: None,
|
||||
bearings: vec![],
|
||||
first_bearing: None,
|
||||
length: 0.0,
|
||||
area: Cell::new(None),
|
||||
area_pending: Cell::new(false),
|
||||
@@ -945,6 +951,8 @@ impl GestureTool {
|
||||
let pose = ev.pen.map(PenPose::sanitized);
|
||||
self.bearing = pose.and_then(super::pen_bearing).or(self.bearing);
|
||||
self.poses.push(pose);
|
||||
self.bearings.push(self.bearing);
|
||||
self.first_bearing = self.first_bearing.or(self.bearing);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -966,6 +974,14 @@ impl GestureTool {
|
||||
None if had_bearing => self.poses.iter().rev().find_map(|q| q.and_then(super::pen_bearing)),
|
||||
None => self.bearing,
|
||||
};
|
||||
if let Some(b) = self.bearings.last_mut() {
|
||||
*b = self.bearing;
|
||||
}
|
||||
// The bearings carry forward, so the last sample gives the first bearing only when the one
|
||||
// before it has none.
|
||||
if self.bearings.len().checked_sub(2).and_then(|i| self.bearings.get(i)).copied().flatten().is_none() {
|
||||
self.first_bearing = self.bearing;
|
||||
}
|
||||
}
|
||||
|
||||
/// Would a press with `m` held draw a straight Pencil line? Shift or Alt held, unless Alt lends
|
||||
@@ -1053,6 +1069,8 @@ impl GestureTool {
|
||||
self.shift_line = None;
|
||||
self.light = false;
|
||||
self.bearing = None;
|
||||
self.bearings.clear();
|
||||
self.first_bearing = None;
|
||||
self.length = 0.0;
|
||||
self.area.set(None);
|
||||
self.area_pending.set(false);
|
||||
@@ -1113,12 +1131,74 @@ impl GestureTool {
|
||||
matches!(self.id, "blobBrush" | "eraser")
|
||||
}
|
||||
|
||||
/// The pen pressure of each point of a Blob Brush or Eraser stroke whose Size varies with
|
||||
/// Pressure, when a pen pressed less than fully anywhere along it (a stroke without pressure
|
||||
/// keeps its Size).
|
||||
fn size_pressures(&self) -> Option<&[f32]> {
|
||||
let pressed = self.pressures.len() == self.points.len() && self.light;
|
||||
(self.tip_modes()[2] == Variation::Pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice())
|
||||
/// Which of the tip's angle, roundness and size vary along a Blob Brush or Eraser stroke: those
|
||||
/// on a mode the pen gave a reading for anywhere along it (a pressure less than full, a tilt, a
|
||||
/// bearing or a rotation). Random draws one value from the whole drag at the release, and the
|
||||
/// outline shows the value itself.
|
||||
fn tip_varies(&self) -> [bool; 3] {
|
||||
let (pressed, posed) = (self.reads_pressures(), self.reads_poses());
|
||||
let reads = |mode: Variation| match mode {
|
||||
Variation::Pressure => pressed,
|
||||
Variation::Tilt => posed && self.poses.iter().flatten().any(|q| q.tilt.is_some()),
|
||||
Variation::Bearing => posed && self.bearings.iter().any(Option::is_some),
|
||||
Variation::Rotation => posed && self.poses.iter().flatten().any(|q| q.rotation.is_some()),
|
||||
Variation::Fixed | Variation::Random => false,
|
||||
};
|
||||
if self.smoothing {
|
||||
return [false; 3];
|
||||
}
|
||||
self.tip_modes().map(reads)
|
||||
}
|
||||
|
||||
/// Does the release read the stroke's pressures ([`Self::stroke_json`]): one for every point,
|
||||
/// with the pen pressed less than fully somewhere? A mode set to Pressure during the drag
|
||||
/// leaves the points before it without one.
|
||||
fn reads_pressures(&self) -> bool {
|
||||
self.light && self.pressures.len() == self.points.len()
|
||||
}
|
||||
|
||||
/// Does the release read the stroke's tilts and rotations ([`Self::stroke_json`]): a pose for
|
||||
/// every point? A mode set to Tilt, Bearing or Rotation during the drag leaves the points
|
||||
/// before it without one.
|
||||
fn reads_poses(&self) -> bool {
|
||||
self.poses.len() == self.points.len()
|
||||
}
|
||||
|
||||
/// The tip at point `i` of the stroke, as `path.eraseRegion` reads the pen there
|
||||
/// ([`Self::controls_of_point`]).
|
||||
fn tip_of_point(&self, i: usize) -> [f64; 3] {
|
||||
self.tip_of_controls(self.controls_of_point(i))
|
||||
}
|
||||
|
||||
/// The tip halfway along the step from point `j` to point `j + 1`, as `path.eraseRegion` reads
|
||||
/// the pen there: the pressure and tilt halfway between those at the two points, and the
|
||||
/// bearing and rotation halfway between them the shorter way round. A tip whose angle follows
|
||||
/// the pressure from 0 at one point to 1 at the next lies level there, not turned as at
|
||||
/// either end.
|
||||
fn tip_between(&self, j: usize) -> [f64; 3] {
|
||||
let (a, b) = (self.controls_of_point(j), self.controls_of_point(j + 1));
|
||||
// Bearing and rotation read ½ plus the angle over 360° ([`super::pen_controls`]).
|
||||
let turn = |a: f64, b: f64| {
|
||||
let (a, b) = ((a - 0.5) * 360.0, (b - 0.5) * 360.0);
|
||||
0.5 + vectorcraft_geom::normalize_deg(a + vectorcraft_geom::normalize_deg(b - a) / 2.0) / 360.0
|
||||
};
|
||||
self.tip_of_controls([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, turn(a[2], b[2]), turn(a[3], b[3])])
|
||||
}
|
||||
|
||||
/// What each of the variation modes Pressure, Tilt, Bearing and Rotation reads at point `i` of
|
||||
/// the stroke, as `path.eraseRegion` reads the pen there ([`super::pen_controls`]): the
|
||||
/// pressure once the pen has pressed less than fully, the tilt and rotation of the point, and
|
||||
/// the bearing of the last point up to it that the pen leaned 1° or more at, or before the
|
||||
/// first such point the bearing of that first one. What the release does not read
|
||||
/// ([`Self::reads_pressures`], [`Self::reads_poses`]) reads ½, the values themselves.
|
||||
fn controls_of_point(&self, i: usize) -> [f64; 4] {
|
||||
let pressure = if self.reads_pressures() { self.pressures.get(i).map_or(0.5, |p| f64::from(*p)) } else { 0.5 };
|
||||
let (pose, bearing) = if self.reads_poses() {
|
||||
(self.poses.get(i).copied().flatten(), self.bearings.get(i).copied().flatten().or(self.first_bearing))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
super::pen_controls(pressure, pose, bearing)
|
||||
}
|
||||
|
||||
/// How the tip's angle, roundness and size vary: the Eraser's three modes, the Blob Brush's
|
||||
@@ -1144,12 +1224,25 @@ impl GestureTool {
|
||||
/// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a
|
||||
/// pen that gives no reading, the values themselves. The Blob Brush's are its own values.
|
||||
fn tip_now(&self) -> [f64; 3] {
|
||||
let base = [self.angle, self.roundness, self.size];
|
||||
if self.id != "eraser" || !self.active {
|
||||
return base;
|
||||
return [self.angle, self.roundness, self.size];
|
||||
}
|
||||
let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 };
|
||||
let controls = super::pen_controls(pressure, self.poses.last().copied().flatten(), self.bearing);
|
||||
self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing)
|
||||
}
|
||||
|
||||
/// The tip's angle, roundness and size for a pen at `pressure` held as `pose`, leaning toward
|
||||
/// `bearing`: each value on a mode that follows the pen goes from the value less its Variation
|
||||
/// to the value plus it ([`super::pen_controls`]); for Random, Fixed and what the pen does not
|
||||
/// give, the values themselves.
|
||||
fn tip_for(&self, pressure: f64, pose: Option<PenPose>, bearing: Option<f64>) -> [f64; 3] {
|
||||
self.tip_of_controls(super::pen_controls(pressure, pose, bearing))
|
||||
}
|
||||
|
||||
/// The tip's angle, roundness and size where the modes Pressure, Tilt, Bearing and Rotation
|
||||
/// read `controls` (0..1 each, [`super::pen_controls`]).
|
||||
fn tip_of_controls(&self, controls: [f64; 4]) -> [f64; 3] {
|
||||
let base = [self.angle, self.roundness, self.size];
|
||||
let variations = [self.angle_variation, self.roundness_variation, self.size_variation];
|
||||
let mut out = base;
|
||||
for (i, (v, mode)) in out.iter_mut().zip(self.tip_modes()).enumerate() {
|
||||
@@ -1660,31 +1753,39 @@ impl Tool for GestureTool {
|
||||
};
|
||||
let color = if self.id == "eraser" { [0x80, 0x80, 0x80] } else { FEEDBACK };
|
||||
// A tip that is not round shows the outline of the area it covers, each step of the drag
|
||||
// as wide as the pen pressed there with Size set to Pressure. So does a round Blob Brush
|
||||
// tip: a line as wide as the brush would end square, where the stroke it adds is round at
|
||||
// both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]).
|
||||
if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || self.id == "blobBrush") && !self.smoothing {
|
||||
let pressures = self.size_pressures();
|
||||
// with the tip the pen gives there on the modes that follow the pen. So does a round Blob
|
||||
// Brush tip: a line as wide as the brush would end square, where the stroke it adds is
|
||||
// round at both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]).
|
||||
let [angle_varies, roundness_varies, size_varies] = self.tip_varies();
|
||||
// An angle varies the tip only when it is not round.
|
||||
let shaped = roundness_varies || (angle_varies && self.roundness < 100.0);
|
||||
if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || shaped || self.id == "blobBrush") && !self.smoothing {
|
||||
let key = AreaKey {
|
||||
blob: self.id == "blobBrush",
|
||||
size: self.size,
|
||||
variation: self.size_variation,
|
||||
variation: if size_varies { self.size_variation } else { 0.0 },
|
||||
angle: self.angle,
|
||||
roundness: self.roundness,
|
||||
pressure: pressures.is_some(),
|
||||
varies: shaped || size_varies,
|
||||
shaped,
|
||||
pressed: self.reads_pressures() && self.tip_modes().contains(&Variation::Pressure),
|
||||
first_bearing: self.first_bearing.filter(|_| self.reads_poses() && self.tip_modes().contains(&Variation::Bearing)),
|
||||
modes: self.tip_modes(),
|
||||
variations: [self.angle_variation, self.roundness_variation, self.size_variation],
|
||||
};
|
||||
let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0]));
|
||||
area.step(&self.points, pressures);
|
||||
let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }];
|
||||
area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j)));
|
||||
let paths = area.paths(&self.points);
|
||||
o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 }));
|
||||
o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false }));
|
||||
self.area_pending.set(area.pending(&self.points));
|
||||
self.area.set(Some(area));
|
||||
} else if let Some(pressures) = self.size_pressures() {
|
||||
// With Size set to Pressure, each step of the drag shows as wide as the pen pressed there.
|
||||
for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) {
|
||||
let pressure = f64::from(p[0] + p[1]) / 2.0;
|
||||
let width = super::pressure_size(self.size, self.size_variation, pressure) * cx.zoom;
|
||||
} else if size_varies {
|
||||
// With Size on a mode that follows the pen, each step of the drag shows as wide as the
|
||||
// tip the pen gives at its ends.
|
||||
for (j, seg) in self.points.windows(2).enumerate() {
|
||||
let width = (self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom;
|
||||
o.push(Overlay::Path { path: polyline(seg), color, width: width as f32, dashed: false });
|
||||
}
|
||||
} else {
|
||||
|
||||
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user