mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 08:52:45 +01:00
Merge main into feat/font-menu-show-similar
This commit is contained in:
commit
3d5a8afdbb
151 files changed
+8228
-776
No files matched your search
Generated
+10
-1
@@ -1016,6 +1016,14 @@ name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
@@ -1212,7 +1220,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -6741,6 +6749,7 @@ dependencies = [
|
||||
name = "vectorcraft-format"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-gzip",
|
||||
"craft-vectorcraft-format",
|
||||
"flate2",
|
||||
"proptest",
|
||||
|
||||
+2
-1
@@ -21,7 +21,8 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
|
||||
|
||||
| | Value | Kind |
|
||||
|---|---|---|
|
||||
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
|
||||
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
|
||||
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
|
||||
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
|
||||
| **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated |
|
||||
|
||||
@@ -238,10 +238,11 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_metadata_templates_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
prefs_dir::attach_profile_store(&mut h.session);
|
||||
prefs_dir::attach_color_settings(&mut h.session);
|
||||
|
||||
@@ -163,6 +163,10 @@ fn takes_files(mimes: &[&'static str]) -> bool {
|
||||
|
||||
/// [`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> {
|
||||
// A list of more than MAX_URIS files (untrusted data) names none, before any file is looked at.
|
||||
if paths.len() > MAX_URIS {
|
||||
return None;
|
||||
}
|
||||
paths.into_iter().find_map(|path| {
|
||||
// text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only.
|
||||
let path = match path.to_str() {
|
||||
@@ -203,6 +207,53 @@ fn read_rest(file: impl Read, mut data: Vec<u8>, limit: usize) -> Option<Vec<u8>
|
||||
(data.len() <= limit).then_some(data)
|
||||
}
|
||||
|
||||
/// The data `copy` takes off the clipboard, called only when `size` (what the clipboard reports
|
||||
/// before the copy) is known and from 1 to `limit` bytes. `None` without a call otherwise, and
|
||||
/// when the copy comes to more than `limit` bytes.
|
||||
#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
|
||||
fn copy_within(size: Option<usize>, limit: usize, copy: impl FnOnce() -> Option<Vec<u8>>) -> Option<Vec<u8>> {
|
||||
size.filter(|&n| n > 0 && n <= limit)?;
|
||||
copy().filter(|data| data.len() <= limit)
|
||||
}
|
||||
|
||||
/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at
|
||||
/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn utf8_most(utf16: usize) -> usize {
|
||||
utf16.div_ceil(2).saturating_mul(3)
|
||||
}
|
||||
|
||||
/// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a
|
||||
/// NUL and the list by one more, in UTF-16 when the header's `fWide` is set) names at most `limit`
|
||||
/// files. Counting stops at the first name past `limit`. A block too short for its header, or
|
||||
/// whose names would start past its end, is not within.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn drop_files_within(block: &[u8], limit: usize) -> bool {
|
||||
let field = |at: usize| Some(u32::from_le_bytes(block.get(at..at.checked_add(4)?)?.try_into().ok()?));
|
||||
let (Some(start), Some(wide)) = (field(0), field(16)) else {
|
||||
return false;
|
||||
};
|
||||
let Some(names) = usize::try_from(start).ok().and_then(|start| block.get(start..)) else {
|
||||
return false;
|
||||
};
|
||||
let (mut count, mut in_name) = (0usize, false);
|
||||
for unit in names.chunks_exact(if wide != 0 { 2 } else { 1 }) {
|
||||
if unit.iter().all(|&b| b == 0) {
|
||||
if !in_name {
|
||||
break;
|
||||
}
|
||||
in_name = false;
|
||||
} else if !in_name {
|
||||
in_name = true;
|
||||
count += 1;
|
||||
if count > limit {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted
|
||||
/// data) names no files.
|
||||
const MAX_URIS: usize = 1024;
|
||||
@@ -284,12 +335,13 @@ fn file_uri_path(uri: &str) -> Option<PathBuf> {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod win {
|
||||
use std::num::NonZeroU32;
|
||||
use std::num::{NonZeroU32, NonZeroUsize};
|
||||
|
||||
use clipboard_win::{formats, options::NoClear, raw};
|
||||
|
||||
use super::{
|
||||
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats,
|
||||
BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png,
|
||||
dib_image, drop_files_within, png_flavour, utf8_most, windows_formats,
|
||||
};
|
||||
|
||||
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
|
||||
@@ -376,8 +428,11 @@ mod win {
|
||||
let mut files = vec![];
|
||||
{
|
||||
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
|
||||
// None copied when the clipboard holds no file list.
|
||||
let _ = raw::get_file_list_path(&mut files);
|
||||
// None copied when the clipboard holds no file list, or one of more than MAX_BYTES
|
||||
// or MAX_URIS files: the list is counted before its names are copied.
|
||||
if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) {
|
||||
let _ = raw::get_file_list_path(&mut files);
|
||||
}
|
||||
}
|
||||
// The files are read with the clipboard closed again, not keeping other apps waiting.
|
||||
copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| {
|
||||
@@ -396,44 +451,64 @@ mod win {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the first registered format of `mime` the clipboard holds into `data`.
|
||||
fn read_registered(mime: &str, data: &mut Vec<u8>) -> bool {
|
||||
formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| {
|
||||
data.clear();
|
||||
raw::get_vec(id, data).is_ok() && !data.is_empty()
|
||||
/// The size the clipboard reports for format `id`, while it is open.
|
||||
fn size_of(id: u32) -> Option<usize> {
|
||||
raw::size(id).map(NonZeroUsize::get)
|
||||
}
|
||||
|
||||
/// The data of format `id`, while the clipboard is open, copied only when its size is at most
|
||||
/// `limit` bytes ([`copy_within`]).
|
||||
fn copy_registered(id: u32, limit: usize) -> Option<Vec<u8>> {
|
||||
copy_within(size_of(id), limit, || {
|
||||
let mut data = vec![];
|
||||
raw::get_vec(id, &mut data).ok()?;
|
||||
Some(data)
|
||||
})
|
||||
}
|
||||
|
||||
/// The first registered format of `mime` the clipboard holds that is not empty and at most
|
||||
/// [`MAX_BYTES`]; a larger one is skipped and the next tried.
|
||||
fn read_registered(mime: &str) -> Option<Vec<u8>> {
|
||||
formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty()))
|
||||
}
|
||||
|
||||
/// A device-independent bitmap as a PNG flavour.
|
||||
fn dib_png(dib: &[u8]) -> Option<Flavour> {
|
||||
png_flavour(&dib_image(dib)?)
|
||||
}
|
||||
|
||||
/// Copy both bitmap formats while the clipboard is open, then decode them in preference order.
|
||||
pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
|
||||
let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect();
|
||||
/// `size` gives each format's size before `get` copies it, and a format of more than
|
||||
/// [`MAX_BYTES`] is not copied ([`copy_within`]) and the next one is tried.
|
||||
pub(super) fn read_dibs(mut size: impl FnMut(u32) -> Option<usize>, mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
|
||||
let dibs: Vec<_> = DIBS.into_iter().filter_map(|id| copy_within(size(id), MAX_BYTES, || get(id))).collect();
|
||||
(!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib)))))
|
||||
}
|
||||
|
||||
/// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and
|
||||
/// the work that comes back decodes each captured format in preference order.
|
||||
/// the work that comes back decodes each captured format in preference order. Text whose
|
||||
/// UTF-16 block could come to more than [`MAX_BYTES`] as UTF-8 ([`utf8_most`]) is not read.
|
||||
fn read_one(mime: &'static str) -> Option<ClipboardRead> {
|
||||
let mut data = vec![];
|
||||
let mime = match mime {
|
||||
BITMAP if read_registered(PNG, &mut data) => PNG,
|
||||
BITMAP => {
|
||||
return read_dibs(|id| {
|
||||
let mut dib = vec![];
|
||||
raw::get_vec(id, &mut dib).ok()?;
|
||||
Some(dib)
|
||||
});
|
||||
}
|
||||
let (mime, mut data) = match mime {
|
||||
BITMAP => match read_registered(PNG) {
|
||||
Some(png) => (PNG, png),
|
||||
None => {
|
||||
return read_dibs(size_of, |id| {
|
||||
let mut dib = vec![];
|
||||
raw::get_vec(id, &mut dib).ok()?;
|
||||
Some(dib)
|
||||
});
|
||||
}
|
||||
},
|
||||
TEXT => {
|
||||
raw::get_string(&mut data).ok()?;
|
||||
TEXT
|
||||
let text = copy_within(size_of(formats::CF_UNICODETEXT).map(utf8_most), MAX_BYTES, || {
|
||||
let mut text = vec![];
|
||||
raw::get_string(&mut text).ok()?;
|
||||
Some(text)
|
||||
})?;
|
||||
(TEXT, text)
|
||||
}
|
||||
m if read_registered(m, &mut data) => m,
|
||||
_ => return None,
|
||||
m => (m, read_registered(m)?),
|
||||
};
|
||||
// Memory blocks can be longer than the data: SVG text ends at its first NUL.
|
||||
if mime == SVG
|
||||
@@ -3141,7 +3216,7 @@ mod mac {
|
||||
use objc2_app_kit::NSPasteboard;
|
||||
use objc2_foundation::{NSArray, NSString};
|
||||
|
||||
use super::{Flavour, pasteboard_types};
|
||||
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
|
||||
|
||||
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
|
||||
pub fn has(mimes: &[&'static str]) -> bool {
|
||||
@@ -3152,13 +3227,16 @@ mod mac {
|
||||
})
|
||||
}
|
||||
|
||||
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]).
|
||||
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is
|
||||
/// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger
|
||||
/// type is skipped and the next tried.
|
||||
pub fn read(mime: &str) -> Option<Flavour> {
|
||||
autoreleasepool(|_| {
|
||||
let pasteboard = NSPasteboard::generalPasteboard();
|
||||
pasteboard_types(mime).iter().find_map(|&(t, mime)| {
|
||||
let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec();
|
||||
(!data.is_empty()).then_some(Flavour { mime, data })
|
||||
let held = pasteboard.dataForType(&NSString::from_str(t))?;
|
||||
let data = copy_within(Some(held.len()), MAX_BYTES, || Some(held.to_vec()))?;
|
||||
Some(Flavour { mime, data })
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -3345,6 +3423,102 @@ mod tests {
|
||||
assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty());
|
||||
}
|
||||
|
||||
/// A copied file list of more than 1,024 files pastes none, before any file is looked at,
|
||||
/// wherever the list came from; 1,024 files paste the first that is art.
|
||||
#[test]
|
||||
fn a_copied_file_list_longer_than_the_limit_pastes_no_file() {
|
||||
let d = dir("many");
|
||||
let art = d.path().join("art.svg");
|
||||
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
|
||||
let missing = |n: usize| (0..n).map(|i| d.path().join(format!("gone{i}.png"))).collect::<Vec<_>>();
|
||||
let last = [missing(MAX_URIS - 1), vec![art.clone()]].concat();
|
||||
assert_eq!(copied_file(last, &PASTE_ORDER).map(|f| f.mime), Some(SVG));
|
||||
// The art first: no file is opened past the count.
|
||||
let first = [vec![art.clone()], missing(MAX_URIS)].concat();
|
||||
assert!(copied_file(first, &PASTE_ORDER).is_none());
|
||||
assert!(copied_file([missing(MAX_URIS), vec![art]].concat(), &PASTE_ORDER).is_none());
|
||||
}
|
||||
|
||||
/// Clipboard data is copied only when the size the clipboard gives is from 1 byte to the limit,
|
||||
/// and the copy is not asked for otherwise.
|
||||
#[test]
|
||||
fn clipboard_data_is_copied_only_when_its_size_fits() {
|
||||
let copy = |size: Option<usize>, got: usize| {
|
||||
let mut asked = false;
|
||||
let data = copy_within(size, 8, || {
|
||||
asked = true;
|
||||
Some(vec![1; got])
|
||||
});
|
||||
(data.map(|d| d.len()), asked)
|
||||
};
|
||||
assert_eq!(copy(Some(8), 8), (Some(8), true));
|
||||
assert_eq!(copy(Some(1), 1), (Some(1), true));
|
||||
for size in [None, Some(0), Some(9), Some(usize::MAX)] {
|
||||
assert_eq!(copy(size, 1), (None, false), "{size:?}");
|
||||
}
|
||||
// Data that comes to more than the limit after all is refused.
|
||||
assert_eq!(copy(Some(8), 9), (None, true));
|
||||
assert_eq!(MAX_BYTES, 64 << 20);
|
||||
}
|
||||
|
||||
/// The UTF-8 that UTF-16 text comes to is bounded from the UTF-16 block's size alone, before
|
||||
/// the text is converted: a block that could pass the limit as UTF-8 is not read.
|
||||
#[test]
|
||||
fn text_is_bounded_by_what_its_utf8_could_come_to() {
|
||||
for text in ["", "a", "\u{20ac}\u{20ac}\u{20ac}", "\u{1f600}", "a\u{20ac}\u{1f600}\u{ffff}"] {
|
||||
let utf16 = text.encode_utf16().count() * 2;
|
||||
assert!(utf8_most(utf16) >= text.len(), "{text:?}");
|
||||
}
|
||||
// Every code unit at 3 bytes of UTF-8: the bound is exact.
|
||||
assert_eq!(utf8_most("\u{20ac}\u{20ac}".encode_utf16().count() * 2), "\u{20ac}\u{20ac}".len());
|
||||
let copied = |utf16: usize| copy_within(Some(utf8_most(utf16)), MAX_BYTES, || Some(vec![])).is_some();
|
||||
assert!(copied(MAX_BYTES / 3 * 2));
|
||||
assert!(!copied(MAX_BYTES / 3 * 2 + 2));
|
||||
assert!(!copied(MAX_BYTES));
|
||||
assert_eq!(utf8_most(usize::MAX), usize::MAX);
|
||||
}
|
||||
|
||||
/// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one
|
||||
/// byte a character, each ended by a NUL, and one more NUL.
|
||||
fn drop_files(names: &[&str], wide: bool) -> Vec<u8> {
|
||||
let mut block = vec![];
|
||||
block.extend(20u32.to_le_bytes());
|
||||
block.extend([0u8; 12]);
|
||||
block.extend(u32::from(wide).to_le_bytes());
|
||||
for name in names.iter().copied().chain([""]) {
|
||||
for unit in name.encode_utf16().chain([0]) {
|
||||
if wide {
|
||||
block.extend(unit.to_le_bytes());
|
||||
} else {
|
||||
block.push(unit as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
block
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windows_file_list_is_counted_before_its_names_are_read() {
|
||||
let names = |n: usize| (0..n).map(|i| format!("C:\\art\\{i}.svg")).collect::<Vec<_>>();
|
||||
for wide in [true, false] {
|
||||
let list = |n: usize| drop_files(&names(n).iter().map(String::as_str).collect::<Vec<_>>(), wide);
|
||||
assert!(drop_files_within(&list(MAX_URIS), MAX_URIS), "{wide}");
|
||||
assert!(!drop_files_within(&list(MAX_URIS + 1), MAX_URIS), "{wide}");
|
||||
assert!(drop_files_within(&list(0), MAX_URIS), "{wide}");
|
||||
// Names past the list's closing NUL are not counted.
|
||||
let mut ended = list(2);
|
||||
ended.extend(list(MAX_URIS + 1).get(20..).unwrap());
|
||||
assert!(drop_files_within(&ended, 2), "{wide}");
|
||||
// A list cut short counts the names it holds.
|
||||
assert!(!drop_files_within(&list(3)[..list(3).len() - 4], 2), "{wide}");
|
||||
}
|
||||
// A header cut short, or names that would start past the block's end.
|
||||
assert!(!drop_files_within(&drop_files(&["a"], true)[..19], MAX_URIS));
|
||||
let mut past = drop_files(&["a"], true);
|
||||
past[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert!(!drop_files_within(&past, MAX_URIS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gnome_files_list_names_its_files_after_copy_or_cut() {
|
||||
let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>();
|
||||
@@ -3398,19 +3572,48 @@ mod tests {
|
||||
|
||||
let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED]));
|
||||
let mut captured = Vec::new();
|
||||
let read = win::read_dibs(|id| {
|
||||
captured.push(id);
|
||||
match id {
|
||||
CF_DIBV5 => Some(vec![40, 0, 0]),
|
||||
CF_DIB => Some(valid.clone()),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
let get = |id: u32| match id {
|
||||
CF_DIBV5 => Some(vec![40, 0, 0]),
|
||||
CF_DIB => Some(valid.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let read = win::read_dibs(
|
||||
|id| get(id).map(|d| d.len()),
|
||||
|id| {
|
||||
captured.push(id);
|
||||
get(id)
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
|
||||
let flavour = read.flavour().unwrap();
|
||||
assert_eq!(flavour.mime, PNG);
|
||||
assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]);
|
||||
// A bitmap larger than the limit is not copied, and the other one still pastes.
|
||||
captured.clear();
|
||||
let read = win::read_dibs(
|
||||
|id| if id == CF_DIBV5 { Some(MAX_BYTES + 1) } else { get(id).map(|d| d.len()) },
|
||||
|id| {
|
||||
captured.push(id);
|
||||
get(id)
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(captured, [CF_DIB]);
|
||||
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
|
||||
// Each format has the limit to itself: a first one at the limit that doesn't decode
|
||||
// leaves the second to paste.
|
||||
captured.clear();
|
||||
let read = win::read_dibs(
|
||||
|id| if id == CF_DIBV5 { Some(MAX_BYTES) } else { get(id).map(|d| d.len()) },
|
||||
|id| {
|
||||
captured.push(id);
|
||||
get(id)
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
|
||||
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -535,6 +535,8 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
|
||||
prefs_dir::attach_scripts_dir(&mut session);
|
||||
// File Info's metadata templates live in their own folder next to the preferences.
|
||||
prefs_dir::attach_metadata_templates_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
|
||||
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
|
||||
/// makes.
|
||||
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Metadata Templates") {
|
||||
session.attach_metadata_templates_dir(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Have File › New start each category's documents from its profile in the `New Document
|
||||
/// Profiles` folder, which `file.newProfiles.edit` makes.
|
||||
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -28,6 +28,7 @@ pub mod shared;
|
||||
mod symbol_export_type;
|
||||
mod symbol_nine_slice;
|
||||
pub mod symbol_overrides;
|
||||
mod symbol_pixel_aligned;
|
||||
mod symbol_registration;
|
||||
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
|
||||
pub use shared::Shared;
|
||||
@@ -37,6 +38,7 @@ pub use symbol_nine_slice::{
|
||||
SymbolNineSlice, charge_symbol_art,
|
||||
};
|
||||
pub use symbol_overrides::SymbolOverride;
|
||||
pub use symbol_pixel_aligned::SYMBOL_PIXEL_ALIGNED;
|
||||
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
|
||||
pub mod links;
|
||||
pub mod live;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Symbol Options › Align to Pixel Grid: a symbol whose instances stay on the pixel grid at their
|
||||
//! actual size wherever they are placed
|
||||
//! (<https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28>).
|
||||
//!
|
||||
//! Stored under [`SYMBOL_PIXEL_ALIGNED`] keyed by symbol name; a symbol that is not pixel-aligned
|
||||
//! (the default) is left out of the map.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::Document;
|
||||
|
||||
/// Document unknown key: `{ symbolName: true }` for each pixel-aligned symbol.
|
||||
pub const SYMBOL_PIXEL_ALIGNED: &str = "symbolPixelAligned";
|
||||
|
||||
impl Document {
|
||||
/// Whether symbol `name` has Symbol Options › Align to Pixel Grid on (default: off).
|
||||
pub fn symbol_pixel_aligned(&self, name: &str) -> bool {
|
||||
self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.get(name)).and_then(serde_json::Value::as_bool).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Turn Align to Pixel Grid on or off for symbol `name`. Off removes the symbol from the map,
|
||||
/// and the map goes when it is empty.
|
||||
pub fn set_symbol_pixel_aligned(&mut self, name: &str, on: bool) {
|
||||
if on {
|
||||
let m = self.unknown.entry(SYMBOL_PIXEL_ALIGNED.to_string()).or_insert_with(|| serde_json::json!({}));
|
||||
if let Some(o) = m.as_object_mut() {
|
||||
o.insert(name.into(), serde_json::json!(true));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(o) = self.unknown.get_mut(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object_mut()) else { return };
|
||||
o.remove(name);
|
||||
if o.is_empty() {
|
||||
self.unknown.remove(SYMBOL_PIXEL_ALIGNED);
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the stored setting when a symbol is renamed.
|
||||
pub fn rename_symbol_pixel_aligned(&mut self, from: &str, to: &str) {
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
let on = self.symbol_pixel_aligned(from);
|
||||
self.set_symbol_pixel_aligned(from, false);
|
||||
self.set_symbol_pixel_aligned(to, on);
|
||||
}
|
||||
|
||||
/// The names of the pixel-aligned symbols the document holds (empty for most documents).
|
||||
pub fn pixel_aligned_symbols(&self) -> HashSet<String> {
|
||||
let Some(o) = self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object()) else { return HashSet::new() };
|
||||
o.iter()
|
||||
.filter(|(name, v)| v.as_bool() == Some(true) && self.symbols.iter().any(|s| &s.name == *name))
|
||||
.map(|(name, _)| name.clone())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_setting_is_off_by_default_and_follows_a_rename() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let art = std::sync::Arc::new(crate::Node::group(d.alloc_id(), vec![]));
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "A".into(), art });
|
||||
assert!(!d.symbol_pixel_aligned("A"));
|
||||
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
|
||||
d.set_symbol_pixel_aligned("A", true);
|
||||
assert!(d.symbol_pixel_aligned("A"));
|
||||
assert_eq!(d.pixel_aligned_symbols(), HashSet::from(["A".to_string()]));
|
||||
d.symbols[0].name = "B".into();
|
||||
d.rename_symbol_pixel_aligned("A", "B");
|
||||
assert!(!d.symbol_pixel_aligned("A"));
|
||||
assert!(d.symbol_pixel_aligned("B"));
|
||||
d.set_symbol_pixel_aligned("B", false);
|
||||
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
|
||||
assert!(d.pixel_aligned_symbols().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
|
||||
TabStop,
|
||||
};
|
||||
pub use wrap::{resolve_wrap, wrap_work};
|
||||
pub use wrap::{resolve_wrap, wrap_sources, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
|
||||
+58
-34
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{PathData, shapes};
|
||||
|
||||
use super::{TextKind, WrapShape};
|
||||
use super::{TextKind, TextObject, WrapShape};
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
|
||||
@@ -82,6 +82,57 @@ pub fn wrap_work(doc: &Document) -> usize {
|
||||
total
|
||||
}
|
||||
|
||||
/// Each area text object of `layer`, from the top down, with the wrap objects above it in the
|
||||
/// layer whose outlines aren't empty, topmost first, each with the shape its outline makes in
|
||||
/// document coordinates. Each wrap object's outline is made once.
|
||||
fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapShape)])) {
|
||||
let mut items = vec![];
|
||||
collect(layer, &mut items);
|
||||
let mut above: Vec<(&Node, WrapShape)> = vec![];
|
||||
for it in items.iter().rev() {
|
||||
match it {
|
||||
Item::Wrap(n) => {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
above.push((n, WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() }));
|
||||
}
|
||||
}
|
||||
Item::Text(n) => f(n, &above),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wrap shapes of text object `t` (text space) from `above`, the wrap objects above it as
|
||||
/// [`each_text`] gives them: bottom first.
|
||||
fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec<WrapShape> {
|
||||
let inv = t.xf.inverse();
|
||||
above
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(_, s)| {
|
||||
let mut path = s.path.clone();
|
||||
path.transform(inv);
|
||||
WrapShape { path, wrap: s.wrap }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each area text object on `doc`'s layers that [`resolve_wrap`] gives wrap shapes, with the wrap
|
||||
/// objects whose outlines make them, bottom first, and those shapes (text space), as
|
||||
/// [`resolve_wrap`] works them out. The copying is [`wrap_work`].
|
||||
pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>, Vec<WrapShape>)) {
|
||||
for layer in &doc.layers {
|
||||
each_text(layer, |n, above| {
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& !above.is_empty()
|
||||
{
|
||||
f(n, above.iter().rev().map(|(s, _)| *s).collect(), shapes_of(t, above));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the
|
||||
/// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged
|
||||
/// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes
|
||||
@@ -95,41 +146,14 @@ pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec<NodeId
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut items = vec![];
|
||||
collect(layer, &mut items);
|
||||
if items.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// From the top down, each wrap object's outline is made once; each area text object takes
|
||||
// those above it, bottom first.
|
||||
let mut above: Vec<WrapShape> = vec![];
|
||||
for it in items.iter().rev() {
|
||||
match it {
|
||||
Item::Wrap(n) => {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() });
|
||||
}
|
||||
}
|
||||
Item::Text(n) => {
|
||||
let NodeKind::Text(t) = &n.kind else { continue };
|
||||
let inv = t.xf.inverse();
|
||||
let shapes: Vec<WrapShape> = above
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|s| {
|
||||
let mut path = s.path.clone();
|
||||
path.transform(inv);
|
||||
WrapShape { path, wrap: s.wrap }
|
||||
})
|
||||
.collect();
|
||||
if shapes != t.wrap {
|
||||
updates.push((n.id, shapes));
|
||||
}
|
||||
each_text(layer, |n, above| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
let shapes = shapes_of(t, above);
|
||||
if shapes != t.wrap {
|
||||
updates.push((n.id, shapes));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut changed = Vec::with_capacity(updates.len());
|
||||
for (id, shapes) in updates {
|
||||
|
||||
@@ -367,9 +367,14 @@ fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineH
|
||||
fn styled(src: &Node, path: PathData, outline: bool) -> Node {
|
||||
let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() };
|
||||
if outline {
|
||||
let fill = src.appearance.fill_paint();
|
||||
let paint = if fill.is_none() { src.appearance.stroke_paint() } else { fill };
|
||||
appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(paint, 1.0))], ..Default::default() };
|
||||
// The edges take the paint, opacity, blend mode and overprint of the top fill that paints,
|
||||
// or of the top stroke that paints when no fill does.
|
||||
let layer = top_painting_fill(&src.appearance).or_else(|| src.appearance.items.iter().rev().find(|i| paints(i)));
|
||||
let mut stroke = StrokeLayer::new(layer.map_or(Paint::None, |i| i.paint().clone()), 1.0);
|
||||
if let Some(i) = layer {
|
||||
(stroke.opacity, stroke.blend, stroke.overprint) = (i.opacity(), i.blend(), i.overprint());
|
||||
}
|
||||
appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() };
|
||||
}
|
||||
let mut n = Node::path(src.id, path, appearance);
|
||||
n.opacity = src.opacity;
|
||||
@@ -504,7 +509,8 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
.iter()
|
||||
.filter_map(|l| {
|
||||
let (path, rule) = geometry(l)?;
|
||||
Some((l.id, crate::trap::TrapSource { path, rule, fill: l.appearance.fill_paint() }))
|
||||
let fill = top_painting_fill(&l.appearance).map_or(Paint::None, |i| i.paint().clone());
|
||||
Some((l.id, crate::trap::TrapSource { path, rule, fill }))
|
||||
})
|
||||
.unzip();
|
||||
let made = crate::trap::traps(&srcs, &crate::trap::TrapOptions::from_params(&e.params));
|
||||
@@ -580,7 +586,8 @@ fn mixing_rate(params: &Value) -> f64 {
|
||||
}
|
||||
|
||||
fn fill_cmyk(src: &Node) -> Option<[f32; 4]> {
|
||||
let paint = src.appearance.fill_paint();
|
||||
// The top fill that paints: a hidden fill adds no color.
|
||||
let paint = top_painting_fill(&src.appearance)?.paint().clone();
|
||||
let color = paint.color()?;
|
||||
let tinted = match paint {
|
||||
Paint::Solid { tint, .. } => color.tinted(tint),
|
||||
@@ -637,6 +644,11 @@ fn is_container(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// The top fill of `a` that paints: hidden fills and fills of no paint are skipped.
|
||||
fn top_painting_fill(a: &Appearance) -> Option<&AppearanceItem> {
|
||||
a.items.iter().rev().find(|i| i.is_fill() && paints(i))
|
||||
}
|
||||
|
||||
/// Does `item` paint anything?
|
||||
pub fn paints(item: &AppearanceItem) -> bool {
|
||||
item.visible()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject};
|
||||
use vectorcraft_doc::{CharStyle, Effect, FillLayer, NodeId, TextObject};
|
||||
use vectorcraft_geom::{Point, Rect, shapes};
|
||||
|
||||
/// Type tests need glyph outlines, which only the optional craft-fonts build input provides.
|
||||
@@ -71,6 +71,33 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() {
|
||||
assert_eq!(fill.paint.color(), Some(yellow));
|
||||
}
|
||||
|
||||
/// Trap takes each member's top fill that paints: a hidden fill on top is skipped, and a member
|
||||
/// whose only fill is hidden does not take part.
|
||||
#[test]
|
||||
fn trap_skips_a_hidden_fill() {
|
||||
let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0);
|
||||
let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0);
|
||||
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
hidden.visible = false;
|
||||
let trap = |members: Vec<Arc<Node>>| {
|
||||
let mut g = Node::group(NodeId(10), members);
|
||||
let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100});
|
||||
g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true });
|
||||
pathfinder_children(None, &g, None).unwrap()
|
||||
};
|
||||
let mut covered = (*sq(1, 0.0, yellow)).clone();
|
||||
covered.appearance.items.push(AppearanceItem::Fill(hidden.clone()));
|
||||
let out = trap(vec![Arc::new(covered), sq(2, 10.0, blue)]);
|
||||
assert_eq!(out.len(), 3, "both squares and one trap");
|
||||
assert_eq!(out[2].appearance.fill().unwrap().paint.color(), Some(yellow));
|
||||
let only_hidden = Node::path(
|
||||
NodeId(1),
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)),
|
||||
Appearance { items: vec![AppearanceItem::Fill(hidden)], ..Default::default() },
|
||||
);
|
||||
assert_eq!(trap(vec![Arc::new(only_hidden), sq(2, 10.0, blue)]).len(), 2, "no trap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() {
|
||||
let mut g = two_overlapping_cmyk_squares();
|
||||
@@ -87,6 +114,72 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() {
|
||||
assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}");
|
||||
}
|
||||
|
||||
/// Soft Mix and Hard Mix mix the top fill that paints: a hidden fill above it adds no color.
|
||||
#[test]
|
||||
fn mixes_skip_a_hidden_fill() {
|
||||
for effect in ["pathfinder.softMix", "pathfinder.hardMix"] {
|
||||
let mut plain = two_overlapping_cmyk_squares();
|
||||
plain.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true });
|
||||
let mut covered = plain.clone();
|
||||
let NodeKind::Group { children, .. } = &mut covered.kind else { panic!("group") };
|
||||
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
hidden.visible = false;
|
||||
for c in children.iter_mut() {
|
||||
Arc::make_mut(c).appearance.items.push(AppearanceItem::Fill(hidden.clone()));
|
||||
}
|
||||
assert_eq!(overlap_cmyk(&covered), overlap_cmyk(&plain), "{effect}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline strokes each edge with the top fill that paints, keeping that fill's opacity, blend
|
||||
/// mode and overprint. A hidden fill or a fill of no paint gives the edges nothing; with no fill
|
||||
/// that paints, the edges take the top stroke that paints, which skips hidden and 0 pt strokes.
|
||||
#[test]
|
||||
fn outline_edges_keep_the_fill_layers_opacity_blend_and_overprint() {
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
let mut fill = FillLayer::new(red.clone());
|
||||
(fill.opacity, fill.blend, fill.overprint) = (0.5, BlendMode::Multiply, true);
|
||||
let mut hidden = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
hidden.visible = false;
|
||||
let mut stroke = StrokeLayer::new(blue.clone(), 2.0);
|
||||
(stroke.opacity, stroke.blend, stroke.overprint) = (0.5, BlendMode::Multiply, true);
|
||||
let mut hidden_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 2.0);
|
||||
hidden_stroke.visible = false;
|
||||
let zero_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 0.0);
|
||||
let look = |items: Vec<AppearanceItem>| Appearance { items, ..Default::default() };
|
||||
let (f, s) = (AppearanceItem::Fill, AppearanceItem::Stroke);
|
||||
let cases = [
|
||||
(look(vec![f(fill.clone())]), Some(red.clone())),
|
||||
(look(vec![f(fill.clone()), f(hidden.clone())]), Some(red.clone())),
|
||||
(look(vec![f(fill.clone()), f(FillLayer::new(Paint::None))]), Some(red.clone())),
|
||||
(look(vec![f(hidden.clone())]), None),
|
||||
(look(vec![s(stroke.clone())]), Some(blue.clone())),
|
||||
(look(vec![f(hidden.clone()), s(stroke.clone())]), Some(blue.clone())),
|
||||
(look(vec![s(stroke.clone()), s(hidden_stroke), s(zero_stroke.clone())]), Some(blue.clone())),
|
||||
(look(vec![s(zero_stroke)]), None),
|
||||
];
|
||||
for (appearance, want) in cases {
|
||||
let member = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), appearance));
|
||||
let mut g = Node::group(NodeId(10), vec![member, sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]);
|
||||
g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({}), visible: true });
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
let edges: Vec<_> = out.iter().filter(|n| n.id == NodeId(1)).collect();
|
||||
assert!(!edges.is_empty(), "{out:#?}");
|
||||
for n in edges {
|
||||
let [AppearanceItem::Stroke(s)] = n.appearance.items.as_slice() else { panic!("one stroke: {n:#?}") };
|
||||
match &want {
|
||||
Some(paint) => {
|
||||
assert_eq!(&s.paint, paint);
|
||||
assert_eq!((s.opacity, s.blend, s.overprint), (0.5, BlendMode::Multiply, true), "{s:#?}");
|
||||
}
|
||||
None => assert!(s.paint.is_none() && s.opacity == 1.0, "{s:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_modes_follow_the_pathfinder_panel() {
|
||||
let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -625,7 +625,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);
|
||||
@@ -634,7 +636,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()
|
||||
@@ -671,6 +673,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.
|
||||
|
||||
@@ -231,14 +231,15 @@ 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`]).
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
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;
|
||||
let children = facets
|
||||
.into_iter()
|
||||
|
||||
@@ -1960,6 +1960,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
|
||||
|
||||
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbols",
|
||||
[],
|
||||
None,
|
||||
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}",
|
||||
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic, alignToPixelGrid: bool}], current}",
|
||||
has_doc,
|
||||
symbol_list
|
||||
),
|
||||
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Symbol…",
|
||||
[],
|
||||
None,
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_selection,
|
||||
symbol_new
|
||||
),
|
||||
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Options…",
|
||||
[],
|
||||
None,
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_doc,
|
||||
symbol_options
|
||||
),
|
||||
|
||||
@@ -69,6 +69,15 @@ fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> R
|
||||
})
|
||||
}
|
||||
|
||||
/// `alignToPixelGrid` (Symbol Options › Align to Pixel Grid): `None` when it is not given; any
|
||||
/// value other than true or false, null included, is an error.
|
||||
fn pixel_grid_param(p: &Value, cmd: &str) -> Result<Option<bool>> {
|
||||
match p.get("alignToPixelGrid") {
|
||||
None => Ok(None),
|
||||
Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, "alignToPixelGrid must be true or false")),
|
||||
}
|
||||
}
|
||||
|
||||
fn nine_slice_json(d: &Document, name: &str) -> Value {
|
||||
d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value)
|
||||
}
|
||||
@@ -187,6 +196,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"exportType": d.symbol_export_type(&sym.name).id(),
|
||||
"nineSlice": nine_slice_json(d, &sym.name),
|
||||
"type": type_id(sym.dynamic),
|
||||
"alignToPixelGrid": d.symbol_pixel_aligned(&sym.name),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -239,6 +249,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let export = export_type_param(p, C)?.unwrap_or_default();
|
||||
let nine = nine_slice_param(p, C, None)?.flatten();
|
||||
let dynamic = type_param(p, C)?.unwrap_or(false);
|
||||
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
|
||||
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
|
||||
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
|
||||
let id = s.edit("New Symbol", |d, sel| {
|
||||
@@ -249,6 +260,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_registration(&name, reg);
|
||||
d.set_symbol_export_type(&name, export);
|
||||
d.set_symbol_nine_slice(&name, nine);
|
||||
d.set_symbol_pixel_aligned(&name, pixel);
|
||||
let id = instance_in_place(d, &ids, &name, place)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
@@ -260,6 +272,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"exportType": export.id(),
|
||||
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
|
||||
"type": type_id(dynamic),
|
||||
"alignToPixelGrid": pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -270,9 +283,15 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reg = registration_param(p, C)?;
|
||||
let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?;
|
||||
let dynamic = type_param(p, C)?;
|
||||
let pixel = pixel_grid_param(p, C)?;
|
||||
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
|
||||
return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type"));
|
||||
match pixel {
|
||||
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
|
||||
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
|
||||
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
@@ -324,6 +343,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.rename_symbol_registration(&name, n);
|
||||
d.rename_symbol_export_type(&name, n);
|
||||
d.rename_symbol_nine_slice(&name, n);
|
||||
d.rename_symbol_pixel_aligned(&name, n);
|
||||
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
|
||||
d.unknown.insert(CURRENT_SYMBOL.into(), json!(n));
|
||||
}
|
||||
@@ -352,16 +372,26 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sym.dynamic = dynamic;
|
||||
fit_overrides(d, &instances_of(d, Some(&final_name)));
|
||||
}
|
||||
// Turning it on snaps the art and the instances at actual size when the edit ends
|
||||
// (`object::refresh_pixel_aligned`).
|
||||
if let Some(on) = pixel {
|
||||
d.set_symbol_pixel_aligned(&final_name, on);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(json!({
|
||||
"name": final_name,
|
||||
"registration": d.symbol_registration(&final_name).0,
|
||||
"exportType": d.symbol_export_type(&final_name).id(),
|
||||
"nineSlice": nine_slice_json(d, &final_name),
|
||||
"type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)),
|
||||
}))
|
||||
Ok(options_json(&s.doc()?.doc, &final_name))
|
||||
}
|
||||
|
||||
/// What `symbol.options` answers for symbol `name`.
|
||||
fn options_json(d: &Document, name: &str) -> Value {
|
||||
json!({
|
||||
"name": name,
|
||||
"registration": d.symbol_registration(name).0,
|
||||
"exportType": d.symbol_export_type(name).id(),
|
||||
"nineSlice": nine_slice_json(d, name),
|
||||
"type": type_id(d.symbols.iter().any(|x| x.name == name && x.dynamic)),
|
||||
"alignToPixelGrid": d.symbol_pixel_aligned(name),
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
|
||||
@@ -702,6 +732,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_registration(name, SymbolRegistration::CENTER);
|
||||
d.clear_symbol_export_type(name);
|
||||
d.set_symbol_nine_slice(name, None);
|
||||
d.set_symbol_pixel_aligned(name, false);
|
||||
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
|
||||
d.unknown.remove(CURRENT_SYMBOL);
|
||||
}
|
||||
@@ -725,6 +756,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reg = d.symbol_registration(&name);
|
||||
let export = d.symbol_export_type(&name);
|
||||
let nine = d.symbol_nine_slice(&name);
|
||||
let pixel = d.symbol_pixel_aligned(&name);
|
||||
s.edit("Duplicate Symbol", |d, _| {
|
||||
let art = d.reid(&sym.art);
|
||||
d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) });
|
||||
@@ -732,6 +764,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_registration(&new, reg);
|
||||
d.set_symbol_export_type(&new, export);
|
||||
d.set_symbol_nine_slice(&new, nine);
|
||||
d.set_symbol_pixel_aligned(&new, pixel);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }))
|
||||
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket (Stroke)",
|
||||
[],
|
||||
None,
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
has_doc,
|
||||
lp_stroke_edge
|
||||
),
|
||||
|
||||
@@ -580,6 +580,12 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (eid, count, changed) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
|
||||
// Each id in `through` is an edge of the group, given once.
|
||||
let group_edges: std::collections::HashSet<NodeId> = b::edges(n).iter().map(|e| e.id).collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
if let Some(id) = through.iter().find(|id| !group_edges.contains(id) || !seen.insert(**id)) {
|
||||
return Err(bad(C, format!("through: {id} is not an edge of {g}, or is given twice")));
|
||||
}
|
||||
let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
|
||||
let eid = start.id;
|
||||
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
|
||||
|
||||
@@ -766,6 +766,8 @@ pub struct SymbolOptions {
|
||||
pub export_type: SymbolExportType,
|
||||
/// 9-slice guides (`None`: 9-slice scaling off).
|
||||
pub nine_slice: Option<SymbolNineSlice>,
|
||||
/// Align to Pixel Grid.
|
||||
pub pixel_aligned: bool,
|
||||
}
|
||||
|
||||
impl SymbolOptions {
|
||||
@@ -776,6 +778,7 @@ impl SymbolOptions {
|
||||
registration: d.symbol_registration(name),
|
||||
export_type: d.symbol_export_type(name),
|
||||
nine_slice: d.symbol_nine_slice(name),
|
||||
pixel_aligned: d.symbol_pixel_aligned(name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -785,6 +788,7 @@ impl SymbolOptions {
|
||||
d.set_symbol_registration(name, self.registration);
|
||||
d.set_symbol_export_type(name, self.export_type);
|
||||
d.set_symbol_nine_slice(name, self.nine_slice);
|
||||
d.set_symbol_pixel_aligned(name, self.pixel_aligned);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1035,10 +1039,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Ellipse",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}",
|
||||
has_doc,
|
||||
ellipse
|
||||
),
|
||||
@@ -362,10 +362,28 @@ fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
|
||||
}
|
||||
|
||||
/// The most anchors `shape.ellipse` draws, as many as a polygon's sides.
|
||||
const MAX_ELLIPSE_ANCHORS: u64 = 1000;
|
||||
|
||||
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = rect_of(p, "shape.ellipse")?;
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? };
|
||||
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
|
||||
// One message for every number that is not a whole count in range (a fraction, a negative,
|
||||
// 0, 1, too many); a value that is not a number gets `number_or`'s.
|
||||
let (key, min, max) = ("anchors", 2, MAX_ELLIPSE_ANCHORS);
|
||||
let n = number_or(p, key, 4.0, "shape.ellipse")?;
|
||||
if n.fract() != 0.0 || !(min as f64..=max as f64).contains(&n) {
|
||||
return Err(bad("shape.ellipse", format!("`{key}` must be a whole number between {min} and {max} (got {n})")));
|
||||
}
|
||||
let x = n as u64;
|
||||
let xf = rect_transform(r, p, "shape.ellipse")?;
|
||||
let rotation = f64_or(p, "rotation", 0.0);
|
||||
if x != 4 {
|
||||
// Another count is a plain path: a live ellipse always has 4 anchors.
|
||||
let path = shapes::ellipse_with_anchors(Rect::new(0.0, 0.0, r.width(), r.height()), x as u32).transformed(xf);
|
||||
return add_art_turned(s, "Ellipse", path_kind(path, None), rotation);
|
||||
}
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf };
|
||||
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
|
||||
}
|
||||
|
||||
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
|
||||
|
||||
@@ -631,13 +631,12 @@ impl LiquifyStroke {
|
||||
}
|
||||
let msg = (!ids.is_empty()).then(|| {
|
||||
let n = ids.len();
|
||||
format!(
|
||||
"{} left {n} object{} under the brush as {} ({}): it reshapes paths only",
|
||||
self.prm.kind.label(),
|
||||
if n == 1 { "" } else { "s" },
|
||||
if n == 1 { "it was" } else { "they were" },
|
||||
kinds.join(", ")
|
||||
)
|
||||
let (tool, kinds) = (self.prm.kind.label(), kinds.join(", "));
|
||||
if n == 1 {
|
||||
format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only")
|
||||
} else {
|
||||
format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only")
|
||||
}
|
||||
});
|
||||
(ids, msg)
|
||||
}
|
||||
|
||||
@@ -270,6 +270,33 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
super::fileinfo::file_info
|
||||
),
|
||||
cmd!(
|
||||
"file.info.saveTemplate",
|
||||
"Save Metadata Template…",
|
||||
[],
|
||||
None,
|
||||
"{name?: save into the metadata templates folder as <name>.xmp (a name with characters file systems reject, a dot at either end, or a device name is an error (spaces at either end are dropped); the same name replaces that template), path?: save to this file instead (not both), fields?: {File Info fields as file.info takes them} save these instead of the document's (default: the document's File Info)} write the File Info as an XMP metadata template: title (only one of its own, not Untitled-N), author, authorTitle, description, keywords, rating (1–5), copyrightStatus, copyrightNotice and copyrightUrl, each where it has a value; the dates are left out → {name, path} (with name), {path} (with path), or {data: the XMP text} with neither",
|
||||
has_doc,
|
||||
super::fileinfo::save_template
|
||||
),
|
||||
cmd!(
|
||||
"file.info.applyTemplate",
|
||||
"Import Metadata Template…",
|
||||
[],
|
||||
None,
|
||||
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
|
||||
has_doc,
|
||||
super::fileinfo::apply_template
|
||||
),
|
||||
cmd!(
|
||||
query "file.info.templates",
|
||||
"Metadata Templates",
|
||||
[],
|
||||
None,
|
||||
"{create?: false (true: make the folder when it is missing)} the metadata templates in the metadata templates folder next to the preferences, sorted by name, at most 1,000 → {templates: [{name, file: the file name, path}], folder?: the folder (left out for a request that may not read it, in runs without preferences and on the web, where the list is empty)}",
|
||||
super::always,
|
||||
super::fileinfo::templates
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
|
||||
@@ -3,9 +3,10 @@ use super::common::{
|
||||
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session,
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
|
||||
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
};
|
||||
use kurbo::{CubicBez, Line, PathSeg};
|
||||
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
use vectorcraft_tools::draw2::MIN_BRUSH_SIZE;
|
||||
@@ -46,8 +47,8 @@ pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
|
||||
|
||||
/// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment
|
||||
/// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least
|
||||
/// `step` long is found.
|
||||
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<SubPath>> {
|
||||
/// `step` long is found, and also at the parameters `extra` gives for it.
|
||||
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec<f64>) -> Option<Vec<SubPath>> {
|
||||
let nseg = sp.segment_count();
|
||||
if nseg == 0 {
|
||||
return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]);
|
||||
@@ -64,6 +65,13 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
|
||||
let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot());
|
||||
let wanted = (3.0 * edge / step).ceil();
|
||||
let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K };
|
||||
let mut ts: Vec<f64> = (1..=samples).map(|k| k as f64 / samples as f64).collect();
|
||||
let more = extra(c);
|
||||
if !more.is_empty() {
|
||||
ts.extend(more.into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0));
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup();
|
||||
}
|
||||
let mut prev_t = 0.0;
|
||||
let mut prev_rm = remove(c.eval(0.0));
|
||||
let mut start = if prev_rm { None } else { Some(0.0) };
|
||||
@@ -73,8 +81,7 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
|
||||
runs.push(std::mem::take(&mut cur));
|
||||
}
|
||||
}
|
||||
for k in 1..=samples {
|
||||
let t = k as f64 / samples as f64;
|
||||
for t in ts {
|
||||
let rm = remove(c.eval(t));
|
||||
if rm != prev_rm {
|
||||
let (mut lo, mut hi) = (prev_t, t);
|
||||
@@ -146,10 +153,15 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
|
||||
/// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output
|
||||
/// object (one object per piece when the path had a single subpath), or None if unchanged.
|
||||
pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<PathData>> {
|
||||
erase_outline_at(pd, step, remove, &|_| vec![])
|
||||
}
|
||||
|
||||
/// [`erase_outline`], also sampling each segment at the parameters `extra` gives for it.
|
||||
fn erase_outline_at(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec<f64>) -> Option<Vec<PathData>> {
|
||||
let mut changed = false;
|
||||
let mut subs = vec![];
|
||||
for sp in &pd.subpaths {
|
||||
match cut_subpath(sp, step, remove) {
|
||||
match cut_subpath(sp, step, remove, extra) {
|
||||
Some(pieces) => {
|
||||
changed = true;
|
||||
subs.extend(pieces);
|
||||
@@ -274,6 +286,12 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.eraseRegion";
|
||||
if let Some(rect) = p.get("rect").filter(|v| !v.is_null()) {
|
||||
if p.get("points").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "give `points` or `rect`, not both"));
|
||||
}
|
||||
return erase_rect(s, marquee_param(rect, C)?);
|
||||
}
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = number_or(p, "size", 10.0, C)?;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
@@ -325,6 +343,58 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a
|
||||
/// height above 0.
|
||||
fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
|
||||
const SHAPE: &str = "rect is [x, y, width, height] in points, with a width and a height above 0";
|
||||
let n: Vec<f64> = match v.as_array() {
|
||||
Some(a) if a.len() == 4 => a.iter().map(Value::as_f64).collect::<Option<_>>().ok_or_else(|| bad(cmd, SHAPE))?,
|
||||
_ => return Err(bad(cmd, SHAPE)),
|
||||
};
|
||||
let [x, y, w, h] = [n[0], n[1], n[2], n[3]];
|
||||
if !(n.iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && (x + w).is_finite() && (y + h).is_finite()) {
|
||||
return Err(bad(cmd, SHAPE));
|
||||
}
|
||||
Ok(Rect::new(x, y, x + w, y + h))
|
||||
}
|
||||
|
||||
/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or
|
||||
/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges.
|
||||
fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
|
||||
let region =
|
||||
PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true));
|
||||
let inside = |q: Point| q.x >= r.x0 && q.x <= r.x1 && q.y >= r.y0 && q.y <= r.y1;
|
||||
// An open path is sampled at least every half of the rectangle's shorter side, and also where
|
||||
// each segment crosses the rectangle's edges and halfway between those crossings, so a stretch
|
||||
// inside the rectangle is found however long the segment is.
|
||||
let step = r.width().min(r.height()) / 2.0;
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
|
||||
let crossings = |c: CubicBez| {
|
||||
let mut ts: Vec<f64> = (0..4)
|
||||
.flat_map(|k| PathSeg::Cubic(c).intersect_line(Line::new(corners[k], corners[(k + 1) % 4])))
|
||||
.map(|x| x.segment_t)
|
||||
.filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)
|
||||
.collect();
|
||||
ts.sort_by(f64::total_cmp);
|
||||
let mids: Vec<f64> = [0.0].iter().chain(&ts).zip(ts.iter().chain(&[1.0])).map(|(a, b)| 0.5 * (a + b)).collect();
|
||||
ts.extend(mids);
|
||||
ts
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? {
|
||||
if pd.is_closed() {
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference))));
|
||||
} else if let Some(pieces) = erase_outline_at(&pd, step, &inside, &crossings) {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
|
||||
/// `sizeMode`.
|
||||
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
|
||||
|
||||
@@ -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)
|
||||
),
|
||||
|
||||
@@ -3,14 +3,28 @@
|
||||
//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]),
|
||||
//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or
|
||||
//! `.ai` opens with the File Info it gives ([`read_pdf`]).
|
||||
//!
|
||||
//! Metadata templates: `file.info.saveTemplate` writes the File Info as an XMP file
|
||||
//! ([`vectorcraft_pdf::metadata_template`]), `file.info.applyTemplate` merges one into the File
|
||||
//! Info, and `file.info.templates` lists those in the metadata templates folder.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::metadata::{MAX_RATING, iso8601};
|
||||
use vectorcraft_doc::{ColorMode, CopyrightStatus, DocMetadata, Document};
|
||||
|
||||
use super::{Result, Session, bad};
|
||||
use super::{Result, Session, bad, switch_or, text_param};
|
||||
|
||||
const C: &str = "file.info";
|
||||
const SAVE: &str = "file.info.saveTemplate";
|
||||
const APPLY: &str = "file.info.applyTemplate";
|
||||
const LIST: &str = "file.info.templates";
|
||||
/// The extension of a metadata template file.
|
||||
const TEMPLATE_EXT: &str = "xmp";
|
||||
/// The most templates `file.info.templates` lists.
|
||||
const MAX_LISTED: usize = 1000;
|
||||
/// The largest metadata template `file.info.saveTemplate` writes and `file.info.applyTemplate`
|
||||
/// reads, in bytes (8 MB). The largest template File Info's fields can give is under 4 MB.
|
||||
const MAX_TEMPLATE_FILE: usize = vectorcraft_pdf::MAX_TEMPLATE_BYTES;
|
||||
/// Longest text field, in characters.
|
||||
const MAX_TEXT: usize = 65_536;
|
||||
/// Longest keyword, in characters.
|
||||
@@ -21,9 +35,13 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb
|
||||
|
||||
/// What `file.info` reports (and takes back).
|
||||
pub(crate) fn info_json(d: &Document) -> Value {
|
||||
let m = &d.metadata;
|
||||
info_json_with(d, d.info_title(), &d.metadata)
|
||||
}
|
||||
|
||||
/// [`info_json`] with the title `title` and the metadata `m` in place of the document's.
|
||||
fn info_json_with(d: &Document, title: &str, m: &DocMetadata) -> Value {
|
||||
json!({
|
||||
"title": d.info_title(),
|
||||
"title": title,
|
||||
"author": m.author,
|
||||
"authorTitle": m.author_title,
|
||||
"description": m.description,
|
||||
@@ -48,11 +66,25 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Value::Object(o) => o,
|
||||
_ => return Err(bad(C, "params must be an object")),
|
||||
};
|
||||
let (title, m) = edited(s, Some(o))?;
|
||||
commit(s, title, m)?;
|
||||
Ok(info_json(&s.doc()?.doc))
|
||||
}
|
||||
|
||||
/// The active document's File Info title and metadata with `fields` (as `file.info` takes them)
|
||||
/// applied.
|
||||
fn edited(s: &Session, fields: Option<&Map<String, Value>>) -> Result<(String, DocMetadata)> {
|
||||
let d = &s.doc()?.doc;
|
||||
let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone());
|
||||
for (k, v) in o {
|
||||
for (k, v) in fields.into_iter().flatten() {
|
||||
apply(&mut title, &mut m, k, v)?;
|
||||
}
|
||||
Ok((title, m))
|
||||
}
|
||||
|
||||
/// Make `title` and `m` the active document's File Info in one undo step; nothing is recorded when
|
||||
/// they are what it has. Whether anything changed.
|
||||
fn commit(s: &mut Session, title: String, mut m: DocMetadata) -> Result<bool> {
|
||||
let d = &s.doc()?.doc;
|
||||
// A title File Info changes becomes the document's own, as it always has (the tab and Save As
|
||||
// offer it where the document has no file), and replaces the one its file gave.
|
||||
@@ -60,16 +92,290 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if retitled {
|
||||
m.title = None;
|
||||
}
|
||||
if retitled || m != d.metadata {
|
||||
s.edit("File Info", |d, _| {
|
||||
if retitled {
|
||||
d.title = title;
|
||||
}
|
||||
d.metadata = m;
|
||||
Ok(())
|
||||
})?;
|
||||
if !retitled && m == d.metadata {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(info_json(&s.doc()?.doc))
|
||||
s.edit("File Info", |d, _| {
|
||||
if retitled {
|
||||
d.title = title;
|
||||
}
|
||||
d.metadata = m;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The optional object `p` gives for `key`.
|
||||
fn fields_param<'a>(p: &'a Value, key: &str, c: &str) -> Result<Option<&'a Map<String, Value>>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Object(o)) => Ok(Some(o)),
|
||||
Some(_) => Err(bad(c, format!("`{key}` must be an object"))),
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Have `file.info.saveTemplate`, `file.info.applyTemplate` and `file.info.templates` keep the
|
||||
/// metadata templates in the folder `dir`, which a save makes when it is missing.
|
||||
pub fn attach_metadata_templates_dir(&mut self, dir: std::path::PathBuf) {
|
||||
self.metadata_templates_dir = Some(dir);
|
||||
}
|
||||
|
||||
/// The metadata templates folder ([`Session::attach_metadata_templates_dir`]); none on the web,
|
||||
/// which has no folders.
|
||||
pub fn metadata_templates_dir(&self) -> Option<&std::path::Path> {
|
||||
self.metadata_templates_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The metadata template of the File Info `title` and `m`: each field that has a value, the title
|
||||
/// only where it is one of its own ([`super::fileio::is_own_title`]), the rating only from 1 up.
|
||||
fn template_of(title: &str, m: &DocMetadata) -> vectorcraft_pdf::FileInfo {
|
||||
let text = |s: &str| (!s.trim().is_empty()).then(|| s.to_string());
|
||||
vectorcraft_pdf::FileInfo {
|
||||
title: super::fileio::is_own_title(title).then(|| title.to_string()),
|
||||
author: text(&m.author),
|
||||
author_title: text(&m.author_title),
|
||||
description: text(&m.description),
|
||||
keywords: (!m.keywords.is_empty()).then(|| m.keywords.clone()),
|
||||
rating: (m.rating > 0).then_some(m.rating),
|
||||
copyright_notice: text(&m.copyright_notice),
|
||||
copyright_url: text(&m.copyright_url),
|
||||
copyrighted: match m.copyright_status {
|
||||
CopyrightStatus::Copyrighted => Some(true),
|
||||
CopyrightStatus::PublicDomain => Some(false),
|
||||
CopyrightStatus::Unknown => None,
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of the template `name` in the folder `dir`: `name` made a safe file name, with
|
||||
/// [`TEMPLATE_EXT`].
|
||||
fn template_path(dir: &std::path::Path, name: &str, c: &str) -> Result<String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(bad(c, "the template name can't be empty"));
|
||||
}
|
||||
Ok(dir.join(super::swatchlib::library_file_name(name, TEMPLATE_EXT)).to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// The error for a template over [`MAX_TEMPLATE_FILE`].
|
||||
fn too_big(c: &str) -> crate::EngineError {
|
||||
bad(c, format!("the file is larger than {} MB", MAX_TEMPLATE_FILE >> 20))
|
||||
}
|
||||
|
||||
/// File Info › Save Metadata Template: `file.info.saveTemplate {name?, path?, fields?}`.
|
||||
pub(crate) fn save_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = text_param(p, "name", SAVE)?;
|
||||
let path = text_param(p, "path", SAVE)?;
|
||||
let (title, m) = edited(s, fields_param(p, "fields", SAVE)?)?;
|
||||
let xmp = vectorcraft_pdf::metadata_template(&template_of(&title, &m));
|
||||
if xmp.len() > MAX_TEMPLATE_FILE {
|
||||
return Err(too_big(SAVE));
|
||||
}
|
||||
match (name, path) {
|
||||
(Some(_), Some(_)) => Err(bad(SAVE, "give `name` or `path`, not both")),
|
||||
(Some(name), None) => {
|
||||
let dir = s.metadata_templates_dir().ok_or_else(|| bad(SAVE, "no metadata templates folder here"))?.to_path_buf();
|
||||
let path = template_path(&dir, name, SAVE)?;
|
||||
// The name is the file name as it is, so two names never share a file.
|
||||
let listed = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned());
|
||||
if listed.as_deref() != Some(name.trim()) {
|
||||
return Err(bad(SAVE, "the template name isn't usable as a file name"));
|
||||
}
|
||||
// Only a file in the folder itself is replaced: a link there is not followed.
|
||||
if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) {
|
||||
return Err(crate::EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
let dir = dir.to_string_lossy().into_owned();
|
||||
// The app's own folder, under a name checked above: no root applies.
|
||||
crate::file_access::unconfined(|| super::fileio::create_dir(&dir).and_then(|()| super::fileio::write_file(&path, xmp.as_bytes())))?;
|
||||
Ok(json!({ "name": listed, "path": super::fileio::shown_path(&path) }))
|
||||
}
|
||||
(None, Some(path)) => {
|
||||
super::fileio::write_file(path, xmp.as_bytes())?;
|
||||
Ok(json!({ "path": path }))
|
||||
}
|
||||
(None, None) => Ok(json!({ "data": xmp })),
|
||||
}
|
||||
}
|
||||
|
||||
/// How `file.info.applyTemplate` merges a template's fields into the File Info.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Merge {
|
||||
/// Clear the fields a template can hold, then take the template's.
|
||||
Replace,
|
||||
/// Keep the fields, and take each one the template gives.
|
||||
Keep,
|
||||
/// Keep the fields: add the template's keywords, and take its other fields only where the File
|
||||
/// Info has none.
|
||||
Append,
|
||||
}
|
||||
|
||||
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
|
||||
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mode = match text_param(p, "mode", APPLY)? {
|
||||
Some("replace") => Merge::Replace,
|
||||
Some("keep") => Merge::Keep,
|
||||
Some("append") => Merge::Append,
|
||||
_ => return Err(bad(APPLY, "mode must be replace, keep or append")),
|
||||
};
|
||||
let apply = switch_or(p, "apply", true, APPLY)?;
|
||||
let base = fields_param(p, "base", APPLY)?;
|
||||
let bytes = template_bytes(s, p)?;
|
||||
let t = vectorcraft_pdf::read_template(&bytes).ok_or_else(|| bad(APPLY, "the file is not an XMP metadata template"))?;
|
||||
let (mut title, mut m) = edited(s, base)?;
|
||||
merge(&mut title, &mut m, t, mode);
|
||||
if !apply {
|
||||
return Ok(info_json_with(&s.doc()?.doc, &title, &m));
|
||||
}
|
||||
let changed = commit(s, title, m)?;
|
||||
let mut out = info_json(&s.doc()?.doc);
|
||||
out["changed"] = json!(changed);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
|
||||
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
|
||||
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
|
||||
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
|
||||
// At most one byte past the limit is read, so a huge file is never read whole.
|
||||
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
|
||||
let bytes = match given {
|
||||
[Some(path), None, None] => read(path)?,
|
||||
[None, Some(name), None] => {
|
||||
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
|
||||
let mut path = template_path(dir, name, APPLY)?;
|
||||
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
|
||||
// the extension in lowercase, then in other letter case. Only files in the folder itself
|
||||
// are listed: a link there is not followed.
|
||||
let name = name.trim();
|
||||
let own = format!("{name}.{TEMPLATE_EXT}");
|
||||
let listed = template_files(dir)
|
||||
.filter(|f| f == name || f.rsplit_once('.').is_some_and(|(stem, _)| stem == name))
|
||||
.min_by_key(|f| (f != name, *f != own));
|
||||
if let Some(file) = listed {
|
||||
path = dir.join(file).to_string_lossy().into_owned();
|
||||
} else if std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy()).as_deref() != Some(name) {
|
||||
// A name that is not a file name as it is never opens another template.
|
||||
return Err(bad(APPLY, "the template name isn't usable as a file name"));
|
||||
}
|
||||
let plain_file = |path: &str| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file());
|
||||
if std::fs::symlink_metadata(&path).is_ok() && !plain_file(&path) {
|
||||
return Err(crate::EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
// The app's own folder: no root applies.
|
||||
crate::file_access::unconfined(|| read(&path))?
|
||||
}
|
||||
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
|
||||
[None, None, Some(data)] => data.as_bytes().to_vec(),
|
||||
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
|
||||
};
|
||||
if bytes.len() > MAX_TEMPLATE_FILE {
|
||||
return Err(too_big(APPLY));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Merge the template `t` into the File Info `title` and `m` as `mode` says. Each field goes in as
|
||||
/// `file.info` would take it; a value it would refuse is left out.
|
||||
fn merge(title: &mut String, m: &mut DocMetadata, t: vectorcraft_pdf::FileInfo, mode: Merge) {
|
||||
if mode == Merge::Replace {
|
||||
// The title is never cleared: a document always has one.
|
||||
m.author.clear();
|
||||
m.author_title.clear();
|
||||
m.description.clear();
|
||||
m.keywords.clear();
|
||||
m.rating = 0;
|
||||
m.copyright_status = CopyrightStatus::Unknown;
|
||||
m.copyright_notice.clear();
|
||||
m.copyright_url.clear();
|
||||
}
|
||||
let status = t.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
|
||||
let fields = [
|
||||
("title", t.title.map(Value::from)),
|
||||
("author", t.author.map(Value::from)),
|
||||
("authorTitle", t.author_title.map(Value::from)),
|
||||
("description", t.description.map(Value::from)),
|
||||
("keywords", t.keywords.map(Value::from)),
|
||||
("rating", t.rating.map(Value::from)),
|
||||
("copyrightStatus", status.map(|s| Value::from(s.id()))),
|
||||
("copyrightNotice", t.copyright_notice.map(Value::from)),
|
||||
("copyrightUrl", t.copyright_url.map(Value::from)),
|
||||
];
|
||||
for (k, v) in fields {
|
||||
let Some(mut v) = v else { continue };
|
||||
if mode == Merge::Append {
|
||||
let empty = match k {
|
||||
"title" => !super::fileio::is_own_title(title),
|
||||
"author" => m.author.is_empty(),
|
||||
"authorTitle" => m.author_title.is_empty(),
|
||||
"description" => m.description.is_empty(),
|
||||
"rating" => m.rating == 0,
|
||||
"copyrightStatus" => m.copyright_status == CopyrightStatus::Unknown,
|
||||
"copyrightNotice" => m.copyright_notice.is_empty(),
|
||||
"copyrightUrl" => m.copyright_url.is_empty(),
|
||||
_ => true,
|
||||
};
|
||||
if !empty {
|
||||
continue;
|
||||
}
|
||||
if k == "keywords" {
|
||||
let mut all: Vec<Value> = m.keywords.iter().cloned().map(Value::from).collect();
|
||||
all.extend(v.as_array().cloned().unwrap_or_default());
|
||||
v = Value::from(all);
|
||||
}
|
||||
}
|
||||
// `apply` changes the field only when it takes the value.
|
||||
let _ = apply(title, m, k, &v);
|
||||
}
|
||||
}
|
||||
|
||||
/// The file names of the templates in the folder `dir`: its files with a name before the
|
||||
/// [`TEMPLATE_EXT`] extension, in any case. The app's own folder, read directly; a folder not made
|
||||
/// yet holds none.
|
||||
fn template_files(dir: &std::path::Path) -> impl Iterator<Item = String> {
|
||||
std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|file| file.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(TEMPLATE_EXT) && !stem.is_empty()))
|
||||
}
|
||||
|
||||
/// `file.info.templates {create?}`: the metadata templates in the folder, by name.
|
||||
pub(crate) fn templates(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let create = switch_or(p, "create", false, LIST)?;
|
||||
let Some(dir) = s.metadata_templates_dir().map(|d| d.to_string_lossy().into_owned()) else {
|
||||
return Ok(json!({ "templates": [] }));
|
||||
};
|
||||
if create {
|
||||
// The app's own folder: no root applies.
|
||||
crate::file_access::unconfined(|| super::fileio::create_dir(&dir))?;
|
||||
}
|
||||
// The first [`MAX_LISTED`] by name, with no more than that many held at once.
|
||||
let mut files = std::collections::BTreeSet::new();
|
||||
for file in template_files(std::path::Path::new(&dir)) {
|
||||
files.insert(file);
|
||||
if files.len() > MAX_LISTED {
|
||||
files.pop_last();
|
||||
}
|
||||
}
|
||||
let list: Vec<Value> = files
|
||||
.iter()
|
||||
.filter_map(|file| {
|
||||
let (stem, _) = file.rsplit_once('.')?;
|
||||
let path = std::path::Path::new(&dir).join(file).to_string_lossy().into_owned();
|
||||
Some(json!({ "name": stem, "file": file, "path": super::fileio::shown_path(&path) }))
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({ "templates": list });
|
||||
if super::fileio::shown_path(&dir) == dir.as_str() {
|
||||
out["folder"] = json!(dir);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each
|
||||
@@ -79,8 +385,10 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
|
||||
let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
|
||||
let fields = [
|
||||
("author", f.author.map(Value::from)),
|
||||
("authorTitle", f.author_title.map(Value::from)),
|
||||
("description", f.description.map(Value::from)),
|
||||
("keywords", f.keywords.map(Value::from)),
|
||||
("rating", f.rating.map(Value::from)),
|
||||
("copyrightStatus", status.map(|s| Value::from(s.id()))),
|
||||
("copyrightNotice", f.copyright_notice.map(Value::from)),
|
||||
("copyrightUrl", f.copyright_url.map(Value::from)),
|
||||
|
||||
@@ -39,7 +39,7 @@ pub mod jxlread;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note};
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
mod jp2read;
|
||||
|
||||
@@ -199,8 +199,12 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
|
||||
/// out, at any depth of layers, sublayers and groups that don't clip, unless what the renderer
|
||||
/// draws for them, their effects included ([`vectorcraft_render::effect_bounds`]), reaches it.
|
||||
/// Objects that reach it stay whole (the file's bounds clip them), as DXF's crop leaves them.
|
||||
/// Symbol instances are measured by their art, and the box of one whose art holds brushed strokes
|
||||
/// grows by as far as their brush art can paint ([`SymbolBoxes::with_brush_art`]). An object that
|
||||
/// Both boxes grow by the room brush art can paint past the brushed strokes of the object and of
|
||||
/// the objects in it ([`vectorcraft_brush::reach_within`]: a clipping group or layer by its clipping
|
||||
/// path's, a compound path by its own strokes'), so a brushed path just off `rect` stays when its
|
||||
/// brush art reaches it. Symbol instances are measured by their art, and the box of one whose art
|
||||
/// holds brushed strokes grows by as far as their brush art can paint
|
||||
/// ([`SymbolBoxes::with_brush_art`]). An object that
|
||||
/// holds a symbol instance also stays when what the canvas paints for it reaches `rect`
|
||||
/// ([`vectorcraft_render::painted_bounds`]: the effects in the symbols' art and its own effects). A
|
||||
/// clipping layer keeps every object, its clipping path among them. An artboard's file then holds
|
||||
@@ -233,7 +237,9 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &
|
||||
let mut holds_instance = false;
|
||||
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
|
||||
(n.visual_bounds_with(symbols).is_none_or(over) || renderer.effect_bounds(symbols, n).is_some_and(over) || painted()).then(|| n.clone())
|
||||
let reach = vectorcraft_brush::reach_within(n);
|
||||
let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b });
|
||||
(n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone())
|
||||
}
|
||||
let symbols = doc.symbol_boxes().with_brush_art();
|
||||
let mut d = doc.clone();
|
||||
|
||||
@@ -73,8 +73,10 @@ pub struct RasterImage {
|
||||
pub height: u32,
|
||||
/// The resolution the file declares (see [`super::ppi::resolution`]).
|
||||
pub ppi: Option<(f64, f64)>,
|
||||
/// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]).
|
||||
pub clip: Option<vectorcraft_geom::PathData>,
|
||||
/// The clipping path its file draws it through, in the image's pixel space, with its fill rule:
|
||||
/// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd,
|
||||
/// [`psdread::clipping_path`]).
|
||||
pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>,
|
||||
}
|
||||
|
||||
pub(super) fn err(e: impl std::fmt::Display) -> EngineError {
|
||||
@@ -949,7 +951,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
|
||||
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
|
||||
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
|
||||
/// other samples become 8-bit RGBA.
|
||||
/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file
|
||||
/// names ([`png_with_clip`]).
|
||||
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
let ppi = super::ppi::resolution(bytes);
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
@@ -957,7 +960,8 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
}
|
||||
if psdread::is_psd(bytes) {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi);
|
||||
let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?;
|
||||
return Ok(png_with_clip(img, psdread::clipping_path(bytes)));
|
||||
}
|
||||
if jxlread::is_jxl(bytes) {
|
||||
let (img, icc, orientation) = jxlread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?;
|
||||
@@ -1125,10 +1129,48 @@ fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi:
|
||||
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None })
|
||||
}
|
||||
|
||||
/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from
|
||||
/// ([`png_with_clip`]).
|
||||
const CLIP_KEYWORD: &str = "VectorCraft clip";
|
||||
|
||||
/// Longest clipping path a PNG keeps (bytes of its JSON).
|
||||
const MAX_PNG_CLIP: usize = 16 << 20;
|
||||
|
||||
/// `img`, a PNG made from a PSD or PSB file, with `clip`, the clipping path that file names in the
|
||||
/// image's pixel space (even-odd): the image keeps it, and its PNG keeps it in a text chunk, so the
|
||||
/// Links commands know a clip group of that path as the file's ([`png_clip`]). A path whose JSON is
|
||||
/// longer than [`MAX_PNG_CLIP`] is left out, and the image comes in unclipped.
|
||||
fn png_with_clip(mut img: RasterImage, clip: Option<vectorcraft_geom::PathData>) -> RasterImage {
|
||||
let Some(clip) = clip else { return img };
|
||||
let Some(json) = serde_json::to_string(&clip).ok().filter(|j| j.len() <= MAX_PNG_CLIP) else { return img };
|
||||
let png = vectorcraft_render::encode::png::with_text(img.blob.bytes.to_vec(), &[(CLIP_KEYWORD, json.into())]);
|
||||
img.blob = ImageBlob::new("image/png", png);
|
||||
img.key = img.blob.content_key();
|
||||
img.clip = Some((clip, vectorcraft_geom::FillRule::EvenOdd));
|
||||
img
|
||||
}
|
||||
|
||||
/// The clipping path a PNG made from a PSD or PSB file keeps ([`png_with_clip`]), in its pixel
|
||||
/// space; `None` for other images, and for a text chunk longer than [`MAX_PNG_CLIP`] or a path
|
||||
/// past [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Reads only the chunks before the image data.
|
||||
pub(crate) fn png_clip(png: &[u8]) -> Option<vectorcraft_geom::PathData> {
|
||||
if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
return None;
|
||||
}
|
||||
let keyword = [CLIP_KEYWORD.as_bytes(), &[0]].concat();
|
||||
let json = super::ppi::png_chunks(png)
|
||||
.take_while(|(ty, _)| *ty != b"IDAT")
|
||||
.find_map(|(ty, data)| data.strip_prefix(keyword.as_slice()).filter(|_| ty == b"tEXt"))?;
|
||||
if json.len() > MAX_PNG_CLIP {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
|
||||
}
|
||||
|
||||
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
|
||||
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
|
||||
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?;
|
||||
let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?;
|
||||
let (sx, sy) = crate::cmd::place::pt_per_px(ppi);
|
||||
let mut d = Document::new(width as f64 * sx, height as f64 * sy);
|
||||
let layer = d.layers[0].id;
|
||||
@@ -1138,7 +1180,7 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
id,
|
||||
NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })),
|
||||
);
|
||||
let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes));
|
||||
let mut n = file_clipped(&mut d, n, clip.map(|(path, _)| path));
|
||||
n.name = Some(name.to_string());
|
||||
d.images.insert(key, blob);
|
||||
d.insert(Some(layer), 0, n).map_err(err)?;
|
||||
|
||||
@@ -414,6 +414,98 @@ fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() {
|
||||
assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}");
|
||||
}
|
||||
|
||||
/// A square saved as "Square" and the clipping path naming it.
|
||||
fn square_resources() -> Vec<u8> {
|
||||
let square = saved_path(false, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]);
|
||||
[resource(2000, b"Square", &square), clipping_name(b"Square")].concat()
|
||||
}
|
||||
|
||||
/// `bytes` written as `name` in `dir`, by its path.
|
||||
fn write_file(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, bytes).unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// links.relink and links.update put a linked PSD file's image in the clip group of the clipping
|
||||
/// path its new file names, take that clip group's clipping path away when the new file names
|
||||
/// none, and give it back when a later file names one again.
|
||||
#[test]
|
||||
fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-relink-clip");
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let square = write_file(&dir, "square.psd", &red_psd(&square_resources()));
|
||||
let plain = write_file(&dir, "plain.psd", &red_psd(&[]));
|
||||
let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]];
|
||||
let squared = vec![[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]];
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
|
||||
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), r["image"].as_u64().unwrap());
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)));
|
||||
s.execute("links.relink", &json!({"ids": [image], "path": square})).unwrap();
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared.clone(), true, NodeId(image)), "the new file's clipping path");
|
||||
s.execute("links.relink", &json!({"ids": [image], "path": plain})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
match d.node(group).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id.0).collect::<Vec<_>>(), [image]),
|
||||
other => panic!("a plain group of the image: {other:?}"),
|
||||
}
|
||||
s.execute("links.relink", &json!({"ids": [image], "path": cut})).unwrap();
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)), "clipped again");
|
||||
// The file is saved again with another clipping path.
|
||||
std::fs::write(&cut, red_psd(&square_resources())).unwrap();
|
||||
s.execute("links.update", &json!({"ids": [image]})).unwrap();
|
||||
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
|
||||
}
|
||||
|
||||
/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a
|
||||
/// text chunk within the size limit that reads as a path gives one back.
|
||||
#[test]
|
||||
fn the_kept_png_holds_the_clipping_path_within_bounds() {
|
||||
let img = raster_image(&red_psd(&triangle_resources())).unwrap();
|
||||
let (path, rule) = img.clip.clone().expect("the file's clipping path");
|
||||
assert_eq!(rule, vectorcraft_geom::FillRule::EvenOdd);
|
||||
assert_eq!(super::load::png_clip(&img.blob.bytes), Some(path));
|
||||
let plain = raster_image(&red_psd(&[])).unwrap();
|
||||
assert!(plain.clip.is_none() && super::load::png_clip(&plain.blob.bytes).is_none());
|
||||
let with = |text: String| vectorcraft_render::encode::png::with_text(plain.blob.bytes.to_vec(), &[("VectorCraft clip", text.into())]);
|
||||
assert_eq!(super::load::png_clip(&with("not a path".into())), None);
|
||||
assert_eq!(super::load::png_clip(&with(" ".repeat((16 << 20) + 1))), None, "a chunk past the limit is not read");
|
||||
}
|
||||
|
||||
/// A plain image relinked to a PSD file that names a clipping path goes into a clip group of that
|
||||
/// path, under the even-odd rule; a clipping mask made in the document stays around it.
|
||||
#[test]
|
||||
fn a_plain_image_relinked_to_a_clipped_psd_is_clipped_by_its_path() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("psd-relink-plain");
|
||||
let plain = write_file(&dir, "plain.psd", &red_psd(&[]));
|
||||
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"path": plain, "at": [50, 25]})).unwrap();
|
||||
let image = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let group = d.parent_of(image).expect("a clip group");
|
||||
assert_eq!(clip_group(d, group), (vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]], true, image));
|
||||
// The clipping path's fill rule changed in the document makes it the document's own mask: a
|
||||
// relink keeps it and puts the file's clip group inside it.
|
||||
let clip = match d.node(group).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, .. }) => children[0].id,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let Some(vectorcraft_doc::Node { kind: NodeKind::Path { rule, .. }, .. }) = doc.node_mut(clip) {
|
||||
*rule = vectorcraft_geom::FillRule::NonZero;
|
||||
}
|
||||
s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let inner = d.parent_of(image).unwrap();
|
||||
assert_eq!(d.parent_of(inner), Some(group), "the document's mask holds the file's clip group");
|
||||
assert!(clip_group(d, inner).1, "the file's clip group is even-odd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() {
|
||||
let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]);
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! SVG encodings, profiles and embedded fonts through the engine: the options reach the file,
|
||||
//! files in each encoding open again, and `document.serialize` reads them as text.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Document;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -109,6 +112,106 @@ fn a_chosen_artboard_s_svg_keeps_an_object_whose_shadow_reaches_it() {
|
||||
assert_eq!(paths(&mut s), 1, "its shadow reaches 10 pt onto the artboard");
|
||||
}
|
||||
|
||||
/// A 100 × 100 document whose 3 pt. Round brush paints with a 20 pt nib, and the left edge of its
|
||||
/// artboard.
|
||||
fn nib_doc() -> (Document, f64) {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else {
|
||||
panic!("the 3 pt. Round brush")
|
||||
};
|
||||
c.size = 20.0;
|
||||
vectorcraft_brush::store(&mut d, &lib);
|
||||
let x0 = d.artboards[0].rect.x0;
|
||||
(d, x0)
|
||||
}
|
||||
|
||||
/// A line from (`x`, 40) to (`x`, 60) with a 1 pt stroke in `paint`, painted by the 20 pt nib of
|
||||
/// [`nib_doc`] when `brushed`: the nib paints 10 pt either side of the line.
|
||||
fn nib_line(d: &mut Document, x: f64, paint: vectorcraft_color::Paint, brushed: bool) -> vectorcraft_doc::Node {
|
||||
let mut look = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, paint, 1.0);
|
||||
if brushed {
|
||||
look.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
|
||||
}
|
||||
let line = vectorcraft_geom::shapes::line((x, 40.0).into(), (x, 60.0).into());
|
||||
vectorcraft_doc::Node::path(d.alloc_id(), line, look)
|
||||
}
|
||||
|
||||
fn black() -> vectorcraft_color::Paint {
|
||||
vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK)
|
||||
}
|
||||
|
||||
/// A brushed path just left of a chosen artboard, whose brush art paints onto it, is in that
|
||||
/// artboard's SVG and SVGZ; a brushed path too far off for its brush art to reach it is not.
|
||||
#[test]
|
||||
fn a_chosen_artboard_s_svg_keeps_brush_art_reaching_in() {
|
||||
let (mut d, x0) = nib_doc();
|
||||
let layer = d.layers[0].id;
|
||||
let near = nib_line(&mut d, x0 - 5.0, black(), true);
|
||||
let far = nib_line(&mut d, x0 - 200.0, black(), true);
|
||||
let (near, far) = (d.insert(Some(layer), 0, near).unwrap(), d.insert(Some(layer), 0, far).unwrap());
|
||||
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
|
||||
assert!(kept.node(near).is_some(), "the nib paints 5 pt onto the artboard");
|
||||
assert!(kept.node(far).is_none(), "the nib paints 190 pt short of the artboard");
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg", "artboard": 0})).unwrap();
|
||||
let svg = svg["text"].as_str().unwrap().to_string();
|
||||
assert!(vectorcraft_testkit::svg_shapes(&svg) > 0, "{svg}");
|
||||
let svgz = s.execute("document.serialize", &json!({"format": "svgz", "artboard": 0})).unwrap();
|
||||
let svgz = vectorcraft_format::base64_decode(svgz["dataBase64"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(vectorcraft_svg::text_of(&svgz).unwrap(), svg, "the SVGZ is the SVG gzipped");
|
||||
}
|
||||
|
||||
/// The room for brush art also keeps a brushed path in a plain group on a sublayer. A brushed
|
||||
/// stroke without a paint draws no brush art, a clipping group's clip keeps its members' brush art
|
||||
/// inside it, and a compound path is painted with its own appearance, not its paths': those stay
|
||||
/// out when only brush art could reach the artboard.
|
||||
#[test]
|
||||
fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_art() {
|
||||
use vectorcraft_doc::{LayerColor, Node, NodeKind};
|
||||
let (mut d, x0) = nib_doc();
|
||||
let layer = d.layers[0].id;
|
||||
let x = x0 - 5.0;
|
||||
// A brushed line in a plain group on a sublayer.
|
||||
let line = nib_line(&mut d, x, black(), true);
|
||||
let nested = line.id;
|
||||
let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(line)], clip: false });
|
||||
let mut sublayer = Node::layer(d.alloc_id(), "Sublayer", LayerColor::Preset(1));
|
||||
sublayer.children_mut().unwrap().push(Arc::new(group));
|
||||
d.insert(Some(layer), 0, sublayer).unwrap();
|
||||
// A brushed stroke without a paint.
|
||||
let unpainted = nib_line(&mut d, x, vectorcraft_color::Paint::None, true);
|
||||
let unpainted = d.insert(Some(layer), 0, unpainted).unwrap();
|
||||
// A clipping group whose clip, far left of the artboard, holds a brushed line just off it.
|
||||
let mut clip = Node::path(
|
||||
d.alloc_id(),
|
||||
vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x0 - 100.0, 40.0, x0 - 90.0, 60.0)),
|
||||
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0),
|
||||
);
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let member = nib_line(&mut d, x, black(), true);
|
||||
let clipped = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(member)], clip: true });
|
||||
let clipped = d.insert(Some(layer), 0, clipped).unwrap();
|
||||
// Compound paths of a brushed line: plain itself, then brushed itself.
|
||||
let mut compounds = vec![];
|
||||
for own in [false, true] {
|
||||
let member = nib_line(&mut d, x, black(), true);
|
||||
let mut compound =
|
||||
Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: vectorcraft_geom::FillRule::NonZero });
|
||||
compound.appearance = nib_line(&mut d, x, black(), own).appearance;
|
||||
compounds.push(d.insert(Some(layer), 0, compound).unwrap());
|
||||
}
|
||||
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
|
||||
assert!(kept.node(nested).is_some(), "the brushed line in the group on the sublayer");
|
||||
assert!(kept.node(unpainted).is_none(), "a brushed stroke without a paint");
|
||||
assert!(kept.node(clipped).is_none(), "a clipping group whose clip misses the artboard");
|
||||
assert!(kept.node(compounds[0]).is_none(), "a compound path that is not brushed itself");
|
||||
assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself");
|
||||
}
|
||||
|
||||
/// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset)
|
||||
/// has the artboard's (or asset's) name as `<title>`; Save's SVG and Export for Screens' Full
|
||||
/// Document keep the document's.
|
||||
|
||||
@@ -62,6 +62,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
similar_fonts
|
||||
),
|
||||
cmd!(
|
||||
query "text.glyphCategories",
|
||||
"Glyph Categories",
|
||||
[],
|
||||
None,
|
||||
"{family, style?} the OpenType categories of the font's glyphs, what the Glyphs panel's Show menu lists after Alternates for Current Selection: from the font's GSUB table, the glyphs that the single, alternate, multiple and ligature substitutions of each kind's features give, each glyph once by id, in this order: `ligatures` (liga, dlig, hlig), `swashes` (swsh, cswh), `stylisticAlternates` (salt), `ss01` to `ss20`, `smallCaps` (smcp, c2sc), `ornaments` (ornm), `fractions` (frac, afrc, numr, dnom) and `figures` (lnum, onum, pnum, tnum); a kind without glyphs is left out; contextual lookups are not followed → {family, style, categories: [{id, name?: a stylistic set's name in the font, glyphs: [glyph id]}]} (style omitted: the family's first style; an error when the family or style isn't available)",
|
||||
always,
|
||||
glyph_categories
|
||||
),
|
||||
cmd!(
|
||||
"text.rescanFonts",
|
||||
"Refresh Font List",
|
||||
@@ -1176,6 +1185,44 @@ fn similar_fonts(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "family": family, "families": families }))
|
||||
}
|
||||
|
||||
/// `text.glyphCategories`: the OpenType categories of a font's glyphs
|
||||
/// ([`vectorcraft_text::FontFace::glyph_categories`]).
|
||||
fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.glyphCategories";
|
||||
let text = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(s)) => Ok(Some(s.as_str())),
|
||||
Some(_) => Err(bad(C, format!("`{key}` must be a string"))),
|
||||
};
|
||||
let family = text("family")?.ok_or_else(|| bad(C, "missing `family`"))?;
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
if !db.has_family(family) {
|
||||
return Err(bad(C, format!("font family `{family}` is not available")));
|
||||
}
|
||||
let styles = db.styles(family);
|
||||
let style = match text("style")? {
|
||||
Some(style) => styles
|
||||
.iter()
|
||||
.find(|s| s.eq_ignore_ascii_case(style))
|
||||
.cloned()
|
||||
.ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?,
|
||||
None => styles.first().cloned().unwrap_or_else(|| "Regular".into()),
|
||||
};
|
||||
let face = db.face(family, &style).ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?;
|
||||
let categories: Vec<Value> = face
|
||||
.glyph_categories()
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut v = json!({"id": c.kind.id(), "glyphs": c.glyphs});
|
||||
if let Some(name) = &c.name {
|
||||
v["name"] = json!(name);
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"family": face.family, "style": face.style, "categories": categories}))
|
||||
}
|
||||
|
||||
pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -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()))
|
||||
|
||||
@@ -698,6 +698,20 @@ fn clip_shape((frame, room): Clip) -> PathData {
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame)
|
||||
}
|
||||
|
||||
/// The clipping path an image's file draws it through, with the fill rule its clip group takes:
|
||||
/// a DCS file's (nonzero) or a PSD or PSB file's (even-odd).
|
||||
type FileClip = (PathData, FillRule);
|
||||
|
||||
/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it
|
||||
/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB
|
||||
/// file's ([`fileio::png_clip`]).
|
||||
fn file_clip(blob: &ImageBlob) -> Option<FileClip> {
|
||||
if let Some(path) = blob.separated_clip() {
|
||||
return Some((path, FillRule::NonZero));
|
||||
}
|
||||
(blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd))
|
||||
}
|
||||
|
||||
/// What happens to the clip of an object a link update remakes.
|
||||
enum ClipTo {
|
||||
/// It stays as it is.
|
||||
@@ -705,25 +719,25 @@ enum ClipTo {
|
||||
/// It is clipped to this path (Placement Options' clip): the clipping path of the clip group
|
||||
/// holding just it changes, else it goes into a new clip group.
|
||||
Path(PathData),
|
||||
/// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`],
|
||||
/// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group
|
||||
/// again.
|
||||
File(PathData),
|
||||
/// It is clipped to this path, the clipping path its file draws it through, under its fill
|
||||
/// rule: as [`ClipTo::Path`], except that a plain group holding just it (as [`ClipTo::Off`]
|
||||
/// leaves one) becomes a clip group again.
|
||||
File(FileClip),
|
||||
/// It goes into a new clip group of this path, inside the clip group that holds it.
|
||||
Nest(PathData),
|
||||
/// Placement Options clip it to `placement` while its DCS file draws it through `file`: it is
|
||||
Nest(FileClip),
|
||||
/// Placement Options clip it to `placement` while its file draws it through `file`: it is
|
||||
/// clipped to `file` as [`ClipTo::File`] clips it, and the clip group holding it is clipped to
|
||||
/// `placement` as [`ClipTo::Path`] clips an object. With no `file` (the new file lacks the
|
||||
/// clipping path of the clip group holding it), that group stays as [`ClipTo::Off`] leaves it,
|
||||
/// clipped to `placement`.
|
||||
Both { file: Option<PathData>, placement: PathData },
|
||||
/// Placement Options clip it to `placement` while its DCS file draws it through `file`, and the
|
||||
Both { file: Option<FileClip>, placement: PathData },
|
||||
/// Placement Options clip it to `placement` while its file draws it through `file`, and the
|
||||
/// clip group holding just it is not its old file's: that clip group's clipping path becomes
|
||||
/// `placement`, and it goes into a new clip group of `file` inside it.
|
||||
BothInside { file: PathData, placement: PathData },
|
||||
/// The clipping path of the clip group holding just it goes (a DCS file's clipping path that
|
||||
/// its new file lacks): the group stays as a plain group of it, with its id, name, visibility
|
||||
/// and transparency.
|
||||
BothInside { file: FileClip, placement: PathData },
|
||||
/// The clipping path of the clip group holding just it goes (its old file's clipping path,
|
||||
/// which its new file lacks): the group stays as a plain group of it, with its id, name,
|
||||
/// visibility and transparency.
|
||||
Off,
|
||||
}
|
||||
|
||||
@@ -756,25 +770,25 @@ fn same_path(a: &PathData, b: &PathData) -> bool {
|
||||
}
|
||||
|
||||
/// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with
|
||||
/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path a DCS file
|
||||
/// draws `img` through, the file's clip group inside the placement's. When neither clips it, a clip
|
||||
/// group holding just it whose clipping path `held` is its old DCS file's (`old_clip`, in the old
|
||||
/// pixels, under the nonzero rule its clip groups get) goes.
|
||||
/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path the file
|
||||
/// (DCS, PSD or PSB) draws `img` through, the file's clip group inside the placement's. When
|
||||
/// neither clips it, a clip group holding just it whose clipping path `held` is its old file's
|
||||
/// (`old_clip`, in the old pixels, under the fill rule its clip groups get) goes.
|
||||
fn clip_to(
|
||||
old_xf: Affine,
|
||||
old_clip: Option<&PathData>,
|
||||
old_clip: Option<&FileClip>,
|
||||
clip: Option<Clip>,
|
||||
img: &RasterImage,
|
||||
new_xf: Affine,
|
||||
held: Option<(&PathData, FillRule)>,
|
||||
) -> ClipTo {
|
||||
// Whether the clip group holding just the image is the old DCS file's: a clipping path whose
|
||||
// fill rule was changed in the document is not.
|
||||
// Whether the clip group holding just the image is the old file's: a clipping path whose fill
|
||||
// rule was changed in the document is not.
|
||||
let file_held = match (old_clip, held) {
|
||||
(Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held),
|
||||
(Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held),
|
||||
_ => false,
|
||||
};
|
||||
let file = img.clip.as_ref().map(|path| path.transformed(new_xf));
|
||||
let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule));
|
||||
if let Some(clip) = clip {
|
||||
let placement = clip_shape(clip);
|
||||
return match file {
|
||||
@@ -831,7 +845,7 @@ impl Nested<'_> {
|
||||
fn root(&mut self, n: &mut Arc<Node>) {
|
||||
if !(self.pick)(n) {
|
||||
if let Some(placement) = self.update(n, true) {
|
||||
*n = Arc::new(self.clip_group(Arc::clone(n), placement));
|
||||
*n = Arc::new(self.clip_group(Arc::clone(n), (placement, FillRule::NonZero)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -839,7 +853,8 @@ impl Nested<'_> {
|
||||
let mut new = Arc::new(new);
|
||||
let _ = self.update(&mut new, true);
|
||||
*n = match clip {
|
||||
ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)),
|
||||
ClipTo::Path(path) => Arc::new(self.clip_group(new, (path, FillRule::NonZero))),
|
||||
ClipTo::File(file) | ClipTo::Nest(file) => Arc::new(self.clip_group(new, file)),
|
||||
ClipTo::Both { file, placement } => self.clip_both(new, file, placement),
|
||||
ClipTo::BothInside { file, placement } => self.clip_both(new, Some(file), placement),
|
||||
ClipTo::Keep | ClipTo::Off => new,
|
||||
@@ -848,8 +863,8 @@ impl Nested<'_> {
|
||||
|
||||
/// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays
|
||||
/// the same node when none is there, and only the nodes on the way to one are copied. The
|
||||
/// result is Placement Options' clip that `n` itself, now the clip group of a DCS file's
|
||||
/// clipping path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes:
|
||||
/// result is Placement Options' clip that `n` itself, now the clip group of a file's clipping
|
||||
/// path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes:
|
||||
/// the clipping path of the clip group holding just `n` becomes it, else `n` goes into a new
|
||||
/// clip group of it.
|
||||
#[must_use]
|
||||
@@ -880,8 +895,8 @@ impl Nested<'_> {
|
||||
match (self.update(&mut new, nested), clip_path) {
|
||||
(None, _) if Arc::ptr_eq(&new, c) => {}
|
||||
(None, _) => slots.push((i, new)),
|
||||
(Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement)), (1, new)]),
|
||||
(Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, placement)))),
|
||||
(Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement, None)), (1, new)]),
|
||||
(Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, (placement, FillRule::NonZero))))),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -894,17 +909,22 @@ impl Nested<'_> {
|
||||
let _ = self.update(&mut new, true);
|
||||
match (clip, clip_path) {
|
||||
(ClipTo::Keep, _) => slots.push((i, new)),
|
||||
(ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip)), (1, new)]),
|
||||
(ClipTo::Path(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, None)), (1, new)]),
|
||||
(ClipTo::File((clip, rule)), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, Some(rule))), (1, new)]),
|
||||
(ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)),
|
||||
(ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => {
|
||||
(ClipTo::Path(clip), _) => {
|
||||
let group = self.clip_group(new, (clip, FillRule::NonZero));
|
||||
slots.push((i, Arc::new(group)));
|
||||
}
|
||||
(ClipTo::File(clip) | ClipTo::Nest(clip), _) => {
|
||||
let group = self.clip_group(new, clip);
|
||||
slots.push((i, Arc::new(group)));
|
||||
}
|
||||
(ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new),
|
||||
(ClipTo::Off, _) => slots.push((i, new)),
|
||||
// The file's clip group stays `n`, and the placement's clip goes around it.
|
||||
(ClipTo::Both { file: Some(file), placement }, Some(path)) if i == 1 => {
|
||||
slots.extend([(0, with_clip(path, file)), (1, new)]);
|
||||
(ClipTo::Both { file: Some((file, rule)), placement }, Some(path)) if i == 1 => {
|
||||
slots.extend([(0, with_clip(path, file, Some(rule))), (1, new)]);
|
||||
around = Some(placement);
|
||||
}
|
||||
(ClipTo::Both { file: Some(file), placement }, None) if plain => {
|
||||
@@ -917,7 +937,7 @@ impl Nested<'_> {
|
||||
}
|
||||
(ClipTo::BothInside { file, placement }, Some(path)) if i == 1 => {
|
||||
let group = self.clip_group(new, file);
|
||||
slots.extend([(0, with_clip(path, placement)), (1, Arc::new(group))]);
|
||||
slots.extend([(0, with_clip(path, placement, None)), (1, Arc::new(group))]);
|
||||
}
|
||||
(ClipTo::Both { file, placement }, _) => slots.push((i, self.clip_both(new, file, placement))),
|
||||
(ClipTo::BothInside { file, placement }, _) => slots.push((i, self.clip_both(new, Some(file), placement))),
|
||||
@@ -958,27 +978,28 @@ impl Nested<'_> {
|
||||
|
||||
/// A clip group of `placement` holding `object`, inside a clip group of `file` when there is a
|
||||
/// `file` ([`ClipTo::Both`] for an object no clip group holds yet).
|
||||
fn clip_both(&mut self, object: Arc<Node>, file: Option<PathData>, placement: PathData) -> Arc<Node> {
|
||||
fn clip_both(&mut self, object: Arc<Node>, file: Option<FileClip>, placement: PathData) -> Arc<Node> {
|
||||
let object = match file {
|
||||
Some(file) => Arc::new(self.clip_group(object, file)),
|
||||
None => object,
|
||||
};
|
||||
Arc::new(self.clip_group(object, placement))
|
||||
Arc::new(self.clip_group(object, (placement, FillRule::NonZero)))
|
||||
}
|
||||
|
||||
/// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers.
|
||||
fn clip_group(&mut self, object: Arc<Node>, clip: PathData) -> Node {
|
||||
/// A clip group of `object` clipped to `clip` under its fill rule, as [`new_clip_group`] makes
|
||||
/// one in the layers.
|
||||
fn clip_group(&mut self, object: Arc<Node>, clip: FileClip) -> Node {
|
||||
let path = self.clipping_path(clip);
|
||||
let group_id = NodeId(self.next);
|
||||
self.next += 1;
|
||||
Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true })
|
||||
}
|
||||
|
||||
/// A clipping path of `clip`, with the next node id.
|
||||
fn clipping_path(&mut self, clip: PathData) -> Node {
|
||||
/// A clipping path of `clip` under its fill rule, with the next node id.
|
||||
fn clipping_path(&mut self, (clip, rule): FileClip) -> Node {
|
||||
let id = NodeId(self.next);
|
||||
self.next += 1;
|
||||
clipping_path(id, clip)
|
||||
clipping_path(id, clip, rule)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1082,9 +1103,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n
|
||||
(frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room)))
|
||||
}
|
||||
|
||||
/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when
|
||||
/// no such clip group holds it.
|
||||
fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool {
|
||||
/// The clipping path of the clip group of `d` holding just object `id` becomes `path`, under fill
|
||||
/// rule `rule` when one is given; false when no such clip group holds it.
|
||||
fn set_clip_path(d: &mut Document, id: NodeId, path: PathData, rule: Option<FillRule>) -> bool {
|
||||
let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind {
|
||||
NodeKind::Group { children, clip: true } => match &children[..] {
|
||||
[c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id),
|
||||
@@ -1093,8 +1114,9 @@ fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool {
|
||||
_ => None,
|
||||
});
|
||||
let Some(c) = clip_path else { return false };
|
||||
if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) {
|
||||
if let Some(Node { kind: NodeKind::Path { path: p, rule: r, .. }, .. }) = d.node_mut(c) {
|
||||
*p = path;
|
||||
*r = rule.unwrap_or(*r);
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -1108,25 +1130,25 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> {
|
||||
/// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes,
|
||||
/// else it goes into a new clip group.
|
||||
fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
|
||||
if set_clip_path(d, id, path.clone()) {
|
||||
if set_clip_path(d, id, path.clone(), None) {
|
||||
return Ok(());
|
||||
}
|
||||
new_clip_group(d, id, path)
|
||||
new_clip_group(d, id, (path, FillRule::NonZero))
|
||||
}
|
||||
|
||||
/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping
|
||||
/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`]
|
||||
/// leaves one) becomes a clip group again, else it goes into a new clip group.
|
||||
fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
|
||||
if set_clip_path(d, id, path.clone()) {
|
||||
/// Clip object `id` of `d` to `path`, the clipping path its file draws it through, under its fill
|
||||
/// rule: the clipping path of the clip group holding just it changes, a plain group holding just it
|
||||
/// (as [`unclip`] leaves one) becomes a clip group again, else it goes into a new clip group.
|
||||
fn clip_file_to(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> {
|
||||
if set_clip_path(d, id, path.clone(), Some(rule)) {
|
||||
return Ok(());
|
||||
}
|
||||
let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) {
|
||||
Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id),
|
||||
_ => false,
|
||||
});
|
||||
let Some(g) = plain else { return new_clip_group(d, id, path) };
|
||||
let clip = clipping_path(d.alloc_id(), path);
|
||||
let Some(g) = plain else { return new_clip_group(d, id, (path, rule)) };
|
||||
let clip = clipping_path(d.alloc_id(), path, rule);
|
||||
d.insert(Some(g), 0, clip)?;
|
||||
if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) {
|
||||
*clip = true;
|
||||
@@ -1134,30 +1156,33 @@ fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clipping path `path` (a node) with its path changed to `clip`.
|
||||
fn with_clip(path: &Node, clip: PathData) -> Arc<Node> {
|
||||
/// Clipping path `path` (a node) with its path changed to `clip`, and its fill rule to `rule` when
|
||||
/// one is given.
|
||||
fn with_clip(path: &Node, clip: PathData, rule: Option<FillRule>) -> Arc<Node> {
|
||||
let mut path = Node::clone(path);
|
||||
if let NodeKind::Path { path: p, .. } = &mut path.kind {
|
||||
if let NodeKind::Path { path: p, rule: r, .. } = &mut path.kind {
|
||||
*p = clip;
|
||||
*r = rule.unwrap_or(*r);
|
||||
}
|
||||
Arc::new(path)
|
||||
}
|
||||
|
||||
/// A clipping path `id` of `path`, unpainted.
|
||||
fn clipping_path(id: NodeId, path: PathData) -> Node {
|
||||
/// A clipping path `id` of `path` under fill rule `rule`, unpainted.
|
||||
fn clipping_path(id: NodeId, path: PathData, rule: FillRule) -> Node {
|
||||
let none = vectorcraft_color::Paint::None;
|
||||
let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
*r = rule;
|
||||
}
|
||||
clip
|
||||
}
|
||||
|
||||
/// Put object `id` of `d` into a new clip group of `path`, where it is.
|
||||
fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
|
||||
/// Put object `id` of `d` into a new clip group of `path`, under its fill rule, where it is.
|
||||
fn new_clip_group(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> {
|
||||
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
let image = d.remove(id)?;
|
||||
let clip = clipping_path(d.alloc_id(), path);
|
||||
let clip = clipping_path(d.alloc_id(), path, rule);
|
||||
let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true });
|
||||
d.insert(par, index, group)?;
|
||||
Ok(())
|
||||
@@ -1186,15 +1211,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
let nested = nested_ids(d, ids);
|
||||
if also.is_some() || !nested.is_empty() {
|
||||
let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false)));
|
||||
// The resolution of each content the images picked show, and the clipping path its DCS file
|
||||
// The resolution of each content the images picked show, and the clipping path its file
|
||||
// drew it through, looked up once each.
|
||||
let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new();
|
||||
let mut old: BTreeMap<String, ((f64, f64), Option<FileClip>)> = BTreeMap::new();
|
||||
d.visit_stored(|n, _| {
|
||||
if let NodeKind::Image(im) = &n.kind
|
||||
&& pick(n)
|
||||
&& !old.contains_key(&im.key)
|
||||
{
|
||||
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip)));
|
||||
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(file_clip)));
|
||||
}
|
||||
});
|
||||
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
|
||||
@@ -1220,8 +1245,9 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o);
|
||||
// Placement Options' clip, else a DCS file's clipping path, read again with its plates.
|
||||
let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip);
|
||||
// Placement Options' clip, else the clipping path of a DCS file (read again with its
|
||||
// plates) or of a PSD or PSB file.
|
||||
let old_clip = d.images.get(&im.key).and_then(file_clip);
|
||||
clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id))));
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
@@ -1235,8 +1261,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
|
||||
clips.into_iter().try_for_each(|(id, clip)| match clip {
|
||||
ClipTo::Keep => Ok(()),
|
||||
ClipTo::Path(path) => clip_image_to(d, id, path),
|
||||
ClipTo::File(path) => clip_file_to(d, id, path),
|
||||
ClipTo::Nest(path) => new_clip_group(d, id, path),
|
||||
ClipTo::File(file) => clip_file_to(d, id, file),
|
||||
ClipTo::Nest(file) => new_clip_group(d, id, file),
|
||||
ClipTo::Off => unclip(d, id),
|
||||
ClipTo::Both { file, placement } => {
|
||||
match file {
|
||||
|
||||
@@ -38,7 +38,7 @@ pub use commands::specs;
|
||||
pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip};
|
||||
pub(crate) use pixelgrid::{
|
||||
align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap,
|
||||
snap_if_aligned,
|
||||
snap_if_aligned, snap_symbol_art,
|
||||
};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that
|
||||
//! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>).
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>),
|
||||
//! and Symbol Options › Align to Pixel Grid, which keeps a symbol's instances on the pixel grid.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
|
||||
|
||||
@@ -150,10 +153,234 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) {
|
||||
keep_pixel_aligned(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
refresh_symbols(before, doc);
|
||||
}
|
||||
|
||||
/// How far the linear part of an instance's transform may be from its symbol's natural size, as a
|
||||
/// fraction of that size, for the instance to count as placed at actual size.
|
||||
const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// After any edit: Symbol Options › Align to Pixel Grid. The art of a pixel-aligned symbol snaps to
|
||||
/// the pixel grid at the symbol's natural size ([`snap_symbol_art`]) when the symbol becomes
|
||||
/// pixel-aligned, when its art or natural size changes, and when symbol editing mode for it ends
|
||||
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
|
||||
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
|
||||
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
|
||||
/// An instance in another symbol's art is placed by that symbol's instances and is left as it is.
|
||||
/// A document without pixel-aligned symbols is not walked.
|
||||
fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let was = before.pixel_aligned_symbols();
|
||||
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let mut every = false;
|
||||
for name in &aligned {
|
||||
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
let art_now = doc.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
let art_changed = match (art_before, art_now) {
|
||||
(Some(b), Some(a)) => !Arc::ptr_eq(b, a),
|
||||
_ => true,
|
||||
};
|
||||
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
|
||||
if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed {
|
||||
snap_symbol_art(doc, name);
|
||||
every = true;
|
||||
}
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
if every {
|
||||
for layer in doc.layers.iter_mut() {
|
||||
if holds_instance(layer, &natural) {
|
||||
snap_instances_in(Arc::make_mut(layer), &natural);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (mut ids, mut masked) = (vec![], vec![]);
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
for id in ids {
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
snap_instance(n, &natural);
|
||||
}
|
||||
}
|
||||
for id in masked {
|
||||
if let Some(m) = doc.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) {
|
||||
snap_instances_in(Arc::make_mut(&mut m.art), &natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Among the objects of `after` that differ from their counterparts in `before` (or are new), in
|
||||
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
|
||||
/// mask art holds such instances (`masked`).
|
||||
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
|
||||
masked.push(a.id);
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &a.kind {
|
||||
if natural.contains_key(symbol) {
|
||||
ids.push(a.id);
|
||||
}
|
||||
} else if let Some(children) = a.children() {
|
||||
changed_instances(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, natural, ids, masked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n`, an object in it or the art of an opacity mask in it is an instance of a symbol in
|
||||
/// `natural`.
|
||||
fn holds_instance(n: &Node, natural: &HashMap<String, Affine>) -> bool {
|
||||
matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if natural.contains_key(symbol))
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_instance(c, natural)))
|
||||
}
|
||||
|
||||
/// [`snap_instance`] on every instance of a symbol in `natural` in `n`, the art of its opacity
|
||||
/// masks included. Only what holds such an instance is copied for editing.
|
||||
fn snap_instances_in(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
snap_instance(n, natural);
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& holds_instance(&m.art, natural)
|
||||
{
|
||||
snap_instances_in(Arc::make_mut(&mut m.art), natural);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if holds_instance(c, natural) {
|
||||
snap_instances_in(Arc::make_mut(c), natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Snap the art of pixel-aligned symbol `name` to the pixel grid as it is drawn at the symbol's
|
||||
/// natural size: each path and compound path in it snaps as a pixel-aligned object does
|
||||
/// ([`snap_object`]), measured from the symbol's origin. The art is stored again only when
|
||||
/// something in it moved, and the answer says whether it did.
|
||||
pub(crate) fn snap_symbol_art(doc: &mut Document, name: &str) -> bool {
|
||||
let natural = doc.symbol_natural_xf(name);
|
||||
let det = natural.determinant();
|
||||
if !det.is_finite() || det.abs() < 1e-18 {
|
||||
return false;
|
||||
}
|
||||
let Some(sym) = doc.symbols.iter_mut().find(|s| s.name == name) else { return false };
|
||||
// Instances draw the art's strokes at their stored width, and the art of unlinked opacity
|
||||
// masks, which `Node::transform` leaves alone, at the natural size too.
|
||||
let mut art = (*sym.art).clone();
|
||||
art.transform(natural, false);
|
||||
transform_unlinked_masks(&mut art, natural);
|
||||
if !snap_art(&mut art) {
|
||||
return false;
|
||||
}
|
||||
let inverse = natural.inverse();
|
||||
art.transform(inverse, false);
|
||||
transform_unlinked_masks(&mut art, inverse);
|
||||
sym.art = Arc::new(art);
|
||||
true
|
||||
}
|
||||
|
||||
/// Transform the art of every unlinked opacity mask in `n` by `xf`, in the art of other masks
|
||||
/// too. Only what holds such a mask is copied for editing.
|
||||
fn transform_unlinked_masks(n: &mut Node, xf: Affine) {
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& holds_unlinked_mask(&m.art, !m.linked)
|
||||
{
|
||||
let linked = m.linked;
|
||||
let art = Arc::make_mut(&mut m.art);
|
||||
if !linked {
|
||||
art.transform(xf, false);
|
||||
}
|
||||
transform_unlinked_masks(art, xf);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if holds_unlinked_mask(c, false) {
|
||||
transform_unlinked_masks(Arc::make_mut(c), xf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` is the art of an unlinked mask (`unlinked`), or it or an object in it, in the art of
|
||||
/// its masks too, has an unlinked opacity mask.
|
||||
fn holds_unlinked_mask(n: &Node, unlinked: bool) -> bool {
|
||||
unlinked
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| holds_unlinked_mask(&m.art, !m.linked))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_unlinked_mask(c, false)))
|
||||
}
|
||||
|
||||
/// Snap every path and compound path in `n` ([`can_align`]) with [`snap_object`], the art of
|
||||
/// opacity masks included (those of a compound path's paths too). Returns whether anything
|
||||
/// changed.
|
||||
fn snap_art(n: &mut Node) -> bool {
|
||||
let mut moved = false;
|
||||
if can_align(n) {
|
||||
let was = n.clone();
|
||||
snap_object(n, Scaling::default());
|
||||
moved = *n != was;
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.extras().mask.is_some() {
|
||||
moved |= snap_mask(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
moved |= snap_art(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
// After the object itself, which a linked mask follows.
|
||||
snap_mask(n) || moved
|
||||
}
|
||||
|
||||
/// [`snap_art`] on the art of `n`'s opacity mask. Returns whether anything changed.
|
||||
fn snap_mask(n: &mut Node) -> bool {
|
||||
let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) else { return false };
|
||||
let mut art = (*m.art).clone();
|
||||
if !snap_art(&mut art) {
|
||||
return false;
|
||||
}
|
||||
m.art = Arc::new(art);
|
||||
true
|
||||
}
|
||||
|
||||
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
|
||||
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
|
||||
/// rotated (a half turn included) or sheared instance stays where it is.
|
||||
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return };
|
||||
let Some(nat) = natural.get(symbol.as_str()) else { return };
|
||||
let [a, b, c, d, e, f] = xf.as_coeffs();
|
||||
let [na, _, _, nd, _, _] = nat.as_coeffs();
|
||||
let near = |v: f64, to: f64| (v.abs() - to.abs()).abs() <= ACTUAL_SIZE_TOLERANCE * to.abs().max(1.0);
|
||||
let actual =
|
||||
near(a, na) && near(d, nd) && b.abs() <= ACTUAL_SIZE_TOLERANCE * na.abs().max(1.0) && c.abs() <= ACTUAL_SIZE_TOLERANCE * nd.abs().max(1.0);
|
||||
// Flipped along both axes is a half turn, which counts as rotated.
|
||||
let half_turn = a * na < 0.0 && d * nd < 0.0;
|
||||
if !actual || half_turn || !e.is_finite() || !f.is_finite() {
|
||||
return;
|
||||
}
|
||||
let (x, y) = (e.round(), f.round());
|
||||
if x != e || y != f {
|
||||
*xf = Affine::new([a, b, c, d, x, y]);
|
||||
}
|
||||
}
|
||||
|
||||
/// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the
|
||||
/// pixel-aligned objects in them to the pixel grid again.
|
||||
/// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid
|
||||
/// again.
|
||||
pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
if doc.node(*id).is_some_and(holds_aligned)
|
||||
@@ -162,6 +389,18 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
keep_pixel_aligned(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
for id in ids {
|
||||
if doc.node(*id).is_some_and(|n| holds_instance(n, &natural))
|
||||
&& let Some(n) = doc.node_mut(*id)
|
||||
{
|
||||
snap_instances_in(n, &natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects of `after` that differ from their counterparts in `before` (or are new) and are
|
||||
|
||||
@@ -306,7 +306,7 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
|
||||
let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes));
|
||||
let mut warnings: Vec<String> = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect();
|
||||
*slices_out = psd_slices(slices_from, natural, &mut warnings);
|
||||
let clip = fileio::psdread::clipping_path(&src.bytes);
|
||||
let clip = img.clip.clone().map(|(path, _)| path);
|
||||
return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None });
|
||||
}
|
||||
if pdf {
|
||||
|
||||
@@ -104,6 +104,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result<DcsArt> {
|
||||
};
|
||||
let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref())
|
||||
.ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?;
|
||||
let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero));
|
||||
let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip };
|
||||
let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect();
|
||||
Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings })
|
||||
|
||||
@@ -624,6 +624,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"text.fonts",
|
||||
"text.getRange",
|
||||
"text.glyphAlternates",
|
||||
"text.glyphCategories",
|
||||
"text.insertInline",
|
||||
"text.missingFonts",
|
||||
"text.replaceFont",
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Randomize Colors",
|
||||
[],
|
||||
None,
|
||||
"{map: rows as recolor.apply, order?: true (shuffle the new colours among the rows that aren't excluded), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}",
|
||||
"{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}",
|
||||
always,
|
||||
randomize
|
||||
),
|
||||
@@ -1746,8 +1746,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?);
|
||||
let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?);
|
||||
// Each new color with its row's tint and model: a tint moves with its color, and goes when
|
||||
// the color changes; a model moves with its color.
|
||||
let mut news: Vec<(Color, f32, Option<ModelRule>)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect();
|
||||
// the color changes; a model moves with its color. A row with no current colors recolors
|
||||
// nothing, so it keeps its new color and takes no other row's.
|
||||
let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some();
|
||||
let mut news: Vec<(Color, f32, Option<ModelRule>)> =
|
||||
rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect();
|
||||
if order {
|
||||
rng.shuffle(&mut news);
|
||||
}
|
||||
@@ -1765,7 +1768,7 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let (to, tint, model) =
|
||||
if r.new_color().is_some() { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) };
|
||||
if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) };
|
||||
let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::<Vec<_>>(), "to": to.as_ref().map(key_str)});
|
||||
if r.exclude {
|
||||
row["exclude"] = json!(true);
|
||||
|
||||
@@ -529,6 +529,24 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
|
||||
};
|
||||
d.symbols[index].art = Arc::new(new_art);
|
||||
follow_objects(d, &se.symbol, (&old, old_group), (&art, group));
|
||||
// A pixel-aligned symbol stores its art on the pixel grid while it is edited too, and the
|
||||
// editing layer shows the snapped art.
|
||||
if d.symbol_pixel_aligned(&se.symbol) && super::object::snap_symbol_art(d, &se.symbol) {
|
||||
let stored = &d.symbols[index].art;
|
||||
let snapped: Vec<Arc<Node>> = if group { stored.children().map(|c| c.to_vec()).unwrap_or_default() } else { vec![stored.clone()] };
|
||||
let mut snapped = snapped.into_iter().map(|n| {
|
||||
let mut n = (*n).clone();
|
||||
n.transform(se.xf, false);
|
||||
Arc::new(n)
|
||||
});
|
||||
if let Some(ch) = d.node_mut(se.layer).and_then(Node::children_mut) {
|
||||
for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) {
|
||||
if let Some(n) = snapped.next() {
|
||||
*c = n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(e) = d.symbol_edit.as_mut() {
|
||||
e.changed = true;
|
||||
e.group = group;
|
||||
|
||||
@@ -499,12 +499,13 @@ fn instance(name: &str) -> Node {
|
||||
}
|
||||
|
||||
/// Symbol `from`'s Symbol Options in `src` (natural size, registration, export type, 9-slice
|
||||
/// guides) given to symbol `to` of `d`.
|
||||
/// guides, Align to Pixel Grid) given to symbol `to` of `d`.
|
||||
fn copy_options(src: &Document, from: &str, d: &mut Document, to: &str) {
|
||||
set_natural_size(d, to, Some(natural_size(src, from)));
|
||||
d.set_symbol_registration(to, src.symbol_registration(from));
|
||||
d.set_symbol_export_type(to, src.symbol_export_type(from));
|
||||
d.set_symbol_nine_slice(to, src.symbol_nine_slice(from));
|
||||
d.set_symbol_pixel_aligned(to, src.symbol_pixel_aligned(from));
|
||||
}
|
||||
|
||||
fn builtin_info(b: &BuiltinSymbolLibrary) -> LibraryInfo {
|
||||
|
||||
@@ -179,6 +179,9 @@ pub struct Session {
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
/// The folder of File Info's metadata templates; `None`: no folder
|
||||
/// ([`Session::attach_metadata_templates_dir`]).
|
||||
metadata_templates_dir: Option<std::path::PathBuf>,
|
||||
/// The folder of the New Document profiles `file.new` starts documents from; `None`: none,
|
||||
/// every document starts with the defaults ([`Session::attach_new_doc_profiles`]).
|
||||
new_doc_profile_dir: Option<std::path::PathBuf>,
|
||||
|
||||
@@ -2012,7 +2012,11 @@ impl Session {
|
||||
Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => {
|
||||
let n = job.host.dialogs.unused();
|
||||
let kind = LimitKind::Host;
|
||||
let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" });
|
||||
let message = if n == 1 {
|
||||
format!("`answers` has {n} answer the script did not use")
|
||||
} else {
|
||||
format!("`answers` has {n} answers the script did not use")
|
||||
};
|
||||
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 }))
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => {
|
||||
|
||||
@@ -93,6 +93,7 @@ impl Session {
|
||||
color_settings_file: None,
|
||||
plugin_dir: None,
|
||||
scripts_dir: None,
|
||||
metadata_templates_dir: None,
|
||||
new_doc_profile_dir: None,
|
||||
plugin_output: None,
|
||||
plugin_install_approval: None,
|
||||
|
||||
@@ -3310,6 +3310,85 @@ fn flare_ring_seed_moves_only_the_rings() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew.
|
||||
#[test]
|
||||
fn ellipse_with_four_anchors_is_the_live_ellipse() {
|
||||
let mut s = session();
|
||||
let draw = |s: &mut Session, extra: Option<u64>| {
|
||||
let mut p = json!({"x": 40, "y": 30, "width": 120, "height": 80});
|
||||
if let Some(n) = extra {
|
||||
p["anchors"] = json!(n);
|
||||
}
|
||||
let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap());
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
};
|
||||
let (plain, four) = (draw(&mut s, None), draw(&mut s, Some(4)));
|
||||
for n in [&plain, &four] {
|
||||
assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape());
|
||||
assert_eq!(n.path_data().unwrap().anchor_count(), 4);
|
||||
}
|
||||
assert_eq!(plain.path_data(), four.path_data());
|
||||
assert_eq!(plain.live_shape(), four.live_shape());
|
||||
}
|
||||
|
||||
/// Any other count draws a closed plain path of that many smooth anchors on the ellipse, its
|
||||
/// bounds the typed size, as one undo step.
|
||||
#[test]
|
||||
fn ellipse_anchors_draw_that_many_anchors_on_the_ellipse() {
|
||||
let mut s = session();
|
||||
let (x, y, w, h) = (40.0, 30.0, 120.0, 80.0);
|
||||
let (c, rx, ry) = (Point::new(x + w / 2.0, y + h / 2.0), w / 2.0, h / 2.0);
|
||||
for n in [2u64, 3, 5, 6, 8] {
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": n})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{n}: one undo step");
|
||||
let node = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(node.live_shape().is_none(), "{n}: a plain path");
|
||||
let path = node.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
let sp = &path.subpaths[0];
|
||||
assert!(sp.closed, "{n}");
|
||||
assert_eq!(sp.anchors.len() as u64, n);
|
||||
for a in &sp.anchors {
|
||||
assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth, "{n}");
|
||||
let on = ((a.p.x - c.x) / rx).powi(2) + ((a.p.y - c.y) / ry).powi(2);
|
||||
assert!((on - 1.0).abs() < 0.01, "{n}: {:?} is off the ellipse ({on})", a.p);
|
||||
}
|
||||
let b = path.bounds().unwrap();
|
||||
for (got, want) in [(b.x0, x), (b.y0, y), (b.x1, x + w), (b.y1, y + h)] {
|
||||
assert!((got - want).abs() < 1e-6, "{n}: bounds {b:?}");
|
||||
}
|
||||
}
|
||||
// The first anchor is the left one, and they run clockwise on screen, as the live ellipse's do.
|
||||
let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": 8})).unwrap()["id"].as_u64().unwrap());
|
||||
let sp = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone();
|
||||
assert!(sp.anchors[0].p.distance(Point::new(x, c.y)) < 1e-6, "{:?}", sp.anchors[0].p);
|
||||
assert!(sp.anchors[2].p.distance(Point::new(c.x, y)) < 1e-6, "{:?}", sp.anchors[2].p);
|
||||
}
|
||||
|
||||
/// An `anchors` that is not a whole number from 2 to 1000 is refused, and nothing is drawn.
|
||||
#[test]
|
||||
fn ellipse_refuses_a_bad_anchor_count() {
|
||||
let mut s = session();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let range = |got: &str| format!("`anchors` must be a whole number between 2 and 1000 (got {got})");
|
||||
for (bad, want) in [
|
||||
(json!(0), range("0")),
|
||||
(json!(1), range("1")),
|
||||
(json!(2.5), range("2.5")),
|
||||
(json!(-3), range("-3")),
|
||||
(json!(1001), range("1001")),
|
||||
(json!("x"), "`anchors` must be a number, not \"x\"".to_string()),
|
||||
(json!("6"), "`anchors` must be a number, not \"6\"".to_string()),
|
||||
(json!(true), "`anchors` must be a number, not true".to_string()),
|
||||
] {
|
||||
let e = s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50, "anchors": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains(&want), "{bad}: {e}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(s.doc().unwrap().doc.layers[0].children().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// Through the session, Ctrl/Cmd in the Flare tool's center drag keeps the center's size while the
|
||||
/// drag sizes the halo, and the flare drawn keeps both.
|
||||
#[test]
|
||||
|
||||
@@ -4272,15 +4272,26 @@ fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() {
|
||||
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
|
||||
}
|
||||
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
|
||||
// `through` takes edge ids, with scope "connected" only.
|
||||
// `through` takes the group's edge ids, each once, with scope "connected" only; a face's id, an
|
||||
// unknown id or an edge given twice is refused and changes nothing.
|
||||
let face = vectorcraft_tools::builder::faces(&node(&s, g)).first().map(|f| f.id).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
for p in [
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}),
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}),
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}),
|
||||
json!({"group": g.0, "point": [15, 50], "through": []}),
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [face.0]}),
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [999_999_999]}),
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0, middle[1].0]}),
|
||||
] {
|
||||
assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
|
||||
let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0]})).unwrap();
|
||||
assert_eq!(r["count"], 3, "an edge of the group is taken");
|
||||
}
|
||||
|
||||
/// A double-click whose second press lands on the next joined edge and is released back on the
|
||||
@@ -4318,6 +4329,32 @@ fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joi
|
||||
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
|
||||
}
|
||||
|
||||
/// With Paint Fills and Paint Strokes both on, a double-click on an edge after a click that filled
|
||||
/// a face whose fill was the edge's stroke paint paints the joined edges: the face is not sent as
|
||||
/// an edge to join through.
|
||||
#[test]
|
||||
fn live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0]);
|
||||
let [a, b] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0)])[..] else { panic!("two faces") };
|
||||
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
|
||||
paint_parts(&mut s, &all, &black, &[(a, black.clone()), (b, black.clone())]);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.set_tool_option("paintStrokes", &json!(true));
|
||||
s.paint.fill = green.clone();
|
||||
s.paint.stroke = green.clone();
|
||||
for (kind, x) in [(PointerKind::Down, 25.0), (PointerKind::Up, 25.0), (PointerKind::Down, 50.0), (PointerKind::Up, 50.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!(fill_of(&s, a), green, "the first click fills the face");
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 50.0, 25.0), v).unwrap();
|
||||
assert!(all.iter().all(|e| node(&s, *e).appearance.stroke_paint() == green), "every joined edge is painted");
|
||||
assert_eq!(fill_of(&s, b), black);
|
||||
}
|
||||
|
||||
/// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches
|
||||
/// the fill the face had before the first click: the lent press counts as one that paints nothing.
|
||||
#[test]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -253,6 +253,25 @@ fn constrain_angle_turns_shapes_made_by_a_click() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An ellipse of another anchor count made by a click turns along the Constrain Angle like the
|
||||
/// live ellipse: it keeps its anchors and its box runs along the turned axes from the click.
|
||||
#[test]
|
||||
fn constrain_angle_turns_an_ellipse_of_six_anchors_made_by_a_click() {
|
||||
let mut s = new_doc();
|
||||
set_angle(&mut s, 90.0);
|
||||
let p = json!({"x": 10, "y": 200, "width": 100, "height": 50, "anchors": 6});
|
||||
let p = constrain_click(&s, "shape.ellipse", p.clone(), corner(&p));
|
||||
assert_eq!(p["anchors"], json!(6));
|
||||
let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(n.live_shape().is_none());
|
||||
assert_eq!(n.path_data().unwrap().anchor_count(), 6);
|
||||
let b = bounds(&s, id);
|
||||
for (got, want) in [(b.x0, 10.0), (b.y0, 100.0), (b.x1, 60.0), (b.y1, 200.0)] {
|
||||
assert!(close(got, want), "{b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Line Segment tool's Shift steps of 45° count from the Constrain Angle.
|
||||
#[test]
|
||||
fn constrain_angle_steps_the_line_segment_tool() {
|
||||
|
||||
@@ -265,6 +265,26 @@ fn liquify_without_selection_hits_paths_under_the_brush() {
|
||||
assert!(path(&s, b).bounds().unwrap().width() < 100.0);
|
||||
}
|
||||
|
||||
/// The warning about objects under the brush that Liquify leaves as they are names their count
|
||||
/// with the matching noun and verb.
|
||||
#[test]
|
||||
fn liquify_warns_about_one_or_several_skipped_objects() {
|
||||
let mut s = session();
|
||||
let text =
|
||||
|s: &mut Session, x: i32| s.execute("text.create", &json!({"x": x, "y": 460, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap();
|
||||
let pucker = json!({"tool": "pucker", "points": [[550, 450]], "diameter": 150, "intensity": 1});
|
||||
let first = text(&mut s, 520);
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
let r = s.execute("object.liquify", &pucker).unwrap();
|
||||
assert_eq!(r["skipped"], json!([first]));
|
||||
assert_eq!(r["warning"], "Pucker left 1 object under the brush as it was (type): it reshapes paths only");
|
||||
let second = text(&mut s, 560);
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
let r = s.execute("object.liquify", &pucker).unwrap();
|
||||
assert_eq!(r["skipped"], json!([first, second]));
|
||||
assert_eq!(r["warning"], "Pucker left 2 objects under the brush as they were (type): it reshapes paths only");
|
||||
}
|
||||
|
||||
/// With nothing selected, a stroke leaves the art on a locked artboard as it is.
|
||||
#[test]
|
||||
fn liquify_without_selection_leaves_the_art_on_a_locked_artboard() {
|
||||
|
||||
@@ -1337,6 +1337,84 @@ fn eraser_removes_small_shape_entirely() {
|
||||
assert!(paths(&s).is_empty());
|
||||
}
|
||||
|
||||
/// `path.eraseRegion {rect}` (the Eraser's Alt-drag marquee) erases everything inside the
|
||||
/// rectangle: a closed shape loses its area, an open path is cut where it crosses the edges, a
|
||||
/// shape wholly inside goes, and only the selected paths take part when something is selected. One
|
||||
/// undo step puts everything back, and a rectangle that touches nothing adds no undo step.
|
||||
#[test]
|
||||
fn erase_region_rect_erases_everything_inside_it() {
|
||||
let filled = |s: &Session, x: f64, y: f64| {
|
||||
paths(s).iter().any(|(_, pd)| pd.is_closed() && vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)))
|
||||
};
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
rect(&mut s, 180.0, 140.0, 10.0, 10.0);
|
||||
line(&mut s, 50.0, 150.0, 350.0, 150.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let undo = undo_steps(&s);
|
||||
let r = s.execute("path.eraseRegion", &json!({"rect": [150, 120, 100, 60]})).unwrap();
|
||||
assert!(!r["ids"].as_array().unwrap().is_empty(), "{r}");
|
||||
assert_eq!(undo_steps(&s), undo + 1);
|
||||
assert!(!filled(&s, 200.0, 150.0) && !filled(&s, 185.0, 145.0), "the area inside is erased, the small square with it");
|
||||
assert!(filled(&s, 120.0, 150.0) && filled(&s, 200.0, 250.0) && filled(&s, 200.0, 110.0), "the rest stays filled");
|
||||
let ps = paths(&s);
|
||||
assert_eq!(ps.iter().filter(|(_, pd)| pd.is_closed()).count(), 1, "the square keeps the rectangle as a hole: {ps:?}");
|
||||
let open: Vec<f64> = ps.iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect();
|
||||
assert_eq!(open.len(), 2, "the line is cut in two: {open:?}");
|
||||
assert!(open.iter().all(|l| (l - 100.0).abs() < 0.01), "{open:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(paths(&s).len(), 3);
|
||||
assert!(filled(&s, 200.0, 160.0) && filled(&s, 185.0, 145.0));
|
||||
// A rectangle away from the art erases nothing and adds no undo step.
|
||||
let undo = undo_steps(&s);
|
||||
assert_eq!(s.execute("path.eraseRegion", &json!({"rect": [500, 500, 10, 10]})).unwrap(), json!({"ids": []}));
|
||||
assert_eq!(undo_steps(&s), undo);
|
||||
// With the line selected, only the line is erased.
|
||||
let ln = paths(&s).into_iter().find(|(_, pd)| !pd.is_closed()).unwrap().0;
|
||||
s.execute("select.set", &json!({"ids": [ln.0]})).unwrap();
|
||||
let closed: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect();
|
||||
s.execute("path.eraseRegion", &json!({"rect": [90, 100, 30, 100]})).unwrap();
|
||||
let after: Vec<PathData> = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect();
|
||||
assert_eq!(after, closed, "the unselected squares are unchanged");
|
||||
let open: Vec<f64> = paths(&s).iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect();
|
||||
assert_eq!(open.len(), 2);
|
||||
assert!((open.iter().sum::<f64>() - 270.0).abs() < 0.01, "{open:?}");
|
||||
}
|
||||
|
||||
/// A narrow `path.eraseRegion {rect}` across a long open path cuts it, wherever the rectangle
|
||||
/// falls between the samples the path's length would give.
|
||||
#[test]
|
||||
fn erase_region_rect_cuts_a_long_line_with_a_narrow_rectangle() {
|
||||
let mut s = session();
|
||||
line(&mut s, 0.0, 100.0, 10000.0, 100.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("path.eraseRegion", &json!({"rect": [5000.3, 90, 1, 20]})).unwrap();
|
||||
let mut open: Vec<f64> = paths(&s).iter().map(|(_, pd)| pd.length()).collect();
|
||||
open.sort_by(f64::total_cmp);
|
||||
assert_eq!(open.len(), 2, "{open:?}");
|
||||
assert!((open[0] - 4998.7).abs() < 0.01 && (open[1] - 5000.3).abs() < 0.01, "{open:?}");
|
||||
}
|
||||
|
||||
/// `path.eraseRegion` refuses a `rect` that is not four finite numbers with a width and a height
|
||||
/// above 0, and `rect` given with `points`, and changes nothing.
|
||||
#[test]
|
||||
fn erase_region_rect_refuses_bad_values() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let shape = "rect is [x, y, width, height] in points, with a width and a height above 0";
|
||||
for p in [
|
||||
json!({"rect": [10, 10, 0, 20]}),
|
||||
json!({"rect": [10, 10, 20, -5]}),
|
||||
json!({"rect": [10, 10, 20]}),
|
||||
json!({"rect": [10, "10", 20, 20]}),
|
||||
json!({"rect": [1e308, 0, 1e308, 20]}),
|
||||
json!({"rect": {"x": 10, "y": 10, "width": 20, "height": 20}}),
|
||||
] {
|
||||
refuses_with(&mut s, "path.eraseRegion", &p, shape);
|
||||
}
|
||||
refuses_with(&mut s, "path.eraseRegion", &json!({"rect": [10, 10, 20, 20], "points": [[0, 0]]}), "give `points` or `rect`, not both");
|
||||
}
|
||||
|
||||
/// #4495: the Eraser cuts a compound path as one shape: its hole stays empty, the erased area is
|
||||
/// empty, and the rest stays filled, with either fill rule. A notch inside the ring keeps one
|
||||
/// compound path; a drag through the whole ring leaves compound paths whose holes stay holes.
|
||||
|
||||
@@ -582,3 +582,233 @@ fn an_untitled_document_saved_to_a_file_exports_titled_after_it() {
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A session whose metadata templates folder is `dir/Metadata Templates`, with a document titled
|
||||
/// Poster.
|
||||
fn template_session(dir: &std::path::Path) -> Session {
|
||||
let mut s = session();
|
||||
s.attach_metadata_templates_dir(dir.join("Metadata Templates"));
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_metadata_template_is_listed_and_applies_to_another_document() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template");
|
||||
let mut s = template_session(&dir);
|
||||
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]), "no folder yet");
|
||||
s.execute("file.info", &info()).unwrap();
|
||||
let r = s.execute("file.info.saveTemplate", &json!({"name": " Studio "})).unwrap();
|
||||
assert_eq!(r["name"], "Studio");
|
||||
let path = dir.join("Metadata Templates").join("Studio.xmp");
|
||||
assert!(path.is_file(), "saved into the folder: {r}");
|
||||
let listed = s.execute("file.info.templates", &json!({})).unwrap();
|
||||
assert_eq!(listed["templates"][0]["name"], "Studio");
|
||||
assert_eq!(listed["templates"].as_array().map(Vec::len), Some(1));
|
||||
// A name that isn't a usable file name as it is is refused, so `a/b` and `a?b` never share a file.
|
||||
for name in ["a/b", "a?b", "CON", "Studio.", "x\u{1}"] {
|
||||
assert!(s.execute("file.info.saveTemplate", &json!({"name": name})).is_err(), "{name}");
|
||||
}
|
||||
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"].as_array().map(Vec::len), Some(1));
|
||||
// Saving is not an edit of the document.
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
|
||||
// Into a new document, by name, in one undo step.
|
||||
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"name": "Studio", "mode": "keep"})).unwrap();
|
||||
assert_eq!(r["changed"], true);
|
||||
let m = &s.doc().unwrap().doc.metadata;
|
||||
assert_eq!((m.author.as_str(), m.author_title.as_str(), m.rating), ("Ada Lovelace", "Designer", 4));
|
||||
assert_eq!(m.keywords, ["fair", "Poster", "print"]);
|
||||
assert_eq!((m.copyright_status, m.copyright_notice.as_str()), (CopyrightStatus::Copyrighted, "(c) 2026 Ada"));
|
||||
assert_eq!(m.description, "A poster\nfor the fair");
|
||||
assert_eq!(r["title"], "Poster", "the template carries the title of its own");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
|
||||
// Applied again, nothing changes and nothing is recorded.
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"path": path.to_str().unwrap(), "mode": "keep"})).unwrap();
|
||||
assert_eq!(r["changed"], false);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.metadata.author, "");
|
||||
// The same name replaces the template.
|
||||
s.execute("file.info.saveTemplate", &json!({"name": "Studio", "fields": {"author": "Grace"}})).unwrap();
|
||||
let back = vectorcraft_pdf::read_template(&std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(back.author.as_deref(), Some("Grace"));
|
||||
assert_eq!(back.title, None, "an Untitled-N title is not written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metadata_template_merges_in_three_modes() {
|
||||
let mut s = session();
|
||||
s.execute("file.info", &json!({"author": "Ada", "keywords": ["fair"], "rating": 2, "copyrightUrl": "https://example.com/a"})).unwrap();
|
||||
let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo {
|
||||
author: Some("Grace".into()),
|
||||
description: Some("From the template".into()),
|
||||
keywords: Some(vec!["print".into(), "Fair".into()]),
|
||||
rating: Some(5),
|
||||
copyrighted: Some(false),
|
||||
..Default::default()
|
||||
});
|
||||
let merged =
|
||||
|s: &mut Session, mode: &str| s.execute("file.info.applyTemplate", &json!({"data": template, "mode": mode, "apply": false})).unwrap();
|
||||
// Clear and replace: the fields the template lacks are cleared; the title stays.
|
||||
let r = merged(&mut s, "replace");
|
||||
assert_eq!((r["author"].as_str(), r["description"].as_str(), r["rating"].as_u64()), (Some("Grace"), Some("From the template"), Some(5)));
|
||||
assert_eq!(
|
||||
(r["keywords"].clone(), r["copyrightUrl"].as_str(), r["copyrightStatus"].as_str()),
|
||||
(json!(["print", "Fair"]), Some(""), Some("publicDomain"))
|
||||
);
|
||||
assert_eq!(r["title"], "Poster");
|
||||
// Keep and replace: the template's fields replace those it has; the others stay.
|
||||
let r = merged(&mut s, "keep");
|
||||
assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["copyrightUrl"].as_str()), (Some("Grace"), Some(5), Some("https://example.com/a")));
|
||||
assert_eq!(r["keywords"], json!(["print", "Fair"]));
|
||||
// Keep and append: keywords are added (each once), and only empty fields are filled.
|
||||
let r = merged(&mut s, "append");
|
||||
assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["description"].as_str()), (Some("Ada"), Some(2), Some("From the template")));
|
||||
assert_eq!((r["keywords"].clone(), r["copyrightStatus"].as_str()), (json!(["fair", "print"]), Some("publicDomain")));
|
||||
// `apply: false` changed nothing; `base` merges into the given fields instead.
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
|
||||
assert_eq!(s.doc().unwrap().doc.metadata.author, "Ada");
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "append", "apply": false, "base": {"author": ""}})).unwrap();
|
||||
assert_eq!(r["author"], "Grace");
|
||||
// Applied: one undo step.
|
||||
s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "replace"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 2);
|
||||
assert_eq!(s.doc().unwrap().doc.metadata.copyright_url, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_template_errors() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-errors");
|
||||
let mut s = template_session(&dir);
|
||||
let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() });
|
||||
let not_xmp = dir.join("note.xmp");
|
||||
std::fs::write(¬_xmp, "<note>not metadata</note>").unwrap();
|
||||
let big = dir.join("big.xmp");
|
||||
std::fs::write(&big, vec![b' '; vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1]).unwrap();
|
||||
let e = s.execute("file.info.applyTemplate", &json!({"path": big.to_str().unwrap(), "mode": "keep"})).unwrap_err();
|
||||
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
|
||||
let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err();
|
||||
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
|
||||
for bad in [
|
||||
json!({"data": xmp, "mode": "merge"}),
|
||||
json!({"data": xmp}),
|
||||
json!({"data": xmp, "mode": 3}),
|
||||
json!({"mode": "keep"}),
|
||||
json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}),
|
||||
json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}),
|
||||
json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}),
|
||||
json!({"path": big.to_str().unwrap(), "mode": "keep"}),
|
||||
json!({"name": "missing", "mode": "keep"}),
|
||||
json!({"data": "Ada Lovelace", "mode": "keep"}),
|
||||
json!({"data": xmp, "mode": "keep", "apply": "yes"}),
|
||||
json!({"data": xmp, "mode": "keep", "base": [1]}),
|
||||
json!({"data": xmp, "mode": "keep", "base": {"rating": 9}}),
|
||||
] {
|
||||
assert!(s.execute("file.info.applyTemplate", &bad).is_err(), "{bad}");
|
||||
}
|
||||
for bad in [json!({"name": "a", "path": "b.xmp"}), json!({"name": " "}), json!({"fields": {"rating": 9}}), json!({"fields": "x"})] {
|
||||
assert!(s.execute("file.info.saveTemplate", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 0);
|
||||
assert!(!dir.join("Metadata Templates").exists(), "no failed save made the folder");
|
||||
// A link in the folder is not followed, by its name or its file name.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let outside = dir.join("outside.xmp");
|
||||
std::fs::write(&outside, &xmp).unwrap();
|
||||
std::fs::create_dir_all(dir.join("Metadata Templates")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, dir.join("Metadata Templates").join("Linked.xmp")).unwrap();
|
||||
for name in ["Linked", "Linked.xmp"] {
|
||||
assert!(s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "keep"})).is_err(), "{name}");
|
||||
}
|
||||
let e = s.execute("file.info.applyTemplate", &json!({"name": "Linked", "mode": "keep"})).unwrap_err();
|
||||
assert!(e.to_string().contains("not a file"), "{e}");
|
||||
assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]));
|
||||
// A save by that name leaves the linked file as it was.
|
||||
let e = s.execute("file.info.saveTemplate", &json!({"name": "Linked", "fields": {"author": "Grace"}})).unwrap_err();
|
||||
assert!(e.to_string().contains("not a file"), "{e}");
|
||||
assert_eq!(std::fs::read_to_string(&outside).unwrap(), xmp);
|
||||
std::fs::remove_dir_all(dir.join("Metadata Templates")).unwrap();
|
||||
}
|
||||
// Without a folder (runs without preferences), a name is an error, the data comes back, and
|
||||
// the list is empty.
|
||||
let mut s = session();
|
||||
assert!(s.execute("file.info.saveTemplate", &json!({"name": "Studio"})).is_err());
|
||||
let data = s.execute("file.info.saveTemplate", &json!({"fields": {"author": "Ada"}})).unwrap()["data"].as_str().unwrap().to_string();
|
||||
assert_eq!(vectorcraft_pdf::read_template(data.as_bytes()).unwrap().author.as_deref(), Some("Ada"));
|
||||
assert_eq!(s.execute("file.info.templates", &json!({"create": true})).unwrap(), json!({"templates": []}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_templates_folder_lists_only_xmp_files_and_can_be_made() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-list");
|
||||
let mut s = template_session(&dir);
|
||||
let r = s.execute("file.info.templates", &json!({"create": true})).unwrap();
|
||||
let folder = dir.join("Metadata Templates");
|
||||
assert!(folder.is_dir());
|
||||
assert_eq!(r["folder"], folder.to_str().unwrap());
|
||||
for f in ["b.XMP", "a.xmp", "notes.txt", ".xmp"] {
|
||||
std::fs::write(folder.join(f), "x").unwrap();
|
||||
}
|
||||
std::fs::create_dir(folder.join("c.xmp")).unwrap();
|
||||
// Other files, however many, leave the templates listed.
|
||||
for i in 0..1000 {
|
||||
std::fs::write(folder.join(format!("{i:04}.txt")), "").unwrap();
|
||||
}
|
||||
let names: Vec<String> = s.execute("file.info.templates", &json!({})).unwrap()["templates"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| t["name"].as_str().unwrap().to_string())
|
||||
.collect();
|
||||
assert_eq!(names, ["a", "b"]);
|
||||
// A listed name opens whatever the case of its extension.
|
||||
let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() });
|
||||
std::fs::write(folder.join("b.XMP"), xmp).unwrap();
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"name": "b", "mode": "keep"})).unwrap();
|
||||
assert_eq!(r["author"], "Grace");
|
||||
// Its listed file name opens it too.
|
||||
let listed = s.execute("file.info.templates", &json!({})).unwrap();
|
||||
assert_eq!(listed["templates"][1]["file"], "b.XMP");
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap();
|
||||
assert_eq!(r["author"], "Grace");
|
||||
// A listed file name is taken before the name with `.xmp` added.
|
||||
let ada = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() });
|
||||
std::fs::write(folder.join("b.XMP.xmp"), ada).unwrap();
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap();
|
||||
assert_eq!(r["author"], "Grace");
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP.xmp", "mode": "replace", "apply": false})).unwrap();
|
||||
assert_eq!(r["author"], "Ada");
|
||||
// A name that is not a file name never opens the template its safe form names.
|
||||
let grace = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() });
|
||||
std::fs::write(folder.join("a-b.xmp"), grace).unwrap();
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"name": "a-b", "mode": "replace", "apply": false})).unwrap();
|
||||
assert_eq!(r["author"], "Grace");
|
||||
for name in ["a/b", "a\\b", "a:b"] {
|
||||
let e = s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "replace", "apply": false})).unwrap_err();
|
||||
assert!(e.to_string().contains("isn't usable as a file name"), "{name}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_largest_file_info_saves_a_template_that_imports() {
|
||||
let mut s = session();
|
||||
let text = "\"&".repeat(32_768);
|
||||
let keywords: Vec<String> = (0..1000).map(|i| format!("{i:04}{}", "\"".repeat(252))).collect();
|
||||
let fields = json!({
|
||||
"author": text, "authorTitle": text, "description": text, "copyrightNotice": text,
|
||||
"copyrightUrl": format!("https://example.com/{}", "&".repeat(2000)), "keywords": keywords, "rating": 5, "copyrightStatus": "copyrighted",
|
||||
});
|
||||
let data = s.execute("file.info.saveTemplate", &json!({"fields": fields})).unwrap()["data"].as_str().unwrap().to_string();
|
||||
assert!(data.len() > 1 << 20, "{} bytes", data.len());
|
||||
let r = s.execute("file.info.applyTemplate", &json!({"data": data, "mode": "replace"})).unwrap();
|
||||
assert_eq!((r["author"].as_str(), r["keywords"].as_array().map(Vec::len)), (Some(text.as_str()), Some(1000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_opens_with_the_rating_and_author_title_its_packet_gives() {
|
||||
let mut m = DocMetadata::default();
|
||||
let f = vectorcraft_pdf::FileInfo { author_title: Some("Editor".into()), rating: Some(3), ..Default::default() };
|
||||
crate::cmd::fileinfo::read_pdf(&mut m, f);
|
||||
assert_eq!((m.author_title.as_str(), m.rating), ("Editor", 3));
|
||||
}
|
||||
@@ -102,6 +102,41 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
|
||||
assert!(!d.is_dirty(), "nothing to save");
|
||||
}
|
||||
|
||||
/// `text.glyphCategories` lists the kinds of glyph a font's OpenType features give, with a
|
||||
/// stylistic set's name, and refuses a font that isn't available and params that aren't strings.
|
||||
#[test]
|
||||
fn glyph_categories_list_the_glyphs_of_each_kind_of_feature() {
|
||||
use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid};
|
||||
FontDb::global().add_font(categories_font().expect("the test font builds"));
|
||||
let mut s = Session::new();
|
||||
let g = |c| u32::from(source_sans_gid(c).expect("a glyph"));
|
||||
let mut figures = vec![g('7'), g('8')];
|
||||
figures.sort_unstable();
|
||||
let r = s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY})).unwrap();
|
||||
assert_eq!(r["family"], CATEGORIES_FAMILY);
|
||||
assert_eq!(r["style"], "Regular");
|
||||
assert_eq!(
|
||||
r["categories"],
|
||||
json!([
|
||||
{"id": "ligatures", "glyphs": [g('L')]},
|
||||
{"id": "ss02", "name": "Round Dots", "glyphs": [g('G')]},
|
||||
{"id": "smallCaps", "glyphs": [g('B')]},
|
||||
{"id": "figures", "glyphs": figures},
|
||||
])
|
||||
);
|
||||
assert_eq!(s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY, "style": "regular"})).unwrap(), r);
|
||||
for (p, says) in [
|
||||
(json!({}), "missing `family`"),
|
||||
(json!({"family": 3}), "`family` must be a string"),
|
||||
(json!({"family": "No Such Font"}), "is not available"),
|
||||
(json!({"family": CATEGORIES_FAMILY, "style": "Black"}), "is not available"),
|
||||
(json!({"family": CATEGORIES_FAMILY, "style": true}), "`style` must be a string"),
|
||||
] {
|
||||
let e = s.execute("text.glyphCategories", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Refreshing the font list while a background save writes the file leaves the document saved
|
||||
/// once the file is written.
|
||||
#[test]
|
||||
|
||||
@@ -399,6 +399,22 @@ fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() {
|
||||
assert!(crate::perspective_click(&s, "shape.rectangle", &json!({}), at).is_none());
|
||||
}
|
||||
|
||||
/// The Ellipse dialog's anchor count reaches the ellipse drawn on the active plane.
|
||||
#[test]
|
||||
fn an_ellipse_of_six_anchors_made_by_a_click_draws_on_the_active_plane() {
|
||||
let (mut s, _) = persp_session();
|
||||
s.execute("perspective.grid.show", &json!({"visible": true})).unwrap();
|
||||
s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap();
|
||||
let at = Point::new(470.0, 300.0);
|
||||
let p = json!({"x": at.x, "y": at.y, "width": 50, "height": 30, "anchors": 6});
|
||||
let (cmd, p) = crate::perspective_click(&s, "shape.ellipse", &p, at).unwrap();
|
||||
let n = undo_len(&s);
|
||||
let id = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Right));
|
||||
assert_eq!(node(&s, id).path_data().unwrap().anchor_count(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_canvas_draws_type_in_perspective_foreshortened() {
|
||||
let (mut s, rect) = persp_session();
|
||||
|
||||
@@ -1158,3 +1158,304 @@ fn not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property() {
|
||||
assert!(!aligned(&s, off));
|
||||
assert_eq!(not_aligned(&mut s, &[compound]), vec![other]);
|
||||
}
|
||||
|
||||
/// The anchors of the paths in the art of symbol instance `inst`, where its transform places them.
|
||||
fn placed_points(s: &Session, inst: u64) -> Vec<(f64, f64)> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &d.node(NodeId(inst)).unwrap().kind else { panic!("{inst} is not a symbol instance") };
|
||||
let art = &d.symbols.iter().find(|x| &x.name == symbol).unwrap().art;
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if let Some(p) = n.path_data() {
|
||||
out.extend(p.anchors().map(|(_, _, a)| {
|
||||
let q = *xf * a.p;
|
||||
(q.x, q.y)
|
||||
}));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The transform of symbol instance `inst`.
|
||||
fn instance_xf(s: &Session, inst: u64) -> vectorcraft_geom::Affine {
|
||||
match &s.doc().unwrap().doc.node(NodeId(inst)).unwrap().kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => *xf,
|
||||
_ => panic!("{inst} is not a symbol instance"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol Options › Align to Pixel Grid on a new symbol: the instance that replaces the selection
|
||||
/// draws its art's edges on whole points, and goes back to them after a move by a fraction of a
|
||||
/// point; a symbol made without it keeps the art where it was drawn.
|
||||
#[test]
|
||||
fn a_pixel_aligned_symbol_keeps_its_instance_on_whole_points() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let r = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
assert_eq!(r["alignToPixelGrid"], true);
|
||||
let inst = r["id"].as_u64().unwrap();
|
||||
let pts = placed_points(&s, inst);
|
||||
assert_eq!(pts.len(), 4);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
let list = s.execute("symbol.list", &json!({})).unwrap();
|
||||
assert_eq!(list["symbols"][0]["alignToPixelGrid"], true);
|
||||
|
||||
path(&mut s, "M100.3 20.6 L140.7 20.6 L140.7 30.3 L100.3 30.3 Z", 2.0);
|
||||
let plain = s.execute("symbol.new", &json!({"name": "Plain"})).unwrap();
|
||||
assert_eq!(plain["alignToPixelGrid"], false);
|
||||
let pts = placed_points(&s, plain["id"].as_u64().unwrap());
|
||||
assert!(!whole(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// A centered stroke of odd weight puts the art's edges on half points, so the stroke's own edges
|
||||
/// fall on the grid.
|
||||
#[test]
|
||||
fn a_pixel_aligned_symbol_with_an_odd_stroke_goes_to_half_points() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(halves(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// Turning it on in Symbol Options snaps the instances placed at actual size and leaves a scaled
|
||||
/// one where it is; instances placed later land on whole points; asking again for the value the
|
||||
/// symbol has adds no undo step; a duplicate and a rename keep it, a delete clears it, and a value
|
||||
/// that is not true or false is refused.
|
||||
#[test]
|
||||
fn symbol_options_align_to_pixel_grid_snaps_instances_at_actual_size() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 150})).unwrap();
|
||||
let scaled = instance_xf(&s, b);
|
||||
assert!(!whole(&placed_points(&s, a)));
|
||||
|
||||
let r = s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
assert_eq!(r["alignToPixelGrid"], true);
|
||||
let pts = placed_points(&s, a);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
assert_eq!(instance_xf(&s, b), scaled);
|
||||
let c = s.execute("symbol.place", &json!({"name": "Px", "x": 50.3, "y": 60.6})).unwrap()["id"].as_u64().unwrap();
|
||||
let pts = placed_points(&s, c);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
|
||||
let steps = undo_len(&s);
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
assert_eq!(undo_len(&s), steps);
|
||||
|
||||
assert_eq!(s.execute("symbol.duplicate", &json!({"name": "Px"})).unwrap()["name"], "Px copy");
|
||||
assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Px copy"));
|
||||
s.execute("symbol.options", &json!({"name": "Px", "newName": "Grid"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Grid"));
|
||||
assert!(!s.doc().unwrap().doc.symbol_pixel_aligned("Px"));
|
||||
s.execute("symbol.delete", &json!({"names": ["Grid", "Px copy"]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_PIXEL_ALIGNED).is_none());
|
||||
|
||||
path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0);
|
||||
assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": "yes"})).is_err());
|
||||
assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": null})).is_err());
|
||||
s.execute("symbol.new", &json!({"name": "Q"})).unwrap();
|
||||
assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": 1})).is_err());
|
||||
assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": null})).is_err());
|
||||
}
|
||||
|
||||
/// An instance reflected across one axis goes back to whole points after a move; one turned a half
|
||||
/// turn counts as rotated and moves by exactly the amount asked.
|
||||
#[test]
|
||||
fn a_reflected_instance_snaps_and_a_half_turned_one_does_not() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
|
||||
let [.., e, f] = instance_xf(&s, inst).as_coeffs();
|
||||
assert!(whole(&[(e, f)]), "{e} {f}");
|
||||
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
|
||||
s.execute("object.rotate", &json!({"angle": 180})).unwrap();
|
||||
let [.., e0, f0] = instance_xf(&s, inst).as_coeffs();
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
|
||||
let [.., e1, f1] = instance_xf(&s, inst).as_coeffs();
|
||||
assert!((e1 - e0 - 0.3).abs() < 1e-9 && (f1 - f0 - 0.45).abs() < 1e-9, "{e0} {f0} -> {e1} {f1}");
|
||||
}
|
||||
|
||||
/// An instance of a pixel-aligned symbol attached to a path goes back to whole points each time the
|
||||
/// path places it.
|
||||
#[test]
|
||||
fn an_instance_on_a_path_stays_on_whole_points() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
|
||||
let spine = s.execute("path.create", &json!({"d": "M 0.3 100.4 L 300.3 100.4"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.objectsOnPath.attach", &json!({"path": spine, "ids": [inst]})).unwrap();
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "attached: {pts:?}");
|
||||
let anchors = json!([{"x": 0.6, "y": 120.7}, {"x": 300.6, "y": 120.7}]);
|
||||
s.execute("path.setAnchors", &json!({"id": spine, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap();
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "path edited: {pts:?}");
|
||||
}
|
||||
|
||||
/// A path in the art of an opacity mask in a pixel-aligned symbol's art snaps with the rest of
|
||||
/// the art.
|
||||
#[test]
|
||||
fn mask_art_in_a_pixel_aligned_symbol_snaps() {
|
||||
let mut s = new_doc();
|
||||
let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let art = d.remove(NodeId(m)).unwrap();
|
||||
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let xf = instance_xf(&s, inst);
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
|
||||
let mut pts = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if let Some(mask) = n.extras().mask.as_ref() {
|
||||
mask.art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
pts.extend(p.anchors().map(|(_, _, a)| {
|
||||
let q = xf * a.p;
|
||||
(q.x, q.y)
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
assert_eq!(pts.len(), 4);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// A path in the art of an unlinked opacity mask in a pixel-aligned symbol's art snaps as the mask
|
||||
/// is drawn at the symbol's natural size.
|
||||
#[test]
|
||||
fn unlinked_mask_art_in_a_pixel_aligned_symbol_snaps_at_natural_size() {
|
||||
let mut s = new_doc();
|
||||
let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let art = d.remove(NodeId(m)).unwrap();
|
||||
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), false)));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [r]})).unwrap();
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_ne!(s.doc().unwrap().doc.symbol_natural_xf("Px"), vectorcraft_geom::Affine::IDENTITY);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let sym = d.symbols.iter_mut().find(|x| x.name == "Px").unwrap();
|
||||
std::sync::Arc::make_mut(&mut sym.art).extras_mut().mask.as_mut().unwrap().linked = false;
|
||||
}
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let xf = instance_xf(&s, inst);
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
|
||||
let mut pts = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if let Some(mask) = n.extras().mask.as_ref() {
|
||||
mask.art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
pts.extend(p.anchors().map(|(_, _, a)| {
|
||||
let q = xf * a.p;
|
||||
(q.x, q.y)
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
assert_eq!(pts.len(), 4);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// A path in the art of an opacity mask on a path of a compound path in a pixel-aligned symbol's
|
||||
/// art snaps with the rest of the art.
|
||||
#[test]
|
||||
fn mask_art_on_a_compound_paths_path_in_a_pixel_aligned_symbol_snaps() {
|
||||
let mut s = new_doc();
|
||||
let a = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let b = path(&mut s, "M50.3 20.6 L60.7 20.6 L60.7 30.3 L50.3 30.3 Z", 2.0);
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let art = d.remove(NodeId(m)).unwrap();
|
||||
let first = d.node(NodeId(c)).unwrap().children().unwrap()[0].id;
|
||||
d.node_mut(first).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [c]})).unwrap();
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let xf = instance_xf(&s, inst);
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
|
||||
let mut pts = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if let Some(mask) = n.extras().mask.as_ref() {
|
||||
mask.art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
pts.extend(p.anchors().map(|(_, _, a)| {
|
||||
let q = xf * a.p;
|
||||
(q.x, q.y)
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
assert_eq!(pts.len(), 4);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// An instance in the art of an object's opacity mask goes to whole points when its symbol is made
|
||||
/// pixel-aligned.
|
||||
#[test]
|
||||
fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
s.execute("symbol.new", &json!({"name": "Px"})).unwrap();
|
||||
let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
|
||||
let r = path(&mut s, "M80 180 L160 180 L160 240 L80 240 Z", 1.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let inst = d.remove(NodeId(b)).unwrap();
|
||||
d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*inst).clone(), true)));
|
||||
}
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mask = d.node(NodeId(r)).unwrap().extras().mask.clone().unwrap();
|
||||
let NodeKind::SymbolInstance { xf, .. } = &mask.art.kind else { panic!("the mask art is not the instance") };
|
||||
let [.., e, f] = xf.as_coeffs();
|
||||
assert!(whole(&[(e, f)]), "{e} {f}");
|
||||
}
|
||||
|
||||
/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored
|
||||
/// on the pixel grid, so its instances stay on it.
|
||||
#[test]
|
||||
fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
|
||||
let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
|
||||
s.execute("select.set", &json!({"ids": [part]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.symbol_edit.is_some());
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
// The editing layer shows the art as it is stored.
|
||||
let shown = points(&s, part);
|
||||
assert!(whole(&shown), "{shown:?}");
|
||||
s.execute("symbol.exitEditing", &json!({})).unwrap();
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
}
|
||||
@@ -380,6 +380,27 @@ fn randomize_shuffles_new_colours_and_skips_excluded_rows() {
|
||||
assert!((hue(&sb["map"][0]["to"]) - 0.0).abs() < 1.0 && (hue(&sb["map"][1]["to"]) - 120.0).abs() < 1.0, "hue kept");
|
||||
}
|
||||
|
||||
/// A row with no current colors (New Row) keeps its new color through Randomize, and its color
|
||||
/// goes to no row that holds current colors: the other rows shuffle their own colors only.
|
||||
#[test]
|
||||
fn randomize_leaves_an_empty_row_out() {
|
||||
let mut s = session();
|
||||
let map = json!([
|
||||
{"from": [], "to": "rgb 0 255 0"},
|
||||
{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"},
|
||||
{"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"},
|
||||
]);
|
||||
for seed in 0..16 {
|
||||
let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": seed}));
|
||||
assert_eq!(r["map"][0], map[0], "seed {seed}: the empty row keeps its color");
|
||||
let mut tos: Vec<String> = [1, 2].iter().map(|i| r["map"][*i]["to"].as_str().unwrap().to_string()).collect();
|
||||
tos.sort();
|
||||
assert_eq!(tos, ["rgb 0 0 255", "rgb 255 0 0"], "seed {seed}: a permutation of the filled rows' colors");
|
||||
}
|
||||
let sb = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": true, "seed": 3}));
|
||||
assert_eq!(sb["map"][0], map[0], "the empty row keeps its saturation and brightness");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_group_rewrites_in_order_as_one_undo_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -120,6 +120,18 @@ fn missing_or_mismatched_answer_rolls_back() {
|
||||
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing");
|
||||
}
|
||||
|
||||
/// The error about answers left over names their count with the matching noun.
|
||||
#[test]
|
||||
fn unused_answers_are_counted_in_the_singular_and_the_plural() {
|
||||
let mut s = one_doc();
|
||||
let ok = json!({"kind": "alert", "value": "ok"});
|
||||
for (extra, says) in [(1, "`answers` has 1 answer the script did not use"), (2, "`answers` has 2 answers the script did not use")] {
|
||||
let given = Value::Array(vec![ok.clone(); extra + 1]);
|
||||
let e = headless(&mut s, "alert('x');", given).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_answers_are_rejected_before_run() {
|
||||
let mut s = one_doc();
|
||||
|
||||
@@ -255,7 +255,7 @@ impl Session {
|
||||
}
|
||||
// The Selection and Group Selection tools act on the instance whole.
|
||||
self.select_whole_instance(id);
|
||||
// The tool lent to does not see the press: it counts as a press elsewhere for the clicks a
|
||||
// The lending tool does not see the press: it counts as a press elsewhere for the clicks a
|
||||
// double-click or triple-click compares.
|
||||
self.tool.press_elsewhere();
|
||||
let lent = self.make_tool(id);
|
||||
|
||||
@@ -265,6 +265,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
|
||||
|
||||
/// [`export_ai_editing`] writing at most `max_objects` objects, counted as the reader counts them.
|
||||
fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Result<AiEditingOutput, String> {
|
||||
export_held(doc, o, max_objects, true)
|
||||
}
|
||||
|
||||
/// [`export_within`]; with `keep_wraps`, wrapped area type the reader wraps the same is written as
|
||||
/// type ([`writer::wraps_held`]). When such type is written and art is left out at the object
|
||||
/// limit, the wrap objects above it may be among what is left out, and the document is written
|
||||
/// again with that type as its outlines.
|
||||
fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep_wraps: bool) -> Result<AiEditingOutput, String> {
|
||||
let doc = source;
|
||||
let board = doc.artboards.first().ok_or("the document has no artboard")?.rect;
|
||||
if !(board.is_finite() && board.width() > 0.0 && board.height() > 0.0) {
|
||||
return Err("the document has no artboard".into());
|
||||
@@ -277,6 +286,8 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re
|
||||
let (symbol_styled, pattern_styled) = writer::styled_definitions(doc);
|
||||
let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles;
|
||||
let links = writer::style_links(doc);
|
||||
// Before baking, which leaves the wrap objects that may be written as they are unchanged.
|
||||
let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() };
|
||||
// Live geometry effects as their result, as the PDF part draws them.
|
||||
let baked = baked(doc);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
@@ -309,6 +320,7 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re
|
||||
w.brushes_live = scale == 1.0;
|
||||
w.symbol_doc = symbol_doc;
|
||||
w.max_objects = max_objects;
|
||||
w.wraps_held = wraps_held;
|
||||
w.reserve_swatch_gradients();
|
||||
if scale == 1.0 {
|
||||
w.styled = styled;
|
||||
@@ -320,6 +332,9 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re
|
||||
for layer in &doc.layers {
|
||||
w.layer(layer);
|
||||
}
|
||||
if w.wrapped_type_cut() {
|
||||
return export_held(source, o, max_objects, false);
|
||||
}
|
||||
// The symbols no instance uses too; their art adds definitions.
|
||||
w.symbols();
|
||||
// The brushes, once the layers have said whether an object is written with one.
|
||||
|
||||
@@ -11634,6 +11634,349 @@ fn same_region(before: &[(Vec<[f64; 4]>, f64, bool)], after: &[(Vec<[f64; 4]>, f
|
||||
before.len() == after.len() && before.iter().zip(after).all(|(b, a)| close(&b.0, &a.0) && (b.1 - a.1).abs() < 1e-6 && b.2 == a.2)
|
||||
}
|
||||
|
||||
/// A `w` × `h` document of area type "Body" in the frame `frame`, with `over` above it (bottom
|
||||
/// first), its wrap shapes resolved as the canvas resolves them.
|
||||
fn wrapped_body(w: f64, h: f64, frame: Rect, over: impl FnOnce(&mut Document) -> Vec<Node>) -> Document {
|
||||
use vectorcraft_doc::{TextKind, TextObject, TextRun};
|
||||
let mut doc = Document::new(w, h);
|
||||
let layer = doc.layers[0].id;
|
||||
let size = frame.height() / 20.0;
|
||||
let mut body = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(size, Color::BLACK));
|
||||
body.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve", style(size, Color::BLACK))];
|
||||
body.kind = TextKind::Area { frame: shapes::rectangle(frame) };
|
||||
body.xf = Affine::IDENTITY;
|
||||
let body = named(text_node(&mut doc, body), "Body");
|
||||
let over = over(&mut doc);
|
||||
for n in std::iter::once(body).chain(over) {
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
vectorcraft_doc::text::resolve_wrap(None, &mut doc);
|
||||
doc
|
||||
}
|
||||
|
||||
/// The characters, frame and wrap shapes of the area type on `doc`'s first layer, as it is (its
|
||||
/// shapes not resolved again).
|
||||
fn area_type(doc: &Document) -> Option<(String, Option<Rect>, usize)> {
|
||||
use vectorcraft_doc::TextKind;
|
||||
doc.layers[0].children().unwrap().iter().find_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) if matches!(&t.kind, TextKind::Area { .. }) => {
|
||||
let TextKind::Area { frame } = &t.kind else { return None };
|
||||
Some((t.runs.iter().map(|r| r.text.as_str()).collect(), frame.transformed(t.xf).bounds(), t.wrap.len()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Area type wrapped only by plain paths, compound paths and groups that don't clip is written as
|
||||
/// type and reopens as area type with its characters, its frame and the same wrap shapes, which
|
||||
/// the reader works out again from the objects above it ([`crate::import`]'s
|
||||
/// `resolve_text_wrap`): a filled path with a negative offset and Invert Wrap, a locked path with
|
||||
/// only a stroke, a compound path, a group of two squares with a hidden member, an offset of
|
||||
/// -1000 pt, and an empty group and an open line with options, which wrap nothing.
|
||||
#[test]
|
||||
fn area_type_wrapped_by_plain_objects_stays_type() {
|
||||
type Make = fn(&mut Document) -> Vec<Node>;
|
||||
fn ring(doc: &mut Document, r: Rect) -> Node {
|
||||
let outer = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::default());
|
||||
let inner = Node::path(doc.alloc_id(), shapes::rectangle(r.inset(-10.0)), Appearance::default());
|
||||
let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd });
|
||||
ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into();
|
||||
ring
|
||||
}
|
||||
let cases: [(&str, Make); 6] = [
|
||||
("a path, a negative offset, Invert Wrap", |doc| {
|
||||
vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), -4.25, true)]
|
||||
}),
|
||||
("a locked stroked path", |doc| {
|
||||
let mut n = Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::ellipse(Rect::new(80.0, 30.0, 180.0, 130.0)),
|
||||
Appearance::basic(Paint::None, solid(Color::BLACK), 2.0),
|
||||
);
|
||||
n.locked = true;
|
||||
vec![wrapped(n, 6.0, false)]
|
||||
}),
|
||||
("a compound path", |doc| vec![wrapped(ring(doc, Rect::new(80.0, 30.0, 200.0, 150.0)), 7.0, true)]),
|
||||
("a group", |doc| {
|
||||
let a = square(doc, Rect::new(40.0, 40.0, 80.0, 80.0), Color::gray(0.5));
|
||||
let mut hidden = square(doc, Rect::new(120.0, 40.0, 160.0, 80.0), Color::gray(0.5));
|
||||
hidden.visible = false;
|
||||
let b = square(doc, Rect::new(200.0, 100.0, 240.0, 140.0), Color::gray(0.5));
|
||||
vec![wrapped(group(doc, vec![a, hidden, b], false), -2.0, false)]
|
||||
}),
|
||||
("an offset of -1000 pt", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), -1000.0, false)]),
|
||||
("an empty group and an open line", |doc| {
|
||||
let line = Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::line((20.0, 20.0).into(), (280.0, 180.0).into()),
|
||||
Appearance::basic(Paint::None, solid(Color::BLACK), 1.0),
|
||||
);
|
||||
let empty = group(doc, vec![], false);
|
||||
let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5));
|
||||
vec![wrapped(n, 3.0, false), wrapped(empty, 5.0, false), wrapped(line, 5.0, false)]
|
||||
}),
|
||||
];
|
||||
for (name, make) in cases {
|
||||
let doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), make);
|
||||
let before = area_type(&doc).unwrap();
|
||||
assert_ne!(before.2, 0, "{name}: the type is wrapped");
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{name}: {:?}", out.warnings);
|
||||
assert!(text_out.contains("/AI11Text"), "{name}");
|
||||
let back = read_back(&doc);
|
||||
let after = area_type(&back).unwrap_or_else(|| panic!("{name}: no area type\n{text_out}"));
|
||||
assert_eq!(after.0, before.0, "{name}");
|
||||
let (b, a) = (before.1.unwrap(), after.1.unwrap());
|
||||
assert!([b.x0 - a.x0, b.y0 - a.y0, b.x1 - a.x1, b.y1 - a.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {a:?}");
|
||||
assert_eq!(after.2, before.2, "{name}: the reader wrapped it");
|
||||
assert!(same_region(&area_wrap_region(&doc), &area_wrap_region(&back)), "{name}\n{text_out}");
|
||||
// The object that wraps it comes back as the same kind, lock and options.
|
||||
let source = |d: &Document| {
|
||||
let n = d.layers[0].children().unwrap()[1].clone();
|
||||
(std::mem::discriminant(&n.kind), n.locked, n.visible, n.extras().wrap)
|
||||
};
|
||||
assert_eq!(source(&back), source(&doc), "{name}\n{text_out}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Area type stays outlines when a wrap object above it is not written as itself, or its shapes
|
||||
/// are not the ones the objects above it give it: an object with an effect, a blend, a symbol
|
||||
/// instance, a path with a gradient, a compound path with a hidden member, a group holding type,
|
||||
/// a compound path of one subpath (read back as a path), an offset past 1000 pt, a clipping group, and shapes of an object that has moved since.
|
||||
#[test]
|
||||
fn area_type_wrapped_by_other_objects_stays_outlines() {
|
||||
type Make = fn(&mut Document) -> Vec<Node>;
|
||||
let cases: [(&str, Make); 10] = [
|
||||
("an effect", |doc| {
|
||||
let n = styled_rect(doc, "Shadowed", Rect::new(100.0, 40.0, 160.0, 120.0), solid(Color::gray(0.5)), Paint::None, vec![drop_shadow()]);
|
||||
vec![wrapped(n, 4.0, false)]
|
||||
}),
|
||||
("a blend", |doc| {
|
||||
let keys = vec![
|
||||
Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))),
|
||||
Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))),
|
||||
];
|
||||
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() };
|
||||
vec![wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 4.5, false)]
|
||||
}),
|
||||
("a symbol instance", |doc| {
|
||||
two_leaves(doc);
|
||||
vec![wrapped(instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])), 4.5, false)]
|
||||
}),
|
||||
("a gradient", |doc| {
|
||||
let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]);
|
||||
let ap = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None, 0.0);
|
||||
vec![wrapped(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 40.0, 160.0, 120.0)), ap), 4.0, false)]
|
||||
}),
|
||||
("a compound path with a hidden member", |doc| {
|
||||
let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)), Appearance::default());
|
||||
let mut inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 50.0, 180.0, 130.0)), Appearance::default());
|
||||
inner.visible = false;
|
||||
let mut ring =
|
||||
Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd });
|
||||
ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into();
|
||||
vec![wrapped(ring, 4.0, false)]
|
||||
}),
|
||||
("a group holding type", |doc| {
|
||||
let label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(100.0, 100.0), "Label", style(20.0, Color::BLACK));
|
||||
let label = text_node(doc, label);
|
||||
let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5));
|
||||
vec![wrapped(group(doc, vec![n, label], false), 4.0, false)]
|
||||
}),
|
||||
("a compound path of one subpath", |doc| {
|
||||
let only = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)), Appearance::default());
|
||||
let mut one = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(only)], rule: FillRule::NonZero });
|
||||
one.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into();
|
||||
vec![wrapped(one, 4.0, false)]
|
||||
}),
|
||||
("an offset past 1000 pt", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 1000.5, false)]),
|
||||
("a clipping group", |doc| {
|
||||
let clip = clipping(doc, shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)));
|
||||
let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5));
|
||||
vec![wrapped(group(doc, vec![clip, n], true), 4.0, false)]
|
||||
}),
|
||||
("a path moved since", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 4.0, false)]),
|
||||
];
|
||||
let mut typed = vec![];
|
||||
for (name, make) in cases {
|
||||
let mut doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), make);
|
||||
assert_ne!(area_type(&doc).unwrap().2, 0, "{name}: the type is wrapped");
|
||||
if name == "a path moved since" {
|
||||
let id = doc.layers[0].children().unwrap()[1].id;
|
||||
doc.node_mut(id).unwrap().transform(Affine::translate((30.0, 0.0)), false);
|
||||
}
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
if !out.warnings.iter().any(|w| w == writer::TYPE) || area_type(&read_back(&doc)).is_some() {
|
||||
typed.push(name);
|
||||
}
|
||||
}
|
||||
assert!(typed.is_empty(), "written as type: {typed:?}");
|
||||
}
|
||||
|
||||
/// Each frame of threaded area type is checked on its own: a thread whose first frame is wrapped
|
||||
/// by a path and a group and whose second by the group alone is written as type and reopens as the
|
||||
/// same thread with the same shapes in each frame; with a blend over the second frame, the whole
|
||||
/// thread is written as outlines.
|
||||
#[test]
|
||||
fn threaded_area_type_wrapped_by_plain_objects_stays_type() {
|
||||
use vectorcraft_doc::{TextKind, TextObject, TextRun};
|
||||
for blend in [false, true] {
|
||||
let mut doc = Document::new(400.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let st = style(10.0, Color::BLACK);
|
||||
let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone());
|
||||
first.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve thirteen fourteen ", st.clone())];
|
||||
first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 190.0, 90.0)) };
|
||||
first.xf = Affine::IDENTITY;
|
||||
let mut second = first.clone();
|
||||
second.runs = vec![TextRun::new("fifteen sixteen seventeen eighteen nineteen twenty", st.clone())];
|
||||
second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(210.0, 10.0, 390.0, 90.0)) };
|
||||
let (first, second) = (named(text_node(&mut doc, first), "First"), named(text_node(&mut doc, second), "Second"));
|
||||
doc.text_threads.push(vec![first.id, second.id]);
|
||||
let path = wrapped(square(&mut doc, Rect::new(60.0, 20.0, 100.0, 60.0), Color::gray(0.5)), -3.0, true);
|
||||
let over_second = if blend {
|
||||
let keys = vec![
|
||||
Arc::new(square(&mut doc, Rect::new(250.0, 20.0, 260.0, 30.0), Color::gray(0.5))),
|
||||
Arc::new(square(&mut doc, Rect::new(340.0, 60.0, 350.0, 70.0), Color::gray(0.5))),
|
||||
];
|
||||
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(30.0), ..Default::default() };
|
||||
wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 2.0, false)
|
||||
} else {
|
||||
let a = square(&mut doc, Rect::new(250.0, 20.0, 290.0, 60.0), Color::gray(0.5));
|
||||
let b = square(&mut doc, Rect::new(120.0, 50.0, 300.0, 80.0), Color::gray(0.5));
|
||||
wrapped(group(&mut doc, vec![a, b], false), 2.0, false)
|
||||
};
|
||||
// Bottom first: the first frame, the path, the second frame, the group or blend.
|
||||
for n in [first, path, second, over_second] {
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
vectorcraft_doc::text::resolve_wrap(None, &mut doc);
|
||||
type Region = Vec<(Vec<[f64; 4]>, f64, bool)>;
|
||||
let shapes = |d: &Document| -> Vec<Region> {
|
||||
d.layers[0]
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some(
|
||||
t.wrap
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let parts = s
|
||||
.path
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|sp| {
|
||||
let b = PathData::new(vec![sp.clone()]).bounds().unwrap_or_default();
|
||||
[b.x0, b.y0, b.x1, b.y1]
|
||||
})
|
||||
.collect();
|
||||
(parts, s.wrap.offset, s.wrap.invert)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let before = shapes(&doc);
|
||||
assert_eq!(before.iter().map(Vec::len).collect::<Vec<_>>(), [2, 1], "blend: {blend}");
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
let back = read_back(&doc);
|
||||
if blend {
|
||||
assert!(out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings);
|
||||
assert!(back.text_threads.is_empty());
|
||||
continue;
|
||||
}
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings);
|
||||
assert_eq!(back.text_threads.len(), 1);
|
||||
let names: Vec<_> = back.text_threads[0].iter().map(|id| back.node(*id).and_then(|n| n.name.clone())).collect();
|
||||
assert_eq!(names, [Some("First".to_string()), Some("Second".to_string())]);
|
||||
let after = shapes(&back);
|
||||
assert_eq!(after.len(), 2);
|
||||
for (b, a) in before.iter().zip(&after) {
|
||||
assert!(same_region(b, a), "{before:?}\n{after:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapped area type is written as type only while the wrap shapes of all the area type the reader
|
||||
/// reads stay within what it copies: 150 frames under a wrap object of 10,000 anchors are, and
|
||||
/// with 100 more frames under it, none are.
|
||||
#[test]
|
||||
fn area_type_wrapped_past_the_reader_limit_stays_outlines() {
|
||||
use vectorcraft_doc::{TextKind, TextObject};
|
||||
let area = |doc: &mut Document| {
|
||||
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Wrapped", style(10.0, Color::BLACK));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)) };
|
||||
t.xf = Affine::IDENTITY;
|
||||
let n = text_node(doc, t);
|
||||
doc.insert(Some(doc.layers[0].id), 0, n).unwrap()
|
||||
};
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let ids: Vec<_> = (0..150).map(|_| area(&mut doc)).collect();
|
||||
let mut zigzag = vec![(40.0, 0.0).into()];
|
||||
zigzag.extend((1..10_000).map(|i| vectorcraft_geom::Point::new(40.0 + 20.0 * f64::from(i) / 10_000.0, if i % 2 == 0 { 0.0 } else { 100.0 })));
|
||||
let n = wrapped(
|
||||
Node::path(doc.alloc_id(), PathData::new(vec![vectorcraft_geom::SubPath::polyline(&zigzag, true)]), Appearance::default()),
|
||||
6.0,
|
||||
false,
|
||||
);
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
|
||||
vectorcraft_doc::text::resolve_wrap(None, &mut doc);
|
||||
let held = writer::wraps_held(&doc, &std::collections::HashMap::new());
|
||||
assert!(ids.iter().all(|id| held.contains(id)), "{} of {}", held.len(), ids.len());
|
||||
for _ in 0..100 {
|
||||
area(&mut doc);
|
||||
}
|
||||
assert!(vectorcraft_doc::text::wrap_work(&doc) > crate::import::MAX_WRAP_WORK);
|
||||
assert!(writer::wraps_held(&doc, &std::collections::HashMap::new()).is_empty());
|
||||
}
|
||||
|
||||
/// Wrapped area type stays type with room for every object, and is written as outlines when art is
|
||||
/// left out at the object limit: one object short, the wrap object above it would be left out and
|
||||
/// the reader would not wrap the type.
|
||||
#[test]
|
||||
fn area_type_wrapped_past_the_object_limit_is_written_as_outlines() {
|
||||
let doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), |doc| {
|
||||
vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 4.0, false)]
|
||||
});
|
||||
let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
|
||||
let all = export_within(&doc, &opts(), read).unwrap();
|
||||
assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT || w == writer::TYPE), "{:?}", all.warnings);
|
||||
let short = export_within(&doc, &opts(), read - 1).unwrap();
|
||||
assert!(short.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", short.warnings);
|
||||
assert!(short.warnings.iter().any(|w| w == writer::TYPE), "{:?}", short.warnings);
|
||||
let (back, _) = crate::ai_alone(&short.program).unwrap();
|
||||
assert!(area_type(&back).is_none(), "{}", String::from_utf8_lossy(&short.program));
|
||||
}
|
||||
|
||||
/// On a large canvas, area type wrapped by a plain path is written as type and reopens with the
|
||||
/// same wrap shapes, the offset at its size.
|
||||
#[test]
|
||||
fn area_type_wrapped_on_a_large_canvas_stays_type() {
|
||||
let doc = wrapped_body(20_000.0, 20_000.0, Rect::new(1000.0, 1000.0, 9000.0, 9000.0), |doc| {
|
||||
vec![wrapped(square(doc, Rect::new(3000.0, 3000.0, 5000.0, 6000.0), Color::gray(0.5)), -12.5, true)]
|
||||
});
|
||||
let before = area_type(&doc).unwrap();
|
||||
assert_ne!(before.2, 0);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
let after = area_type(&back).expect("area type");
|
||||
assert_eq!((after.0.as_str(), after.2), (before.0.as_str(), before.2));
|
||||
let (b, a) = (area_wrap_region(&doc), area_wrap_region(&back));
|
||||
let close = b.len() == a.len()
|
||||
&& b.iter().zip(&a).all(|(b, a)| {
|
||||
b.0.len() == a.0.len()
|
||||
&& b.0.iter().zip(&a.0).all(|(x, y)| x.iter().zip(y).all(|(x, y)| (x - y).abs() < 1e-2))
|
||||
&& (b.1 - a.1).abs() < 1e-3
|
||||
&& b.2 == a.2
|
||||
});
|
||||
assert!(close, "{b:?}\n{a:?}");
|
||||
}
|
||||
|
||||
/// Type written as its outlines wraps area type below it by its bounds, as it did before saving,
|
||||
/// not by its glyphs: its text wrap options go on an unpainted rectangle of its bounds, the last
|
||||
/// member of the outlines' group, which keeps the type's name and has no options of its own.
|
||||
|
||||
@@ -31,6 +31,7 @@ pub(super) use envelopes::ENVELOPES;
|
||||
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects};
|
||||
#[cfg(test)]
|
||||
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance};
|
||||
pub(super) use texts::wraps_held;
|
||||
|
||||
pub(super) use images::PAYLOAD;
|
||||
#[cfg(test)]
|
||||
@@ -49,7 +50,7 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES};
|
||||
/// [`vectorcraft_doc::MAX_DEPTH`].
|
||||
pub(super) const MAX_NEST: u32 = 8;
|
||||
|
||||
pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps";
|
||||
pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type whose text wrap cannot be preserved from the saved objects, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps";
|
||||
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
|
||||
pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps";
|
||||
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
|
||||
@@ -228,6 +229,10 @@ pub(super) struct Writer<'a> {
|
||||
bound: Vec<(vectorcraft_doc::NodeId, String, Vec<String>)>,
|
||||
/// The text document: the stories of the type written as text.
|
||||
pub(super) texts: texts::TextDoc,
|
||||
/// The area type with wrap shapes that may be written as type ([`texts::wraps_held`]).
|
||||
pub(super) wraps_held: HashSet<NodeId>,
|
||||
/// Area type with wrap shapes was written as type.
|
||||
wrapped_typed: bool,
|
||||
/// Symbol instances on the layers may be written as instances ([`Self::live_instance`]); false
|
||||
/// on a large canvas, where they are written as their art.
|
||||
pub(super) symbols_live: bool,
|
||||
@@ -348,6 +353,8 @@ impl<'a> Writer<'a> {
|
||||
typed: false,
|
||||
bound: vec![],
|
||||
texts: texts::TextDoc::default(),
|
||||
wraps_held: HashSet::new(),
|
||||
wrapped_typed: false,
|
||||
cms: vectorcraft_color::cms::active(),
|
||||
body: String::new(),
|
||||
warnings: vec![],
|
||||
@@ -404,6 +411,12 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Was area type with wrap shapes written as type, and art left out at the object limit
|
||||
/// ([`Self::take_objects`])? The reader may then wrap that type by fewer objects than it had.
|
||||
pub(super) fn wrapped_type_cut(&self) -> bool {
|
||||
self.wrapped_typed && self.left_out > 0
|
||||
}
|
||||
|
||||
/// Whether `count` more objects may be written: the objects written so far, counted as the
|
||||
/// reader counts them ([`object_count`]), stay within [`Self::max_objects`]. Past it the art is
|
||||
/// left out, with a warning.
|
||||
@@ -1482,7 +1495,11 @@ impl<'a> Writer<'a> {
|
||||
let thread = doc.text_threads.iter().find(|th| th.contains(&n.id));
|
||||
let contents = self.contents_level.filter(|(hidden, nest, _)| (*hidden, *nest) == (self.hidden, self.nest));
|
||||
// Type that can't be a stub is written as its outlines, which count their own objects.
|
||||
if (self.hidden > 0 && contents.is_none()) || self.clip.is_some() || self.in_symbol || (thread.is_none() && !texts::holds(n, t)) {
|
||||
if (self.hidden > 0 && contents.is_none())
|
||||
|| self.clip.is_some()
|
||||
|| self.in_symbol
|
||||
|| (thread.is_none() && !texts::holds(n, t, self.wraps_held.contains(&n.id)))
|
||||
{
|
||||
self.outlined += 1;
|
||||
return self.outlined_text(n, xy);
|
||||
}
|
||||
@@ -1495,7 +1512,7 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
let placed = if let Some(thread) = thread {
|
||||
// A thread is checked for what it loses, in every frame, when its story is written.
|
||||
let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id));
|
||||
let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held);
|
||||
placed.map(|p| (p, self.texts.take_lost()))
|
||||
} else {
|
||||
self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t)))
|
||||
@@ -1507,6 +1524,7 @@ impl<'a> Writer<'a> {
|
||||
return self.outlined_text(n, xy);
|
||||
};
|
||||
self.typed = true;
|
||||
self.wrapped_typed |= !t.wrap.is_empty();
|
||||
if lost {
|
||||
self.warn(texts::TYPE_ATTRIBUTES);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{ParamCurveArclen, PathSeg};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
@@ -197,8 +198,8 @@ fn solid(p: &Paint) -> Option<Option<Color>> {
|
||||
/// Can the text document hold type `t` of object `n` as it is: point type that isn't mirrored, or
|
||||
/// area type or type on a path that is only moved ([`shape`]); characters other than inline graphics
|
||||
/// and ruby; solid fills and strokes; no fills, strokes, effects or opacity mask of the object's
|
||||
/// own; some text.
|
||||
pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool {
|
||||
/// own; some text. Area type with wrap shapes only when `wrap_held` ([`wraps_held`]).
|
||||
pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject, wrap_held: bool) -> bool {
|
||||
let xf = t.xf.as_coeffs();
|
||||
let shape_ok = match &t.kind {
|
||||
TextKind::Point => xf.iter().all(|v| v.is_finite()) && t.xf.determinant() > 1e-12,
|
||||
@@ -210,10 +211,9 @@ pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool {
|
||||
}
|
||||
};
|
||||
// Area type with wrap shapes: the text document doesn't hold them. The reader works them out
|
||||
// again from the art above the type, which can wrap it differently (a live object written as
|
||||
// its drawn pieces) or not at all.
|
||||
// again from the art above the type, which wraps it the same only where `wraps_held` says so.
|
||||
shape_ok
|
||||
&& t.wrap.is_empty()
|
||||
&& (t.wrap.is_empty() || wrap_held)
|
||||
&& t.ruby.is_empty()
|
||||
&& !t.stacks_warichu()
|
||||
&& t.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace()))
|
||||
@@ -324,6 +324,112 @@ fn plain(n: &Node) -> bool {
|
||||
&& n.extras().mask.is_none()
|
||||
}
|
||||
|
||||
/// The area type of `doc` whose wrap shapes the reader of the editing data works out again as they
|
||||
/// are ([`vectorcraft_doc::text::resolve_wrap`], which the reader runs on what it reads): the
|
||||
/// shapes are the ones the wrap objects above it give it now, and each of those objects is written
|
||||
/// as itself and read back with the same outline and options ([`wrap_source_held`]), in layers
|
||||
/// and groups written as they are ([`plain_containers`]). `styled`: the objects written with an
|
||||
/// art style. Empty when the shapes of the document's area type would hold more anchors than the
|
||||
/// reader copies into them ([`crate::import::MAX_WRAP_WORK`]).
|
||||
pub(in crate::ai_editing) fn wraps_held(doc: &Document, styled: &HashMap<NodeId, Arc<Node>>) -> HashSet<NodeId> {
|
||||
let mut held = HashSet::new();
|
||||
if vectorcraft_doc::text::wrap_work(doc) > crate::import::MAX_WRAP_WORK {
|
||||
return held;
|
||||
}
|
||||
let mut plain_in = HashSet::new();
|
||||
for layer in &doc.layers {
|
||||
plain_containers(layer, true, styled, &mut plain_in);
|
||||
}
|
||||
let mut checked: HashMap<NodeId, bool> = HashMap::new();
|
||||
vectorcraft_doc::text::wrap_sources(doc, |n, sources, shapes| {
|
||||
let NodeKind::Text(t) = &n.kind else { return };
|
||||
if t.wrap.is_empty() || shapes != t.wrap || !plain_in.contains(&n.id) {
|
||||
return;
|
||||
}
|
||||
let ok = sources.iter().all(|s| *checked.entry(s.id).or_insert_with(|| plain_in.contains(&s.id) && wrap_source_held(s, styled)));
|
||||
if ok {
|
||||
held.insert(n.id);
|
||||
}
|
||||
});
|
||||
held
|
||||
}
|
||||
|
||||
/// Adds to `out` the objects with text wrap options and the text objects in `n` (a top-level layer
|
||||
/// when `top`) that sit only in layers and groups written as they are: layers and sublayers that
|
||||
/// don't clip and have no effects, and groups that don't clip, have no fills, strokes, effects,
|
||||
/// art style, opacity mask or graph and aren't written with an art style (`styled`).
|
||||
fn plain_containers(n: &Node, top: bool, styled: &HashMap<NodeId, Arc<Node>>, out: &mut HashSet<NodeId>) {
|
||||
let plain = match &n.kind {
|
||||
NodeKind::Layer { clip, .. } => !clip && n.appearance.effects.is_empty(),
|
||||
NodeKind::Group { clip, .. } => !top && !clip && n.appearance.items.is_empty() && own_plain(n, styled),
|
||||
_ => false,
|
||||
};
|
||||
if !plain {
|
||||
return;
|
||||
}
|
||||
for c in n.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
if c.extras().wrap.is_some() || matches!(c.kind, NodeKind::Text(_)) {
|
||||
out.insert(c.id);
|
||||
}
|
||||
plain_containers(c, false, styled, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Has object `n` no effects, art style, opacity mask or graph, and isn't it a ruler guide or
|
||||
/// written with an art style (`styled`)?
|
||||
fn own_plain(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool {
|
||||
!styled.contains_key(&n.id)
|
||||
&& n.appearance.effects.is_empty()
|
||||
&& n.appearance.items.iter().all(|i| i.effects().is_empty())
|
||||
&& n.extras().graphic_style.is_none()
|
||||
&& n.extras().mask.is_none()
|
||||
&& n.extras().graph.is_none()
|
||||
&& !n.is_ruler_guide()
|
||||
}
|
||||
|
||||
/// Is wrap object `n` written as itself and read back with the same outline and text wrap options:
|
||||
/// an offset the writer and the reader keep as it is (-1000 to 1000 pt) and a plain object
|
||||
/// ([`plain_wrap_art`])?
|
||||
fn wrap_source_held(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool {
|
||||
n.extras().wrap.is_some_and(|w| w.offset.is_finite() && w.offset.abs() <= 1000.0) && plain_wrap_art(n, styled)
|
||||
}
|
||||
|
||||
/// Is `n` written as one object of its own kind that the reader reads back with the same outline
|
||||
/// ([`vectorcraft_doc::text::resolve_wrap`]): a path of one subpath, a compound path of visible
|
||||
/// paths with two subpaths or more in all, each painted with no paint, a solid fill, a plain line of a solid color or both, or a
|
||||
/// group that doesn't clip of such paths, compound paths and groups (hidden ones too) without text
|
||||
/// wrap options of their own; each without effects, art style, opacity mask or graph
|
||||
/// ([`own_plain`]). Each subpath has two anchors or more.
|
||||
fn plain_wrap_art(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool {
|
||||
use vectorcraft_doc::AppearanceItem;
|
||||
let solid = |p: &Paint| matches!(p, Paint::Solid { .. });
|
||||
let painted = || match super::visible_items(n).as_slice() {
|
||||
[] => true,
|
||||
[AppearanceItem::Fill(f)] => solid(&f.paint),
|
||||
[AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
|
||||
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
|
||||
_ => false,
|
||||
};
|
||||
let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2);
|
||||
own_plain(n, styled)
|
||||
&& match &n.kind {
|
||||
NodeKind::Path { path, clipping: false, guide: false, .. } => path.subpaths.len() == 1 && whole(path) && painted(),
|
||||
// One subpath in all would be written, and read back, as a path.
|
||||
NodeKind::Compound { children, .. } => {
|
||||
let subpaths: usize = children.iter().filter_map(|c| c.path_data()).map(|p| p.subpaths.len()).sum();
|
||||
let members = children.iter().all(|c| {
|
||||
c.visible
|
||||
&& matches!(&c.kind, NodeKind::Path { path, clipping: false, guide: false, .. } if !path.subpaths.is_empty() && whole(path))
|
||||
});
|
||||
painted() && subpaths > 1 && members
|
||||
}
|
||||
NodeKind::Group { children, clip: false } => {
|
||||
n.appearance.items.is_empty() && children.iter().all(|c| c.extras().wrap.is_none() && plain_wrap_art(c, styled))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the end bracket of type on an open path so near the path's end that the reader reads it as
|
||||
/// no bracket (`Story::node`: within 0.02 of a segment)?
|
||||
fn end_read_as_none(t: &TextObject) -> bool {
|
||||
@@ -1000,7 +1106,8 @@ impl TextDoc {
|
||||
/// `thread` (its frames in order, all area type the document holds, the first holding the
|
||||
/// story) the first time one of its frames is written. `None` when the thread can't be written
|
||||
/// as one story: `writable` says which frames are written where type can be text (every frame
|
||||
/// of the thread must be).
|
||||
/// of the thread must be), and `wraps_held` which frames with wrap shapes the reader wraps the
|
||||
/// same ([`wraps_held`]; every frame with wrap shapes must be one).
|
||||
pub(in crate::ai_editing) fn thread(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
@@ -1008,6 +1115,7 @@ impl TextDoc {
|
||||
id: NodeId,
|
||||
canvas: Affine,
|
||||
writable: &dyn Fn(NodeId) -> bool,
|
||||
wraps_held: &HashSet<NodeId>,
|
||||
) -> Option<(usize, usize)> {
|
||||
let first = *thread.first()?;
|
||||
if self.planned.insert(first) {
|
||||
@@ -1026,7 +1134,7 @@ impl TextDoc {
|
||||
&& t.vertical == vertical
|
||||
&& writable(n.id)
|
||||
// The text document doesn't hold wrap shapes (see `holds`).
|
||||
&& t.wrap.is_empty()
|
||||
&& (t.wrap.is_empty() || wraps_held.contains(&n.id))
|
||||
&& plain(n)
|
||||
&& t.ruby.is_empty()
|
||||
&& !t.stacks_warichu()
|
||||
|
||||
@@ -96,7 +96,7 @@ pub(crate) use ai::{
|
||||
pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN};
|
||||
pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version};
|
||||
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from};
|
||||
pub(crate) use native::{MAX_TEXT, scale_document, scale_symbols};
|
||||
pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols};
|
||||
pub use text::family_style;
|
||||
pub(crate) use text::{document_font, postscript_face};
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ mod slots;
|
||||
|
||||
#[cfg(test)]
|
||||
use build::{Frame, MADE, prune_unseen};
|
||||
pub(crate) use build::{scale_document, scale_symbols};
|
||||
pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols};
|
||||
#[cfg(test)]
|
||||
use compare::{
|
||||
MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour,
|
||||
|
||||
@@ -773,7 +773,7 @@ fn settle_warped_type(
|
||||
}
|
||||
|
||||
/// Most anchors copied into the wrap shapes of a file's area type ([`vectorcraft_doc::text::wrap_work`]).
|
||||
const MAX_WRAP_WORK: usize = 2_000_000;
|
||||
pub(crate) const MAX_WRAP_WORK: usize = 2_000_000;
|
||||
|
||||
/// [`relayout_wrapped`], or an error when the wrap shapes would hold more than [`MAX_WRAP_WORK`]
|
||||
/// anchors.
|
||||
|
||||
@@ -12,6 +12,7 @@ workspace = true
|
||||
vectorcraft-doc = { workspace = true }
|
||||
vectorcraft-brush = { workspace = true }
|
||||
craft-vectorcraft-format = { workspace = true }
|
||||
craft-gzip = { workspace = true }
|
||||
serde ={ workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
+42
-68
@@ -57,12 +57,14 @@ use vectorcraft_doc::{Document, ImageBlob};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
use craft_gzip::Gz;
|
||||
pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode};
|
||||
use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json};
|
||||
pub use craft_vectorcraft_format::{
|
||||
BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part,
|
||||
sniff,
|
||||
};
|
||||
use stream::{Gz, Indent, KeyScan, Out};
|
||||
use stream::Out;
|
||||
|
||||
/// Most bytes the JSON of a compressed file may unpack to (a guard against decompression bombs,
|
||||
/// as are [`MAX_BLOB`] and [`MAX_BLOBS`]). A compressed save refuses a document past any of them,
|
||||
@@ -367,35 +369,44 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For
|
||||
let profiles: BTreeMap<&str, Image> = o.profiles.iter().map(|(name, icc)| (name.as_str(), out_blobs.image(ICC_MIME, icc, false))).collect();
|
||||
let pdf = o.pdf.as_deref().map(|p| out_blobs.image("application/pdf", p, false));
|
||||
let mut out = if o.compress { Out::Gz(Box::new(Gz::new(w).map_err(encode_err)?)) } else { Out::Plain(w) };
|
||||
let mut env = Envelope { pretty, first: true };
|
||||
// Older apps only know the name from before the rename.
|
||||
env.field(&mut out, "format", &if o.version < 3 { LEGACY_EXTENSION } else { EXTENSION })?;
|
||||
env.field(&mut out, "version", &o.version)?;
|
||||
env.field(&mut out, "generator", &format!("VectorCraft {}", env!("CARGO_PKG_VERSION")))?;
|
||||
if let Some(compatible) = o.pdf_compatible {
|
||||
env.field(&mut out, "pdfCompatible", &compatible)?;
|
||||
}
|
||||
if let Some(png) = &o.preview {
|
||||
env.field(&mut out, "preview", &Image::inline("image/png", png))?;
|
||||
}
|
||||
if !profiles.is_empty() {
|
||||
env.field(&mut out, "profiles", &profiles)?;
|
||||
}
|
||||
if let Some(pdf) = &pdf {
|
||||
env.field(&mut out, "pdf", pdf)?;
|
||||
}
|
||||
env.key(&mut out, "document")?;
|
||||
let mut scan = KeyScan::new(Indent { inner: &mut out, on: pretty });
|
||||
// Without blobs no key matters.
|
||||
scan.active = images.is_none() && !blobs.is_empty();
|
||||
let mut buffered = std::io::BufWriter::with_capacity(JSON_CHUNK, &mut scan);
|
||||
write_body(&mut buffered, v1.as_ref(), &d, pretty)?;
|
||||
buffered.flush().map_err(encode_err)?;
|
||||
drop(buffered);
|
||||
let used = std::mem::take(&mut scan.keys);
|
||||
let images = images.unwrap_or_else(|| entries.images(&used, &mut out_blobs));
|
||||
env.field(&mut out, "images", &images)?;
|
||||
env.finish(&mut out)?;
|
||||
let generator = format!("VectorCraft {}", env!("CARGO_PKG_VERSION"));
|
||||
let preview = o.preview.as_deref().map(|png| Image::inline("image/png", png));
|
||||
let header = FileHeader {
|
||||
version: o.version,
|
||||
generator: &generator,
|
||||
pdf_compatible: o.pdf_compatible,
|
||||
preview: preview.as_ref(),
|
||||
profiles: &profiles,
|
||||
pdf: pdf.as_ref(),
|
||||
};
|
||||
write_file_json(&mut out, &header, pretty, |document| {
|
||||
let mut scan = KeyScan::new(document);
|
||||
// Without blobs no key matters.
|
||||
scan.active = images.is_none() && !blobs.is_empty();
|
||||
let mut buffered = std::io::BufWriter::with_capacity(JSON_CHUNK, &mut scan);
|
||||
match v1.as_ref() {
|
||||
Some(v) => {
|
||||
if pretty {
|
||||
serde_json::to_writer_pretty(&mut buffered, v)
|
||||
} else {
|
||||
serde_json::to_writer(&mut buffered, v)
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if pretty {
|
||||
serde_json::to_writer_pretty(&mut buffered, &d)
|
||||
} else {
|
||||
serde_json::to_writer(&mut buffered, &d)
|
||||
}
|
||||
}
|
||||
}
|
||||
.map_err(std::io::Error::other)?;
|
||||
buffered.flush()?;
|
||||
drop(buffered);
|
||||
let used = std::mem::take(&mut scan.keys);
|
||||
Ok(images.unwrap_or_else(|| entries.images(&used, &mut out_blobs)))
|
||||
})
|
||||
.map_err(encode_err)?;
|
||||
if o.compress {
|
||||
let json = out.written().unwrap_or(0);
|
||||
let tail: Vec<u64> = out_blobs.parts().iter().map(|p| p.bytes.len() as u64).collect();
|
||||
@@ -409,13 +420,7 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For
|
||||
return Err(FormatError::TooBigToCompress(format!("{} MB of images, at most {} MB", out_blobs.len() >> 20, MAX_BLOBS >> 20)));
|
||||
}
|
||||
}
|
||||
if !out_blobs.is_empty() {
|
||||
out.write_all(BLOB_MAGIC).map_err(encode_err)?;
|
||||
for part in out_blobs.parts() {
|
||||
out.packed(is_packed(&part.mime)).map_err(encode_err)?;
|
||||
out.write_all(part.bytes).map_err(encode_err)?;
|
||||
}
|
||||
}
|
||||
out_blobs.write_to_with(&mut out, |out, mime| out.packed(is_packed(mime))).map_err(encode_err)?;
|
||||
out.finish().map_err(encode_err)
|
||||
}
|
||||
|
||||
@@ -450,10 +455,6 @@ fn encode_err(e: impl std::fmt::Display) -> FormatError {
|
||||
FormatError::Encode(e.to_string())
|
||||
}
|
||||
|
||||
fn to_json(v: &impl Serialize, pretty: bool) -> Result<Vec<u8>, FormatError> {
|
||||
if pretty { serde_json::to_vec_pretty(v) } else { serde_json::to_vec(v) }.map_err(encode_err)
|
||||
}
|
||||
|
||||
/// The document's JSON: its version 1 form `v1`, else `d` (generic, not `dyn Write`: serde_json
|
||||
/// writes token by token).
|
||||
fn write_body(w: impl Write, v1: Option<&serde_json::Value>, d: &Document, pretty: bool) -> Result<(), FormatError> {
|
||||
@@ -467,33 +468,6 @@ fn write_json(w: impl Write, v: &impl Serialize, pretty: bool) -> Result<(), For
|
||||
if pretty { serde_json::to_writer_pretty(w, v) } else { serde_json::to_writer(w, v) }.map_err(encode_err)
|
||||
}
|
||||
|
||||
/// The file's top-level object, written member by member (the document is streamed in).
|
||||
struct Envelope {
|
||||
pretty: bool,
|
||||
first: bool,
|
||||
}
|
||||
|
||||
impl Envelope {
|
||||
fn field(&mut self, out: &mut impl Write, key: &str, value: &impl Serialize) -> Result<(), FormatError> {
|
||||
let json = to_json(value, self.pretty)?;
|
||||
self.key(out, key)?;
|
||||
Indent { inner: out, on: self.pretty }.write_all(&json).map_err(encode_err)
|
||||
}
|
||||
|
||||
/// The start of member `key` (a plain name): its value follows, indented one level when
|
||||
/// pretty (as serde_json would: see [`Indent`]).
|
||||
fn key(&mut self, out: &mut impl Write, key: &str) -> Result<(), FormatError> {
|
||||
let sep: &[u8] = if std::mem::take(&mut self.first) { b"{" } else { b"," };
|
||||
let indent: &[u8] = if self.pretty { b"\n " } else { b"" };
|
||||
let colon: &[u8] = if self.pretty { b"\": " } else { b"\":" };
|
||||
[sep, indent, b"\"", key.as_bytes(), colon].iter().try_for_each(|part| out.write_all(part)).map_err(encode_err)
|
||||
}
|
||||
|
||||
fn finish(self, out: &mut impl Write) -> Result<(), FormatError> {
|
||||
out.write_all(if self.pretty { b"\n}" } else { b"}" }).map_err(encode_err)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(bytes: &[u8]) -> Result<Document, FormatError> {
|
||||
load_info(bytes).map(|(doc, _)| doc)
|
||||
}
|
||||
|
||||
+2
-299
@@ -2,10 +2,9 @@
|
||||
//! not) and the data after it is copied in from the document's own buffers, so a save holds no
|
||||
//! copy of the file in memory besides what the caller's writer keeps.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::{self, Write};
|
||||
|
||||
use flate2::{Compress, Compression, Crc, FlushCompress, Status};
|
||||
use craft_gzip::Gz;
|
||||
|
||||
/// The output of a save: plain, or gzip ([`Gz`]).
|
||||
pub(crate) enum Out<W: Write> {
|
||||
@@ -26,7 +25,7 @@ impl<W: Write> Out<W> {
|
||||
pub(crate) fn written(&self) -> Option<u64> {
|
||||
match self {
|
||||
Out::Plain(_) => None,
|
||||
Out::Gz(gz) => Some(gz.total),
|
||||
Out::Gz(gz) => Some(gz.written()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,299 +60,3 @@ impl<W: Write> Write for Out<W> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of compressed output gathered before they go to the writer.
|
||||
const OUT_CHUNK: usize = 64 << 10;
|
||||
|
||||
/// A gzip stream, written as [`flate2::write::GzEncoder`] at the default level writes it (the
|
||||
/// same header and the same data; the deflate blocks are the same too where flate2 deflates with
|
||||
/// miniz_oxide, not with zlib-rs, which writes them by how the data is fed), except that data which
|
||||
/// is compressed already ([`Gz::packed`]) is stored as it is: the default level spends a second
|
||||
/// or more per photo on it for next to nothing, and makes it slower to unpack. Where the level
|
||||
/// changes the deflate blocks so far end with a sync flush and a fresh compressor writes on,
|
||||
/// which makes one valid deflate stream that every reader unpacks.
|
||||
pub(crate) struct Gz<W: Write> {
|
||||
out: W,
|
||||
deflate: Compress,
|
||||
/// What `deflate` writes: stored blocks (packed data), else the default level.
|
||||
stored: bool,
|
||||
crc: Crc,
|
||||
buf: Vec<u8>,
|
||||
/// Bytes written (unpacked).
|
||||
total: u64,
|
||||
}
|
||||
|
||||
impl<W: Write> Gz<W> {
|
||||
pub(crate) fn new(mut out: W) -> io::Result<Self> {
|
||||
// flate2's header for the default level: no name, no time, unknown OS.
|
||||
out.write_all(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 255])?;
|
||||
Ok(Self {
|
||||
out,
|
||||
deflate: Compress::new(Compression::default(), false),
|
||||
stored: false,
|
||||
crc: Crc::new(),
|
||||
buf: Vec::with_capacity(OUT_CHUNK),
|
||||
total: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Run the compressor over `input` with `flush` until it has taken it all (and, flushing,
|
||||
/// written everything out).
|
||||
fn deflate(&mut self, mut input: &[u8], flush: FlushCompress) -> io::Result<()> {
|
||||
loop {
|
||||
if self.buf.len() == self.buf.capacity() {
|
||||
self.out.write_all(&self.buf)?;
|
||||
self.buf.clear();
|
||||
}
|
||||
let (before_in, before_out) = (self.deflate.total_in(), self.deflate.total_out());
|
||||
let status = self.deflate.compress_vec(input, &mut self.buf, flush).map_err(io::Error::other)?;
|
||||
let taken = usize::try_from(self.deflate.total_in() - before_in).unwrap_or(input.len()).min(input.len());
|
||||
input = input.get(taken..).unwrap_or_default();
|
||||
let made = self.deflate.total_out() - before_out;
|
||||
let full = self.buf.len() == self.buf.capacity();
|
||||
match flush {
|
||||
FlushCompress::None if input.is_empty() => return Ok(()),
|
||||
FlushCompress::Finish if status == Status::StreamEnd => return Ok(()),
|
||||
// A flush is done once it left room in the output.
|
||||
FlushCompress::Sync if input.is_empty() && !full => return Ok(()),
|
||||
_ => {}
|
||||
}
|
||||
if taken == 0 && made == 0 && !full {
|
||||
return Err(io::Error::other("the compressor made no progress"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What is written next is compressed already (stored as it is), or not (compressed at the
|
||||
/// default level).
|
||||
fn packed(&mut self, packed: bool) -> io::Result<()> {
|
||||
if packed == self.stored {
|
||||
return Ok(());
|
||||
}
|
||||
self.deflate(&[], FlushCompress::Sync)?;
|
||||
self.deflate = Compress::new(if packed { Compression::none() } else { Compression::default() }, false);
|
||||
self.stored = packed;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(mut self) -> io::Result<()> {
|
||||
self.deflate(&[], FlushCompress::Finish)?;
|
||||
self.out.write_all(&self.buf)?;
|
||||
self.out.write_all(&self.crc.sum().to_le_bytes())?;
|
||||
self.out.write_all(&self.crc.amount().to_le_bytes())?;
|
||||
self.out.flush()
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write> Write for Gz<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.write_all(buf)?;
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
|
||||
self.crc.update(buf);
|
||||
self.total += buf.len() as u64;
|
||||
self.deflate(buf, FlushCompress::None)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
// Flushing would end a deflate block: the stream is flushed when it is finished.
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Indents JSON text written through it one level (two spaces after each newline), as a member
|
||||
/// of the file's top-level object; newlines only occur between tokens, inside strings they are
|
||||
/// escaped.
|
||||
pub(crate) struct Indent<W: Write> {
|
||||
pub(crate) inner: W,
|
||||
pub(crate) on: bool,
|
||||
}
|
||||
|
||||
impl<W: Write> Write for Indent<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.write_all(buf)?;
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
|
||||
if !self.on {
|
||||
return self.inner.write_all(buf);
|
||||
}
|
||||
let mut lines = buf.split(|&b| b == b'\n');
|
||||
self.inner.write_all(lines.next().unwrap_or_default())?;
|
||||
for line in lines {
|
||||
self.inner.write_all(b"\n ")?;
|
||||
self.inner.write_all(line)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// The member that names an image.
|
||||
const TAG: &[u8] = b"\"key\":";
|
||||
|
||||
/// Passes JSON text through, collecting the string values of every `"key": "…"` member at any
|
||||
/// depth (what the images a document uses are named by). Quotes inside JSON strings are escaped,
|
||||
/// so every match is a real member.
|
||||
pub(crate) struct KeyScan<W: Write> {
|
||||
pub(crate) inner: W,
|
||||
pub(crate) keys: HashSet<String>,
|
||||
/// Looking for keys (else it only passes the text on).
|
||||
pub(crate) active: bool,
|
||||
/// How much of [`TAG`] the last bytes matched.
|
||||
matched: usize,
|
||||
/// Right after a tag: skipping whitespace to its value.
|
||||
after_tag: bool,
|
||||
/// The value string so far, quotes included.
|
||||
value: Option<Vec<u8>>,
|
||||
escaped: bool,
|
||||
}
|
||||
|
||||
impl<W: Write> KeyScan<W> {
|
||||
pub(crate) fn new(inner: W) -> Self {
|
||||
Self { inner, keys: HashSet::new(), active: true, matched: 0, after_tag: false, value: None, escaped: false }
|
||||
}
|
||||
|
||||
fn scan(&mut self, buf: &[u8]) {
|
||||
if !self.active {
|
||||
return;
|
||||
}
|
||||
let mut i = 0;
|
||||
while let Some(&b) = buf.get(i) {
|
||||
// Nothing in progress: skip to the next quote.
|
||||
if self.matched == 0 && !self.after_tag && self.value.is_none() {
|
||||
match buf.get(i..).and_then(|r| r.iter().position(|&c| c == b'"')) {
|
||||
Some(at) => i += at,
|
||||
None => return,
|
||||
}
|
||||
self.matched = 1;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
self.step(b);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn step(&mut self, b: u8) {
|
||||
if let Some(v) = self.value.as_mut() {
|
||||
v.push(b);
|
||||
if self.escaped {
|
||||
self.escaped = false;
|
||||
} else if b == b'\\' {
|
||||
self.escaped = true;
|
||||
} else if b == b'"'
|
||||
&& let Some(v) = self.value.take()
|
||||
&& let Ok(s) = serde_json::from_slice::<String>(&v)
|
||||
{
|
||||
self.keys.insert(s);
|
||||
}
|
||||
} else if self.after_tag && !b.is_ascii_whitespace() {
|
||||
self.after_tag = false;
|
||||
if b == b'"' {
|
||||
self.value = Some(vec![b]);
|
||||
}
|
||||
}
|
||||
if TAG.get(self.matched) == Some(&b) {
|
||||
self.matched += 1;
|
||||
if self.matched == TAG.len() {
|
||||
self.matched = 0;
|
||||
self.after_tag = true;
|
||||
self.value = None;
|
||||
self.escaped = false;
|
||||
}
|
||||
} else {
|
||||
self.matched = usize::from(b == b'"');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write> Write for KeyScan<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.write_all(buf)?;
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
|
||||
self.scan(buf);
|
||||
self.inner.write_all(buf)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use proptest::prelude::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// How the keys were found before saves were streamed: in the whole JSON text at once.
|
||||
fn string_members(json: &[u8]) -> HashSet<String> {
|
||||
let mut out = HashSet::new();
|
||||
let mut rest = json;
|
||||
while let Some(at) = rest.windows(TAG.len()).position(|w| w == TAG) {
|
||||
rest = rest.get(at + TAG.len()..).unwrap_or_default();
|
||||
let value = rest.trim_ascii_start();
|
||||
if value.first() == Some(&b'"')
|
||||
&& let Some(Ok(s)) = serde_json::Deserializer::from_slice(value).into_iter::<String>().next()
|
||||
{
|
||||
out.insert(s);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The keys `KeyScan` finds in `json` written in pieces of `chunk` bytes.
|
||||
fn scanned(json: &[u8], chunk: usize) -> HashSet<String> {
|
||||
let mut scan = KeyScan::new(Vec::new());
|
||||
for piece in json.chunks(chunk.max(1)) {
|
||||
scan.write_all(piece).unwrap();
|
||||
}
|
||||
assert_eq!(scan.inner, json, "the text passes through");
|
||||
scan.keys
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_keys_the_whole_text_search_found() {
|
||||
let v = serde_json::json!({"key": "a", "x": [{"key": "b \"q\" \\ é"}, {"monkey": "no"}, {"k": "key"}], "s": "\"key\": \"no\"", "key2": "n", "o": {"key": 3}});
|
||||
for json in [serde_json::to_vec(&v).unwrap(), serde_json::to_vec_pretty(&v).unwrap()] {
|
||||
let want = string_members(&json);
|
||||
assert_eq!(want, HashSet::from(["a".to_string(), "b \"q\" \\ é".to_string()]));
|
||||
for chunk in [1, 2, 3, 7, 64, json.len()] {
|
||||
assert_eq!(scanned(&json, chunk), want, "chunk {chunk}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn arb_json() -> impl Strategy<Value = serde_json::Value> {
|
||||
let key = prop::sample::select(vec!["key", "k", "kkey", "key ", "x"]).prop_map(str::to_string);
|
||||
let leaf = prop_oneof![
|
||||
Just(serde_json::Value::Null),
|
||||
any::<i32>().prop_map(serde_json::Value::from),
|
||||
"[a-z\"\\\\: ké\n]{0,8}".prop_map(serde_json::Value::from),
|
||||
];
|
||||
leaf.prop_recursive(4, 32, 6, move |inner| {
|
||||
prop_oneof![
|
||||
prop::collection::vec(inner.clone(), 0..5).prop_map(serde_json::Value::from),
|
||||
prop::collection::vec((key.clone(), inner), 0..5).prop_map(|m| serde_json::Value::Object(m.into_iter().collect())),
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn scanning_in_pieces_finds_what_the_whole_text_search_found(v in arb_json(), chunk in 1usize..40, pretty in any::<bool>()) {
|
||||
let json = if pretty { serde_json::to_vec_pretty(&v) } else { serde_json::to_vec(&v) }.unwrap();
|
||||
prop_assert_eq!(scanned(&json, chunk), string_members(&json));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,38 @@ pub fn ellipse(r: Rect) -> PathData {
|
||||
PathData::single(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// Ellipse inscribed in `r` with `n` smooth anchors (at least 2) spaced evenly by angle, clockwise
|
||||
/// on screen from the left one, as [`ellipse`] runs. Each segment is a cubic whose handles are
|
||||
/// 4/3·tan(θ/4) of the tangent at its ends (θ = 360°/`n`), scaled along each axis; the path is then
|
||||
/// fitted to `r`, so its bounds are `r` whatever the count. 4 anchors give [`ellipse`].
|
||||
pub fn ellipse_with_anchors(r: Rect, n: u32) -> PathData {
|
||||
let n = n.max(2);
|
||||
let r = r.abs();
|
||||
let c = r.center();
|
||||
let (rx, ry) = (r.width() / 2.0, r.height() / 2.0);
|
||||
let step = TAU / f64::from(n);
|
||||
let k = 4.0 / 3.0 * (step / 4.0).tan();
|
||||
let anchors = (0..n)
|
||||
.map(|i| {
|
||||
// From the left anchor (angle π). With y down, sin is negative just past π, so the next
|
||||
// anchor is above the centre: left, then top, then right, as `ellipse` runs.
|
||||
let a = PI + step * f64::from(i);
|
||||
let p = Point::new(c.x + rx * a.cos(), c.y + ry * a.sin());
|
||||
let d = Vec2::new(-rx * a.sin(), ry * a.cos()) * k;
|
||||
Anchor { p, h_in: p - d, h_out: p + d, kind: AnchorKind::Smooth }
|
||||
})
|
||||
.collect();
|
||||
let path = PathData::single(SubPath::new(anchors, true));
|
||||
// Between anchors a curve can reach a little past the ellipse or stop short of it (0.15% of
|
||||
// the height with 3 anchors): fit the bounds to `r` along each axis that has a size.
|
||||
let Some(b) = path.bounds() else { return path };
|
||||
let fit = |want: f64, got: f64| if want > 0.0 && got > 0.0 { want / got } else { 1.0 };
|
||||
let (sx, sy) = (fit(r.width(), b.width()), fit(r.height(), b.height()));
|
||||
path.transformed(
|
||||
kurbo::Affine::translate(r.origin().to_vec2()) * kurbo::Affine::scale_non_uniform(sx, sy) * kurbo::Affine::translate(-b.origin().to_vec2()),
|
||||
)
|
||||
}
|
||||
|
||||
/// How an ellipse or shape arc is closed or left open when cut between start and end angles.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -693,6 +725,29 @@ mod tests {
|
||||
assert!((area - PI * 50.0 * 30.0).abs() / area < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_with_four_anchors_is_the_ellipse_and_others_fit_the_box() {
|
||||
let r = Rect::new(10.0, 20.0, 110.0, 80.0);
|
||||
let (four, plain) = (ellipse_with_anchors(r, 4), ellipse(r));
|
||||
for (a, b) in four.subpaths[0].anchors.iter().zip(&plain.subpaths[0].anchors) {
|
||||
assert!(a.p.distance(b.p) < 1e-9 && a.h_in.distance(b.h_in) < 1e-9 && a.h_out.distance(b.h_out) < 1e-9, "{a:?} {b:?}");
|
||||
}
|
||||
for n in [2, 3, 5, 7, 9, 1000] {
|
||||
let p = ellipse_with_anchors(r, n);
|
||||
assert_eq!(p.anchor_count(), n as usize);
|
||||
let b = p.bounds().unwrap();
|
||||
assert!(
|
||||
(b.x0 - r.x0).abs() < 1e-9 && (b.y0 - r.y0).abs() < 1e-9 && (b.x1 - r.x1).abs() < 1e-9 && (b.y1 - r.y1).abs() < 1e-9,
|
||||
"{n}: {b:?}"
|
||||
);
|
||||
let area = p.subpaths[0].area().abs();
|
||||
assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}");
|
||||
}
|
||||
// A box with no height leaves the path flat rather than dividing by zero.
|
||||
let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6);
|
||||
assert!(flat.subpaths[0].anchors.iter().all(|a| a.p.y == 5.0 && a.p.x.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounded_rect_clamps() {
|
||||
let p = rounded_rectangle(Rect::new(0.0, 0.0, 20.0, 10.0), 100.0);
|
||||
|
||||
@@ -244,7 +244,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"draw_shape",
|
||||
"Draw shape",
|
||||
"Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.",
|
||||
"Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius; ellipse: anchors, default 4, where any other count from 2 to 1000 draws a plain path rather than a live shape). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.",
|
||||
obj(
|
||||
with_draw_options(json!({
|
||||
"shape": {"type": "string", "enum": ["rectangle", "ellipse", "polygon", "star", "line"]},
|
||||
@@ -253,6 +253,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
"width": num("Width (rectangle/ellipse)"),
|
||||
"height": num("Height (rectangle/ellipse)"),
|
||||
"radius": num("Corner radius (rectangle) or radius (polygon)"),
|
||||
"anchors": {"type": "integer", "minimum": 2, "maximum": 1000, "description": "Ellipse anchors, spaced evenly by angle (default 4, a live ellipse; any other count draws a plain path)"},
|
||||
"cx": num("Centre x (polygon/star)"),
|
||||
"cy": num("Centre y (polygon/star)"),
|
||||
"sides": {"type": "integer", "minimum": 3, "description": "Polygon sides (default 6)"},
|
||||
|
||||
@@ -188,7 +188,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"shortcuts.exportText",
|
||||
"Export Keyboard Shortcuts as Text…",
|
||||
"",
|
||||
"{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `name<TAB>shortcut` line per row, empty after the tab when it has none; without `path`, pick a file",
|
||||
"{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `name<TAB>shortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error",
|
||||
),
|
||||
("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"),
|
||||
(
|
||||
@@ -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",
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
//! dictionary (ISO 32000-1 §14.3.3) and the XMP packet of the catalog's metadata stream (§14.3.2,
|
||||
//! ISO 16684-1). Where both give a field, the XMP packet's value is taken; a packet that can't be
|
||||
//! read leaves the information dictionary's values.
|
||||
//!
|
||||
//! File › File Info's metadata templates are XMP packets of the same properties: [`metadata_template`]
|
||||
//! writes one and [`read_template`] reads one back.
|
||||
|
||||
use craft_pdf::syntax::Pdf;
|
||||
use craft_pdf::syntax::object::{DateTime, Dict, Stream};
|
||||
@@ -19,8 +22,14 @@ 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 PHOTOSHOP: &str = "http://ns.adobe.com/photoshop/1.0/"; // brand-ok: the XMP namespace the files use
|
||||
const X: &str = "adobe:ns:meta/"; // 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 longest metadata template [`read_template`] reads, in bytes.
|
||||
pub const MAX_TEMPLATE_BYTES: usize = MAX_XMP;
|
||||
|
||||
const XMP_NAMESPACES: Canonical<'static> =
|
||||
Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF), ("photoshop", PHOTOSHOP)]); // brand-ok: the XMP namespace prefix the files use
|
||||
|
||||
/// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
@@ -29,10 +38,15 @@ pub struct FileInfo {
|
||||
pub title: Option<String>,
|
||||
/// XMP `dc:creator` (its names joined with ", "), else Info `Author`.
|
||||
pub author: Option<String>,
|
||||
/// XMP `photoshop:AuthorsPosition`.
|
||||
pub author_title: Option<String>,
|
||||
/// XMP `dc:description` (its `x-default` item, else its first), else Info `Subject`.
|
||||
pub description: Option<String>,
|
||||
/// XMP `dc:subject`, else XMP `pdf:Keywords` or Info `Keywords` split at commas and semicolons.
|
||||
pub keywords: Option<Vec<String>>,
|
||||
/// XMP `xmp:Rating`, a whole number from 0 to 5 (a rejected file's -1 and other values are
|
||||
/// left out).
|
||||
pub rating: Option<u8>,
|
||||
/// XMP `dc:rights` (its `x-default` item, else its first).
|
||||
pub copyright_notice: Option<String>,
|
||||
/// XMP `xmpRights:WebStatement`.
|
||||
@@ -77,6 +91,21 @@ fn packet(pdf: &Pdf) -> Option<Vec<u8>> {
|
||||
/// [`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> {
|
||||
read_xmp(packet, false)
|
||||
}
|
||||
|
||||
/// The File Info fields of the metadata template `bytes`, an XMP packet as [`metadata_template`]
|
||||
/// writes one (or any XMP file); `None` when it is longer than [`MAX_TEMPLATE_BYTES`], isn't XML in
|
||||
/// UTF-8 or UTF-16, has no `rdf:RDF` element, or nests more than [`MAX_NESTING`] deep.
|
||||
pub fn read_template(bytes: &[u8]) -> Option<FileInfo> {
|
||||
if bytes.len() > MAX_TEMPLATE_BYTES {
|
||||
return None;
|
||||
}
|
||||
read_xmp(bytes, true)
|
||||
}
|
||||
|
||||
/// [`xmp`]; with `need_rdf`, `None` for XML that has no `rdf:RDF` element.
|
||||
fn read_xmp(packet: &[u8], need_rdf: bool) -> Option<FileInfo> {
|
||||
let text = xml_text(packet)?;
|
||||
let opts = Options {
|
||||
names: Names::Canonical(&XMP_NAMESPACES),
|
||||
@@ -86,9 +115,12 @@ fn xmp(packet: &[u8]) -> Option<FileInfo> {
|
||||
}
|
||||
.strict();
|
||||
let root = opts.parse(text.as_bytes()).ok()?;
|
||||
let rdfs: Vec<&El> = std::iter::once(&root).chain(root.descendants()).filter(|n| n.is("rdf:RDF")).collect();
|
||||
if need_rdf && rdfs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// The resource's own descriptions: those right under `rdf:RDF`, not the ones inside a value.
|
||||
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 descriptions: Vec<&El> = rdfs.iter().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");
|
||||
@@ -96,8 +128,10 @@ fn xmp(packet: &[u8]) -> Option<FileInfo> {
|
||||
Some(FileInfo {
|
||||
title: first("dc:title"),
|
||||
author: (!creators.is_empty()).then(|| creators.join(", ")),
|
||||
author_title: first("photoshop:AuthorsPosition"), // brand-ok: the XMP property name the files use
|
||||
description: first("dc:description"),
|
||||
keywords: if subjects.is_empty() { first("pdf:Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) },
|
||||
rating: first("xmp:Rating").and_then(|r| rating(&r)),
|
||||
copyright_notice: first("dc:rights"),
|
||||
copyright_url: first("xmpRights:WebStatement"),
|
||||
copyrighted: first("xmpRights:Marked").and_then(|m| match m.to_ascii_lowercase().as_str() {
|
||||
@@ -110,6 +144,59 @@ fn xmp(packet: &[u8]) -> Option<FileInfo> {
|
||||
})
|
||||
}
|
||||
|
||||
/// An `xmp:Rating` value as File Info takes one: a whole number from 0 to 5, written as an integer
|
||||
/// or as a real with no fraction (`3`, `3.0`). The rejected rating -1, fractions and other values
|
||||
/// give `None`.
|
||||
fn rating(s: &str) -> Option<u8> {
|
||||
let r: f64 = s.trim().parse().ok()?;
|
||||
(r.fract() == 0.0 && (0.0..=5.0).contains(&r)).then_some(r as u8)
|
||||
}
|
||||
|
||||
/// The metadata template of `f`: an XMP packet (ISO 16684-1) holding its title (`dc:title`), author
|
||||
/// (`dc:creator`), author title (`photoshop:AuthorsPosition`), description (`dc:description`),
|
||||
/// keywords (`dc:subject`), rating (`xmp:Rating`), copyright status (`xmpRights:Marked`), notice
|
||||
/// (`dc:rights`) and URL (`xmpRights:WebStatement`), each where `f` gives it, which
|
||||
/// [`read_template`] reads back. The dates are left out.
|
||||
pub fn metadata_template(f: &FileInfo) -> String {
|
||||
use crate::post::xml_text as esc;
|
||||
let alt = |name: &str, v: &str| format!(" <{name}><rdf:Alt><rdf:li xml:lang=\"x-default\">{}</rdf:li></rdf:Alt></{name}>\n", esc(v));
|
||||
let simple = |name: &str, v: &str| format!(" <{name}>{}</{name}>\n", esc(v));
|
||||
let blank = |v: &Option<String>| v.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_string);
|
||||
let mut props = String::new();
|
||||
if let Some(v) = blank(&f.title) {
|
||||
props.push_str(&alt("dc:title", &v));
|
||||
}
|
||||
if let Some(v) = blank(&f.author) {
|
||||
props.push_str(&format!(" <dc:creator><rdf:Seq><rdf:li>{}</rdf:li></rdf:Seq></dc:creator>\n", esc(&v)));
|
||||
}
|
||||
if let Some(v) = blank(&f.author_title) {
|
||||
props.push_str(&simple("photoshop:AuthorsPosition", &v)); // brand-ok: the XMP property name the files use
|
||||
}
|
||||
if let Some(v) = blank(&f.description) {
|
||||
props.push_str(&alt("dc:description", &v));
|
||||
}
|
||||
let keywords: Vec<&str> = f.keywords.iter().flatten().map(|k| k.trim()).filter(|k| !k.is_empty()).collect();
|
||||
if !keywords.is_empty() {
|
||||
let items: String = keywords.iter().map(|k| format!("<rdf:li>{}</rdf:li>", esc(k))).collect();
|
||||
props.push_str(&format!(" <dc:subject><rdf:Bag>{items}</rdf:Bag></dc:subject>\n"));
|
||||
}
|
||||
if let Some(r) = f.rating {
|
||||
props.push_str(&simple("xmp:Rating", &r.to_string()));
|
||||
}
|
||||
if let Some(c) = f.copyrighted {
|
||||
props.push_str(&simple("xmpRights:Marked", if c { "True" } else { "False" }));
|
||||
}
|
||||
if let Some(v) = blank(&f.copyright_notice) {
|
||||
props.push_str(&alt("dc:rights", &v));
|
||||
}
|
||||
if let Some(v) = blank(&f.copyright_url) {
|
||||
props.push_str(&simple("xmpRights:WebStatement", &v));
|
||||
}
|
||||
format!(
|
||||
"<?xpacket begin=\"\u{FEFF}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"{X}\">\n <rdf:RDF xmlns:rdf=\"{RDF}\">\n <rdf:Description rdf:about=\"\" xmlns:dc=\"{DC}\" xmlns:xmp=\"{XMP}\" xmlns:xmpRights=\"{XMP_RIGHTS}\" xmlns:photoshop=\"{PHOTOSHOP}\">\n{props} </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>\n" // brand-ok: the XMP namespace prefix the files use
|
||||
)
|
||||
}
|
||||
|
||||
/// A packet's text: UTF-8 (with or without a byte order mark), or UTF-16 told by its byte order
|
||||
/// mark or by a zero byte beside the `<` it starts with.
|
||||
fn xml_text(b: &[u8]) -> Option<String> {
|
||||
|
||||
@@ -76,7 +76,7 @@ mod syntax;
|
||||
pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with};
|
||||
pub use encrypt::Encryption;
|
||||
pub use export::{check_page_sizes, export, export_with_report, page_areas};
|
||||
pub use file_info::{FileInfo, file_info};
|
||||
pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template};
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
pub use import::imports_of;
|
||||
pub use import::{
|
||||
|
||||
@@ -180,7 +180,7 @@ fn rights_properties(info: &DocMetadata) -> String {
|
||||
|
||||
/// `s` as XML character data: `&`, `<`, `>` and `"` escaped, a carriage return written as the
|
||||
/// character reference `
`, and the characters XML 1.0 doesn't allow left out.
|
||||
fn xml_text(s: &str) -> String {
|
||||
pub(crate) fn xml_text(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
|
||||
@@ -94,8 +94,10 @@ fn the_xmp_packet_gives_file_info() {
|
||||
FileInfo {
|
||||
title: Some("Poster".into()),
|
||||
author: Some("Ada Lovelace, Charles Babbage".into()),
|
||||
author_title: None,
|
||||
description: Some("A poster\nfor the fair".into()),
|
||||
keywords: Some(vec!["fair".into(), "print".into()]),
|
||||
rating: None,
|
||||
copyright_notice: Some("(c) 2026 Ada".into()),
|
||||
copyright_url: Some("https://example.com/rights".into()),
|
||||
copyrighted: Some(false),
|
||||
@@ -270,3 +272,48 @@ fn a_written_pdf_gives_its_copyright_back() {
|
||||
let f = file_info(&export(&d, &PdfOptions::uncompressed()).unwrap(), None).unwrap();
|
||||
assert_eq!((f.author.as_deref(), f.copyright_notice.as_deref()), (Some("Ada"), Some("(c) Ada")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metadata_template_gives_its_file_info_back() {
|
||||
let f = FileInfo {
|
||||
title: Some("Fair poster".into()),
|
||||
author: Some("Ada & <Lovelace>".into()),
|
||||
author_title: Some("Designer, \"lead\"".into()),
|
||||
description: Some("A poster\r\nfor the fair".into()),
|
||||
keywords: Some(vec!["fair".into(), "print, large".into()]),
|
||||
rating: Some(4),
|
||||
copyright_notice: Some("(c) 2026 Ada".into()),
|
||||
copyright_url: Some("https://example.com/rights?a=1&b=2".into()),
|
||||
copyrighted: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
let xmp = metadata_template(&f);
|
||||
assert!(xmp.starts_with("<?xpacket begin=") && xmp.trim_end().ends_with("<?xpacket end=\"w\"?>"), "{xmp}");
|
||||
assert_eq!(read_template(xmp.as_bytes()), Some(f));
|
||||
// A public-domain status writes Marked False; fields without a value and the dates are left out.
|
||||
let f = FileInfo { copyrighted: Some(false), author: Some(" ".into()), created: Some(CREATED), ..Default::default() };
|
||||
let xmp = metadata_template(&f);
|
||||
assert!(!xmp.contains("dc:creator") && !xmp.contains("CreateDate") && xmp.contains("<xmpRights:Marked>False</xmpRights:Marked>"), "{xmp}");
|
||||
assert_eq!(read_template(xmp.as_bytes()), Some(FileInfo { copyrighted: Some(false), ..Default::default() }));
|
||||
// The template is the PDF packet's format: a PDF whose metadata stream holds one reads the same.
|
||||
let f = FileInfo { author: Some("Ada".into()), author_title: Some("Editor".into()), rating: Some(2), ..Default::default() };
|
||||
let read = file_info(&pdf(None, Some(&metadata_template(&f))), None).unwrap();
|
||||
assert_eq!((read.author, read.author_title, read.rating), (f.author, f.author_title, f.rating));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metadata_template_reads_ratings_and_refuses_what_is_not_xmp() {
|
||||
let rated = |r: &str| read_template(packet(&description(&format!("xmp:Rating=\"{r}\""), "")).as_bytes()).unwrap().rating;
|
||||
assert_eq!([rated("0"), rated("5"), rated("3.0"), rated(" 2 ")], [Some(0), Some(5), Some(3), Some(2)]);
|
||||
// A rejected file's -1, fractions, ratings past 5 and words are left out.
|
||||
assert_eq!([rated("-1"), rated("2.5"), rated("6"), rated("high")], [None; 4]);
|
||||
// XML without `rdf:RDF`, text and a packet that isn't well-formed are not templates.
|
||||
assert_eq!(read_template(b"<root><title>Poster</title></root>"), None);
|
||||
assert_eq!(read_template(b"Ada Lovelace"), None);
|
||||
assert_eq!(read_template(packet("<rdf:Description>").as_bytes()), None);
|
||||
// An XMP packet with no File Info is a template with no fields.
|
||||
assert_eq!(read_template(packet("").as_bytes()), Some(FileInfo::default()));
|
||||
// Longer than the longest template read, it is refused without being parsed.
|
||||
let long = packet(&description("", &" ".repeat(MAX_TEMPLATE_BYTES)));
|
||||
assert_eq!(read_template(long.as_bytes()), None);
|
||||
}
|
||||
@@ -54,7 +54,7 @@ pub(crate) use face::MAX_LIVE_INSTANCES;
|
||||
pub(crate) use face::PathAlignHeights;
|
||||
pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins};
|
||||
pub(crate) use glyph_pen::FlipPen;
|
||||
pub use gsub::{GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind};
|
||||
pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use names::SysFallback;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -94,6 +94,211 @@ pub(super) struct GsubIndex {
|
||||
/// The first feature, listed ones first, that gives each glyph: by a single, multiple,
|
||||
/// alternate or ligature substitution, and the glyph it replaces (not known for a ligature).
|
||||
reached: HashMap<u32, (Tag, Option<u32>)>,
|
||||
/// The face's glyph categories ([`FontFace::glyph_categories`]), read the first time they are
|
||||
/// asked for.
|
||||
categories: std::sync::OnceLock<Vec<GlyphCategory>>,
|
||||
}
|
||||
|
||||
/// A kind of glyph that the Glyphs panel's Show menu lists by OpenType feature
|
||||
/// ([`FontFace::glyph_categories`]). The kinds, the features in each and their order are
|
||||
/// VectorCraft's own.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum GlyphCategoryKind {
|
||||
/// `liga`, `dlig` and `hlig`.
|
||||
Ligatures,
|
||||
/// `swsh` and `cswh`.
|
||||
Swashes,
|
||||
/// `salt`.
|
||||
StylisticAlternates,
|
||||
/// One of `ss01` to `ss20`, by its number.
|
||||
StylisticSet(u8),
|
||||
/// `smcp` and `c2sc`.
|
||||
SmallCaps,
|
||||
/// `ornm`.
|
||||
Ornaments,
|
||||
/// `frac`, `afrc`, `numr` and `dnom`.
|
||||
Fractions,
|
||||
/// `lnum`, `onum`, `pnum` and `tnum`.
|
||||
Figures,
|
||||
}
|
||||
|
||||
impl GlyphCategoryKind {
|
||||
/// Every kind in the order the Show menu lists them, the stylistic sets by number.
|
||||
pub fn all() -> Vec<Self> {
|
||||
let sets = (1..=20).map(Self::StylisticSet);
|
||||
[Self::Ligatures, Self::Swashes, Self::StylisticAlternates]
|
||||
.into_iter()
|
||||
.chain(sets)
|
||||
.chain([Self::SmallCaps, Self::Ornaments, Self::Fractions, Self::Figures])
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `GSUB` features whose substitutions give the kind's glyphs.
|
||||
pub fn features(self) -> Vec<[u8; 4]> {
|
||||
match self {
|
||||
Self::Ligatures => vec![*b"liga", *b"dlig", *b"hlig"],
|
||||
Self::Swashes => vec![*b"swsh", *b"cswh"],
|
||||
Self::StylisticAlternates => vec![*b"salt"],
|
||||
Self::StylisticSet(n) => {
|
||||
let [a, b] = [b'0' + n / 10 % 10, b'0' + n % 10];
|
||||
vec![[b's', b's', a, b]]
|
||||
}
|
||||
Self::SmallCaps => vec![*b"smcp", *b"c2sc"],
|
||||
Self::Ornaments => vec![*b"ornm"],
|
||||
Self::Fractions => vec![*b"frac", *b"afrc", *b"numr", *b"dnom"],
|
||||
Self::Figures => vec![*b"lnum", *b"onum", *b"pnum", *b"tnum"],
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind's id: `ligatures`, `swashes`, `stylisticAlternates`, `ss01` to `ss20`, `smallCaps`,
|
||||
/// `ornaments`, `fractions` or `figures`.
|
||||
pub fn id(self) -> String {
|
||||
match self {
|
||||
Self::Ligatures => "ligatures".into(),
|
||||
Self::Swashes => "swashes".into(),
|
||||
Self::StylisticAlternates => "stylisticAlternates".into(),
|
||||
Self::StylisticSet(n) => format!("ss{n:02}"),
|
||||
Self::SmallCaps => "smallCaps".into(),
|
||||
Self::Ornaments => "ornaments".into(),
|
||||
Self::Fractions => "fractions".into(),
|
||||
Self::Figures => "figures".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind whose [`Self::id`] is `id`.
|
||||
pub fn from_id(id: &str) -> Option<Self> {
|
||||
Self::all().into_iter().find(|k| k.id() == id)
|
||||
}
|
||||
}
|
||||
|
||||
/// The glyphs of one [`GlyphCategoryKind`] that a face has ([`FontFace::glyph_categories`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GlyphCategory {
|
||||
pub kind: GlyphCategoryKind,
|
||||
/// A stylistic set's name from the font's `name` table, when the font gives one.
|
||||
pub name: Option<String>,
|
||||
/// The glyphs the kind's features give, each once, by glyph id.
|
||||
pub glyphs: Vec<u32>,
|
||||
}
|
||||
|
||||
/// Read `face`'s glyph categories ([`FontFace::glyph_categories`]). The caps of [`GsubIndex::read`]
|
||||
/// bound what a damaged table makes it read, and all the lookups together give at most
|
||||
/// `MAX_ENTRIES` glyphs.
|
||||
fn read_categories(face: &FontFace) -> Vec<GlyphCategory> {
|
||||
let Some(font) = face.skrifa() else { return vec![] };
|
||||
let Ok(gsub) = font.gsub() else { return vec![] };
|
||||
let (Ok(features), Ok(lookups)) = (gsub.feature_list(), gsub.lookup_list()) else { return vec![] };
|
||||
let glyphs = font.maxp().map_or(0, |m| u32::from(m.num_glyphs()));
|
||||
let kinds = GlyphCategoryKind::all();
|
||||
// The lookups of each kind's features, in every script's feature records.
|
||||
let mut wanted: Vec<Vec<u16>> = vec![vec![]; kinds.len()];
|
||||
let mut total = 0_usize;
|
||||
for record in features.feature_records().iter().take(MAX_FEATURES) {
|
||||
let tag = record.feature_tag().to_be_bytes();
|
||||
let Some(k) = kinds.iter().position(|kind| kind.features().contains(&tag)) else { continue };
|
||||
let Ok(feature) = record.feature(features.offset_data()) else { continue };
|
||||
for i in feature.lookup_list_indices().iter().take(MAX_FEATURE_LOOKUPS) {
|
||||
if total >= MAX_LOOKUPS {
|
||||
break;
|
||||
}
|
||||
if !wanted[k].contains(&i.get()) {
|
||||
wanted[k].push(i.get());
|
||||
total += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let all = lookups.lookups();
|
||||
let mut reads = MAX_SUBTABLE_READS;
|
||||
// What each lookup gives, read once when several kinds share it.
|
||||
let mut read: HashMap<u16, Vec<u32>> = HashMap::new();
|
||||
// The glyphs all the lookups read together may give: at most `MAX_ENTRIES`.
|
||||
let mut left = MAX_ENTRIES;
|
||||
let mut outputs = |lookup: u16, reads: &mut usize| -> Vec<u32> {
|
||||
if let Some(out) = read.get(&lookup) {
|
||||
return out.clone();
|
||||
}
|
||||
// A lookup not read yet once the read budget is spent gives nothing, and is not cached.
|
||||
if *reads == 0 || left == 0 {
|
||||
return vec![];
|
||||
}
|
||||
// Each subtable adds only what still fits in what is left of the glyph budget.
|
||||
let cap = left;
|
||||
let mut out: Vec<u32> = vec![];
|
||||
// The glyphs an earlier subtable of the lookup covers: OpenType applies the first subtable
|
||||
// that covers a glyph, so a later one's substitution of it is never made.
|
||||
let mut covered: std::collections::HashSet<u32> = std::collections::HashSet::new();
|
||||
let mut first = |from: u32| covered.insert(from);
|
||||
if let Ok(subtables) = all.get(usize::from(lookup)).and_then(|l| l.subtables()) {
|
||||
let n = MAX_SUBTABLES.min(*reads);
|
||||
let room = |out: &Vec<u32>| cap.saturating_sub(out.len());
|
||||
match subtables {
|
||||
SubstitutionSubtables::Single(s) => {
|
||||
for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() {
|
||||
let r = room(&out);
|
||||
out.extend(single_pairs(&t, r).into_iter().filter(|(from, _)| first(*from)).map(|(_, to)| to).take(r));
|
||||
if room(&out) == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
SubstitutionSubtables::Alternate(s) => {
|
||||
for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() {
|
||||
let r = room(&out);
|
||||
out.extend(alternate_sets(&t, r).into_iter().filter(|(from, _)| first(*from)).flat_map(|(_, set)| set).take(r));
|
||||
if room(&out) == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
SubstitutionSubtables::Multiple(s) => {
|
||||
for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() {
|
||||
let r = room(&out);
|
||||
out.extend(multiple_pairs(&t, r).into_iter().filter(|(from, _)| first(*from)).flat_map(|(_, to)| to).take(r));
|
||||
if room(&out) == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
SubstitutionSubtables::Ligature(s) => {
|
||||
for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() {
|
||||
let r = room(&out);
|
||||
out.extend(ligature_glyphs(&t, r).into_iter().take(r));
|
||||
if room(&out) == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
left = left.saturating_sub(out.len());
|
||||
read.insert(lookup, out.clone());
|
||||
out
|
||||
};
|
||||
let names = face.stylistic_sets();
|
||||
let mut categories = vec![];
|
||||
for (kind, lookups) in kinds.into_iter().zip(wanted) {
|
||||
let mut found: Vec<u32> = vec![];
|
||||
for lookup in lookups {
|
||||
let room = MAX_ENTRIES.saturating_sub(found.len());
|
||||
found.extend(outputs(lookup, &mut reads).into_iter().filter(|g| *g != 0 && *g < glyphs).take(room));
|
||||
if found.len() >= MAX_ENTRIES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
found.sort_unstable();
|
||||
found.dedup();
|
||||
found.truncate(MAX_ENTRIES);
|
||||
if found.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let name = match kind {
|
||||
GlyphCategoryKind::StylisticSet(n) => names.iter().find(|s| s.number == n).and_then(|s| s.name.clone()),
|
||||
_ => None,
|
||||
};
|
||||
categories.push(GlyphCategory { kind, name, glyphs: found });
|
||||
}
|
||||
categories
|
||||
}
|
||||
|
||||
/// The glyph single substitution `t` puts in place of each glyph its coverage holds.
|
||||
@@ -383,4 +588,70 @@ impl FontFace {
|
||||
let name = font.glyph_names().get(skrifa::GlyphId::new(gid))?;
|
||||
(!name.is_synthesized()).then(|| name.as_str().to_string())
|
||||
}
|
||||
|
||||
/// The kinds of glyph the face's `GSUB` table gives ([`GlyphCategoryKind`]), in the order of
|
||||
/// [`GlyphCategoryKind::all`], each with the glyphs that the single, alternate, multiple and
|
||||
/// ligature substitutions of its features put in place of others (in extension lookups too),
|
||||
/// each glyph once by id, `.notdef` and ids past the face's glyph count left out. A single,
|
||||
/// alternate or multiple substitution of a glyph an earlier subtable of its lookup covers is
|
||||
/// left out, since that substitution is never made. A kind
|
||||
/// without glyphs is left out. A stylistic set takes its name from the font's `name` table,
|
||||
/// when the font gives one. Contextual lookups are not followed, nor is the choice of a
|
||||
/// variable font's instance of `FeatureVariations`. Read once for the face; empty when it has
|
||||
/// no `GSUB` table or the table cannot be read.
|
||||
pub fn glyph_categories(&self) -> &[GlyphCategory] {
|
||||
self.gsub_index().categories.get_or_init(|| read_categories(self))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The test font lists ligatures, stylistic set 2 with its name, small caps and figures, by
|
||||
/// glyph id; its `cswh` feature has no lookups, so it lists no swashes, and small caps leave out
|
||||
/// the C of a substitution an earlier subtable shadows.
|
||||
#[test]
|
||||
fn categories_list_the_glyphs_each_kind_of_feature_gives() {
|
||||
use crate::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid};
|
||||
let db = super::super::FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(categories_font().expect("the test font builds")), 1);
|
||||
let face = db.face(CATEGORIES_FAMILY, "Regular").expect("the test face");
|
||||
let g = |c| u32::from(source_sans_gid(c).expect("a glyph"));
|
||||
let mut figures = vec![g('7'), g('8')];
|
||||
figures.sort_unstable();
|
||||
let found: Vec<(String, Option<String>, Vec<u32>)> =
|
||||
face.glyph_categories().iter().map(|c| (c.kind.id(), c.name.clone(), c.glyphs.clone())).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
("ligatures".to_string(), None, vec![g('L')]),
|
||||
("ss02".to_string(), Some("Round Dots".to_string()), vec![g('G')]),
|
||||
("smallCaps".to_string(), None, vec![g('B')]),
|
||||
("figures".to_string(), None, figures),
|
||||
]
|
||||
);
|
||||
assert!(std::ptr::eq(face.glyph_categories(), face.glyph_categories()), "read once");
|
||||
}
|
||||
|
||||
/// A face whose `GSUB` table has no features has no categories.
|
||||
#[test]
|
||||
fn a_face_without_features_has_no_categories() {
|
||||
use crate::test_fonts::{HALF_FORM_FAMILY, half_form_font};
|
||||
let db = super::super::FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(half_form_font(false).expect("the test font builds")), 1);
|
||||
let face = db.face(HALF_FORM_FAMILY, "Regular").expect("the test face");
|
||||
assert!(face.glyph_categories().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_round_trip_through_their_ids() {
|
||||
for kind in GlyphCategoryKind::all() {
|
||||
assert_eq!(GlyphCategoryKind::from_id(&kind.id()), Some(kind));
|
||||
}
|
||||
assert_eq!(GlyphCategoryKind::StylisticSet(7).features(), [*b"ss07"]);
|
||||
assert_eq!(GlyphCategoryKind::StylisticSet(20).features(), [*b"ss20"]);
|
||||
assert_eq!(GlyphCategoryKind::from_id("ss21"), None);
|
||||
assert_eq!(GlyphCategoryKind::from_id("Ligatures"), None);
|
||||
}
|
||||
}
|
||||
@@ -41,10 +41,10 @@ pub use features::{
|
||||
EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by,
|
||||
};
|
||||
pub use fontdb::{
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins,
|
||||
JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir,
|
||||
is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight,
|
||||
system_font_dirs, user_font_dirs,
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphCategory,
|
||||
GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind,
|
||||
WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs,
|
||||
set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
|
||||
};
|
||||
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
|
||||
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
|
||||
|
||||
@@ -901,6 +901,66 @@ pub fn capped_candidates_font() -> Option<Vec<u8>> {
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`categories_font`].
|
||||
pub const CATEGORIES_FAMILY: &str = "Categorytest Sans";
|
||||
|
||||
/// The bundled Source Sans 3 Regular, its `cmap` kept, with a `GSUB` table of a `liga` ligature of
|
||||
/// f and i into L, an `onum` alternate substitution of 1 by 7 and 8, an `smcp` single substitution
|
||||
/// of a by B (a second subtable's substitution of a by C is shadowed by it), an `ss02` single substitution of g by G named "Round Dots" (name id 256), and a
|
||||
/// `cswh` feature without lookups. Family [`CATEGORIES_FAMILY`]. `None` when it can't be built.
|
||||
pub fn categories_font() -> Option<Vec<u8>> {
|
||||
use write_fonts::tables::gsub::{
|
||||
AlternateSet, AlternateSubstFormat1, Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SingleSubst, SingleSubstFormat2, SubstitutionLookup,
|
||||
SubstitutionLookupList,
|
||||
};
|
||||
use write_fonts::tables::layout::{
|
||||
CoverageFormat1, Feature, FeatureList, FeatureParams, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord, StylisticSetParams,
|
||||
};
|
||||
use write_fonts::types::GlyphId16;
|
||||
|
||||
let font = skrifa::FontRef::new(SOURCE_SANS).ok()?;
|
||||
let charmap = font.charmap();
|
||||
let name = name_table(&[
|
||||
(1, CATEGORIES_FAMILY),
|
||||
(2, "Regular"),
|
||||
(4, "Categorytest Sans Regular"),
|
||||
(6, "CategorytestSans-Regular"),
|
||||
(256, "Round Dots"),
|
||||
])?;
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_raw(Tag::new(b"name"), name);
|
||||
let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?));
|
||||
let cover = |c| Some(CoverageFormat1::new(vec![gid(c)?]));
|
||||
let single = |from, to| Some(SingleSubst::from(SingleSubstFormat2::new(cover(from)?.into(), vec![gid(to)?])));
|
||||
let liga = LigatureSubstFormat1::new(cover('f')?.into(), vec![LigatureSet::new(vec![Ligature::new(gid('L')?, vec![gid('i')?])])]);
|
||||
let onum = AlternateSubstFormat1::new(cover('1')?.into(), vec![AlternateSet::new(vec![gid('7')?, gid('8')?])]);
|
||||
let lookups = SubstitutionLookupList::new(vec![
|
||||
SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![liga])),
|
||||
SubstitutionLookup::Alternate(Lookup::new(Default::default(), vec![onum])),
|
||||
// The second subtable's substitution of a is never made: the first one covers a.
|
||||
SubstitutionLookup::Single(Lookup::new(Default::default(), vec![single('a', 'B')?, single('a', 'C')?])),
|
||||
SubstitutionLookup::Single(Lookup::new(Default::default(), vec![single('g', 'G')?])),
|
||||
]);
|
||||
let named = Some(FeatureParams::StylisticSet(StylisticSetParams::new(NameId::new(256))));
|
||||
// Features sorted by tag, as OpenType requires.
|
||||
let records = vec![
|
||||
FeatureRecord::new(Tag::new(b"cswh"), Feature::new(None, vec![])),
|
||||
FeatureRecord::new(Tag::new(b"liga"), Feature::new(None, vec![0])),
|
||||
FeatureRecord::new(Tag::new(b"onum"), Feature::new(None, vec![1])),
|
||||
FeatureRecord::new(Tag::new(b"smcp"), Feature::new(None, vec![2])),
|
||||
FeatureRecord::new(Tag::new(b"ss02"), Feature::new(named, vec![3])),
|
||||
];
|
||||
let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0, 1, 2, 3, 4])), vec![]))]);
|
||||
builder.add_table(&Gsub::new(scripts, FeatureList::new(records), lookups)).ok()?;
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
|
||||
}
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`joining_alternates_font`].
|
||||
pub const JOINING_ALTERNATES_FAMILY: &str = "Jointest Sans";
|
||||
|
||||
|
||||
@@ -256,12 +256,20 @@ enum LpDragFrom {
|
||||
/// The faces among `faces` (a Live Paint group's faces, back to front) that a drag along the path
|
||||
/// chunks `chunks` crosses, as `livePaint.fill` finds them, each with its fill.
|
||||
fn crossed_faces(faces: &[Arc<Node>], chunks: &[Vec<Point>]) -> Vec<(NodeId, Paint)> {
|
||||
// Only a face whose bounds meet the drag's bounds can be crossed.
|
||||
let Some(drag) = chunks.iter().flatten().fold(None, |r: Option<Rect>, p| Some(r.map_or(Rect::from_points(*p, *p), |r| r.union_pt(*p)))) else {
|
||||
return vec![];
|
||||
};
|
||||
let mut hit = vec![];
|
||||
let mut regions = vec![];
|
||||
// Front first, as visible_face_at looks.
|
||||
for f in faces.iter().rev().filter(|f| f.visible) {
|
||||
if let Some(path) = f.path_data()
|
||||
&& let Some(bounds) = path.bounds()
|
||||
&& bounds.x0 <= drag.x1
|
||||
&& drag.x0 <= bounds.x1
|
||||
&& bounds.y0 <= drag.y1
|
||||
&& drag.y0 <= bounds.y1
|
||||
{
|
||||
hit.push(f);
|
||||
regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds));
|
||||
@@ -487,8 +495,8 @@ impl LivePaintBucketTool {
|
||||
/// The paint `part` had before the first press of a click sequence of `clicks` presses that
|
||||
/// painted `part`, or before the double-click after a press when that double-click reached it
|
||||
/// (the sequence's first press counts when it made the group `part` is in and the face it
|
||||
/// filled there is `part`), a press's drag or release crossing `part` included; `now` when the
|
||||
/// last press did not paint it.
|
||||
/// filled there is `part`), a press's drag or release crossing `part` included; `now` when no
|
||||
/// press of the sequence painted `part` and the last press's drag did not cross it.
|
||||
fn before(&self, cx: &ToolContext, part: NodeId, clicks: usize, now: Paint) -> Paint {
|
||||
let Some(run) = self.presses.len().checked_sub(clicks).and_then(|from| self.presses.get(from..)) else { return now };
|
||||
let made_part = |at: Point| live_paint_at(cx.doc, at).and_then(|g| visible_face_at(cx.doc.node(g)?, at)).is_some_and(|f| f.id == part);
|
||||
@@ -541,8 +549,11 @@ impl LivePaintBucketTool {
|
||||
if clicks == 2
|
||||
&& let Some(group) = cx.doc.node(g)
|
||||
{
|
||||
// The other edge either click painted joins as the stroke paint it had before.
|
||||
let through: Vec<NodeId> = self
|
||||
// The other edge of this group either click painted joins as the stroke paint it
|
||||
// had before. A face either click filled is not an edge and does not join.
|
||||
let group_edges: std::collections::HashSet<NodeId> = edges(group).iter().map(|x| x.id).collect();
|
||||
let mut through: Vec<NodeId> = vec![];
|
||||
for id in self
|
||||
.presses
|
||||
.len()
|
||||
.checked_sub(2)
|
||||
@@ -552,8 +563,11 @@ impl LivePaintBucketTool {
|
||||
.flatten()
|
||||
.filter(|q| q.before == like)
|
||||
.filter_map(|q| q.part)
|
||||
.filter(|id| *id != e.id)
|
||||
.collect();
|
||||
{
|
||||
if id != e.id && group_edges.contains(&id) && !through.contains(&id) {
|
||||
through.push(id);
|
||||
}
|
||||
}
|
||||
self.note_reached(group, connected_edges_through(group, e.id, &like, &through), true);
|
||||
if !through.is_empty() {
|
||||
v["through"] = json_ids(&through);
|
||||
@@ -797,7 +811,7 @@ impl Tool for LivePaintBucketTool {
|
||||
self.at = None;
|
||||
}
|
||||
|
||||
/// A press the view tools took counts as a press that paints no face or edge, for the clicks
|
||||
/// A press that did not reach the tool counts as a press that paints no face or edge, for the clicks
|
||||
/// a double-click or triple-click compares.
|
||||
fn press_elsewhere(&mut self) {
|
||||
self.note_press(None);
|
||||
|
||||
@@ -22,6 +22,8 @@
|
||||
//! has moved, switches the Blob Brush to the Smooth tool: the drag smooths the selected paths.
|
||||
//! Alt held at a Paintbrush press with a selected path also smooths; Alt pressed after its stroke
|
||||
//! begins closes the path on release.
|
||||
//! Alt held at the Eraser's press draws a marquee instead of a stroke, a square while Shift is
|
||||
//! held, and the release erases everything inside it.
|
||||
//! Alt held at the Knife's press makes it cut along the straight line from the press point to the
|
||||
//! pointer, even if Alt is released during the drag. Shift on each drag or release constrains that
|
||||
//! line to 45° steps from the canvas axes.
|
||||
@@ -163,6 +165,11 @@ pub struct GestureTool {
|
||||
/// The pointer has moved from the press point, by any distance (a move too short to add a
|
||||
/// point counts).
|
||||
moved: bool,
|
||||
/// Active Eraser drag draws a marquee (Alt held at the press): the release erases the
|
||||
/// rectangle from the press point to the pointer, a square while Shift is held.
|
||||
marquee: bool,
|
||||
/// Shift was held at the last event of the Eraser's marquee drag.
|
||||
square: bool,
|
||||
/// Active Pencil drag draws a straight line (Shift or Alt held at the press), or active Knife
|
||||
/// drag cuts along one (Alt held at the press): the stroke is the press point and the pointer.
|
||||
straight: bool,
|
||||
@@ -871,6 +878,8 @@ impl GestureTool {
|
||||
smooth_fidelity: SMOOTH_FIDELITY,
|
||||
smoothing: false,
|
||||
moved: false,
|
||||
marquee: false,
|
||||
square: false,
|
||||
straight: false,
|
||||
unconstrained: false,
|
||||
shift_line: None,
|
||||
@@ -996,6 +1005,11 @@ impl GestureTool {
|
||||
self.id == "blobBrush" && m.alt && !self.moved
|
||||
}
|
||||
|
||||
/// Would a press with `m` held draw the Eraser's marquee? Alt held at the press.
|
||||
fn alt_marquee(&self, m: Mods) -> bool {
|
||||
self.id == "eraser" && m.alt
|
||||
}
|
||||
|
||||
/// Shift keeps an active straight Knife cut at 45° steps; without Shift it follows the pointer.
|
||||
/// Releasing Alt does not end a straight cut.
|
||||
fn knife_shift(&mut self, m: Mods) {
|
||||
@@ -1059,6 +1073,43 @@ impl GestureTool {
|
||||
]
|
||||
}
|
||||
|
||||
/// The Eraser's marquee: the rectangle from the press point to the pointer, or with Shift held
|
||||
/// the square on the larger of its sides, in the direction the pointer went. `None` outside a
|
||||
/// marquee drag.
|
||||
fn marquee_rect(&self) -> Option<Rect> {
|
||||
let (&a, &b) = (self.points.first()?, self.points.last()?);
|
||||
if !self.marquee {
|
||||
return None;
|
||||
}
|
||||
let d = b - a;
|
||||
let b = if self.square {
|
||||
let side = d.x.abs().max(d.y.abs());
|
||||
a + Vec2::new(side.copysign(d.x), side.copysign(d.y))
|
||||
} else {
|
||||
b
|
||||
};
|
||||
Some(Rect::from_points(a, b))
|
||||
}
|
||||
|
||||
/// A drag or the release of the Eraser's marquee: the marquee runs from the press point to the
|
||||
/// pointer, and the release erases it. `None` for any other event.
|
||||
fn marquee_pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option<Vec<Action>> {
|
||||
if !(self.active && self.marquee && matches!(ev.kind, PointerKind::Drag | PointerKind::Up)) {
|
||||
return None;
|
||||
}
|
||||
self.square = ev.mods.shift;
|
||||
self.points.truncate(1);
|
||||
self.points.push(ev.pos);
|
||||
if !matches!(ev.kind, PointerKind::Up) {
|
||||
return Some(vec![]);
|
||||
}
|
||||
let out = self.finish(cx, ev.mods);
|
||||
self.active = false;
|
||||
self.marquee = false;
|
||||
self.clear();
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Forget the stroke.
|
||||
fn clear(&mut self) {
|
||||
self.moved = false;
|
||||
@@ -1422,6 +1473,13 @@ impl GestureTool {
|
||||
}
|
||||
return vec![];
|
||||
}
|
||||
if let Some(r) = self.marquee_rect() {
|
||||
// A click, or a drag along one axis, encloses no area: nothing is erased.
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 || r.width().max(r.height()) < cx.tol(1.0) {
|
||||
return vec![];
|
||||
}
|
||||
return vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [r.x0, r.y0, r.width(), r.height()]}))];
|
||||
}
|
||||
match self.id {
|
||||
"pencil" | "paintbrush" => {
|
||||
if !self.began {
|
||||
@@ -1497,6 +1555,9 @@ impl Tool for GestureTool {
|
||||
if self.varies_size() {
|
||||
self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p);
|
||||
}
|
||||
if let Some(out) = self.marquee_pointer(cx, ev) {
|
||||
return out;
|
||||
}
|
||||
match ev.kind {
|
||||
PointerKind::Down => {
|
||||
self.active = true;
|
||||
@@ -1513,6 +1574,9 @@ impl Tool for GestureTool {
|
||||
// too, the line keeps Shift's 45° steps. Alt makes the Knife cut along a straight line.
|
||||
self.straight = (self.id == "pencil" && !self.smoothing && (ev.mods.shift || ev.mods.alt)) || (self.id == "knife" && ev.mods.alt);
|
||||
self.unconstrained = self.straight && !ev.mods.shift;
|
||||
// Alt makes the Eraser draw a marquee, and Shift keeps it square.
|
||||
self.marquee = self.alt_marquee(ev.mods);
|
||||
self.square = ev.mods.shift;
|
||||
let extend = if self.draws_path() && !self.smoothing { self.find_extend(cx, p) } else { None };
|
||||
self.set_extend(cx, extend);
|
||||
// The stroke's previews select the path it continues, so the others are kept now.
|
||||
@@ -1694,6 +1758,7 @@ impl Tool for GestureTool {
|
||||
self.smoothing = false;
|
||||
self.straight = false;
|
||||
self.unconstrained = false;
|
||||
self.marquee = false;
|
||||
self.clear();
|
||||
if began { vec![Action::Cancel] } else { vec![] }
|
||||
}
|
||||
@@ -1726,6 +1791,7 @@ impl Tool for GestureTool {
|
||||
self.smoothing = false;
|
||||
self.straight = false;
|
||||
self.unconstrained = false;
|
||||
self.marquee = false;
|
||||
self.clear();
|
||||
if began { stale.into_iter().chain([Action::Commit]).collect() } else { vec![] }
|
||||
}
|
||||
@@ -1733,6 +1799,14 @@ impl Tool for GestureTool {
|
||||
self.area_pending.set(false);
|
||||
self.band_pending.set(false);
|
||||
let mut o = self.snap.guides().to_vec();
|
||||
// The Eraser's marquee shows without the tip outline.
|
||||
if self.active
|
||||
&& self.points.len() >= 2
|
||||
&& let Some(r) = self.marquee_rect()
|
||||
{
|
||||
o.push(Overlay::Marquee(r));
|
||||
return o;
|
||||
}
|
||||
// A path being drawn shows itself, except with the Pencil's Live preview off.
|
||||
if !self.active || self.points.len() < 2 || (self.began && self.previews()) {
|
||||
o.extend(self.tip_outline(cx));
|
||||
|
||||
@@ -2032,6 +2032,82 @@ fn eraser_and_knife_exec_on_release() {
|
||||
assert!(matches!(&a[0], Action::Exec(c, v) if c == "path.knife" && v["points"].as_array().unwrap().len() == 3));
|
||||
}
|
||||
|
||||
/// An Alt-drag with the Eraser shows a marquee from the press point to the pointer, without the
|
||||
/// tip outline, and the release erases that rectangle; a drag back up and left gives the same
|
||||
/// kind of rectangle, measured from its top-left corner.
|
||||
#[test]
|
||||
fn eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let mut t = GestureTool::new("eraser");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 170.0).with_mods(alt));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 250.0, 190.0).with_mods(alt));
|
||||
assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(50.0, 150.0, 250.0, 190.0))]);
|
||||
let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 200.0).with_mods(alt));
|
||||
assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [50.0, 150.0, 200.0, 50.0]}))]);
|
||||
assert!(!t.busy() && t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_))));
|
||||
// A click erases nothing.
|
||||
let acts = drag_held(&mut t, &cx, &[(250.0, 200.0)], alt);
|
||||
assert!(acts.iter().all(Vec::is_empty), "a click: {acts:?}");
|
||||
// Alt only at the press is enough, and the drag can go up and left of the press point.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 250.0, 200.0).with_mods(alt));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 120.0));
|
||||
let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 120.0));
|
||||
assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [100.0, 120.0, 150.0, 80.0]}))]);
|
||||
// Without Alt the drag is a stroke.
|
||||
let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default());
|
||||
assert!(matches!(&acts[2][0], Action::Exec(c, v) if c == "path.eraseRegion" && v.get("rect").is_none() && v["points"].is_array()));
|
||||
}
|
||||
|
||||
/// Alt+Shift keeps the Eraser's marquee square on its larger side, in the direction the pointer
|
||||
/// went; Shift can be pressed or let go during the drag.
|
||||
#[test]
|
||||
fn eraser_alt_shift_drag_keeps_the_marquee_square() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let alt_shift = Mods { alt: true, shift: true, ..Mods::default() };
|
||||
let mut t = GestureTool::new("eraser");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(alt_shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 170.0).with_mods(alt_shift));
|
||||
assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(200.0, 140.0, 260.0, 200.0))]);
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 170.0).with_mods(alt));
|
||||
assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(200.0, 170.0, 260.0, 200.0))], "Shift let go");
|
||||
let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 190.0, 280.0).with_mods(alt_shift));
|
||||
assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [120.0, 200.0, 80.0, 80.0]}))]);
|
||||
// A drag along one axis gives a square too.
|
||||
let acts = drag_held(&mut t, &cx, &[(100.0, 100.0), (100.0, 140.0)], alt_shift);
|
||||
assert_eq!(acts[2], vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [100.0, 100.0, 40.0, 40.0]}))]);
|
||||
}
|
||||
|
||||
/// A marquee that encloses no area erases nothing, and Escape during the drag cancels the marquee:
|
||||
/// the release that follows sends nothing.
|
||||
#[test]
|
||||
fn eraser_marquee_click_or_escape_erases_nothing() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let mut t = GestureTool::new("eraser");
|
||||
let acts = drag_held(&mut t, &cx, &[(100.0, 100.0), (100.0, 160.0)], alt);
|
||||
assert!(acts.iter().all(Vec::is_empty), "a drag along one axis: {acts:?}");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(alt));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(alt));
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![]);
|
||||
assert!(!t.busy() && t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_))));
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(alt)), vec![]);
|
||||
// The next plain drag erases a stroke.
|
||||
let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default());
|
||||
assert!(matches!(&acts[2][0], Action::Exec(c, v) if c == "path.eraseRegion" && v["points"].is_array()));
|
||||
}
|
||||
|
||||
/// The points of the Knife's release command.
|
||||
fn knife_points(acts: &[Action]) -> Vec<(f64, f64)> {
|
||||
let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") };
|
||||
|
||||
@@ -291,8 +291,8 @@ pub trait Tool: Send {
|
||||
/// another document became active. The Blend tool drops its first pick and stops adding to the
|
||||
/// blend it just made.
|
||||
fn history_moved(&mut self) {}
|
||||
/// A press on the canvas went to the view tools (held Space, the middle button) and not to the
|
||||
/// tool. The Live Paint Bucket counts it among the clicks a triple-click compares.
|
||||
/// A press on the canvas did not reach the tool: it went to the view tools (held Space, the
|
||||
/// middle button), or with Cmd/Ctrl held to the selection tool the session lends. The Live Paint Bucket counts it among the clicks a triple-click compares.
|
||||
fn press_elsewhere(&mut self) {}
|
||||
/// Time passes while the pointer button is held (`dt` seconds since the last tick, whether or
|
||||
/// not the pointer moved): tools that keep working while the brush holds still (Twirl, Pucker,
|
||||
|
||||
@@ -51,6 +51,8 @@ const ROWS: &[Row] = &[
|
||||
(&["livePaintBucket"], None, &["paintFills", "paintStrokes", "cursorSwatchPreview", "highlight", "color", "width"]),
|
||||
(&["polygon"], None, &["sides"]),
|
||||
(&["star"], None, &["points"]),
|
||||
// The Ellipse dialog's Anchors.
|
||||
(&["ellipse"], None, &["anchors"]),
|
||||
(&["freeTransform"], None, &["constrain"]),
|
||||
// Shape Builder Tool Options (`builder::ShapeBuilderOptions`).
|
||||
(
|
||||
|
||||
@@ -84,6 +84,9 @@ pub struct ShapeTool {
|
||||
began: bool,
|
||||
pub sides: u32,
|
||||
pub points: u32,
|
||||
/// The anchors an ellipse made by a click has (the Ellipse dialog opens on it); 4 is a live
|
||||
/// ellipse.
|
||||
pub anchors: u32,
|
||||
pub corner_radius: f64,
|
||||
/// Star inner radius as a fraction of the outer radius.
|
||||
pub star_ratio: f64,
|
||||
@@ -146,6 +149,7 @@ impl ShapeTool {
|
||||
began: false,
|
||||
sides: 6,
|
||||
points: 5,
|
||||
anchors: 4,
|
||||
corner_radius: 12.0,
|
||||
star_ratio: 0.5,
|
||||
inner: None,
|
||||
@@ -787,6 +791,7 @@ impl Tool for ShapeTool {
|
||||
json!({
|
||||
"sides": self.sides,
|
||||
"points": self.points,
|
||||
"anchors": self.anchors,
|
||||
"cornerRadius": self.corner_radius,
|
||||
"starRatio": self.star_ratio,
|
||||
"length": self.line_length,
|
||||
@@ -799,6 +804,7 @@ impl Tool for ShapeTool {
|
||||
match key {
|
||||
"sides" => self.sides = v.as_u64().unwrap_or(6).clamp(3, 1000) as u32,
|
||||
"points" => self.points = v.as_u64().unwrap_or(5).clamp(3, 1000) as u32,
|
||||
"anchors" => self.anchors = v.as_u64().unwrap_or(4).clamp(2, 1000) as u32,
|
||||
"cornerRadius" => self.corner_radius = finite.unwrap_or(12.0).clamp(0.0, MAX_CORNER_RADIUS),
|
||||
"starRatio" => self.star_ratio = v.as_f64().unwrap_or(0.5).clamp(0.01, 1.0),
|
||||
"length" => self.line_length = finite.map_or(self.line_length, |n| n.abs().min(1e6)),
|
||||
|
||||
@@ -536,3 +536,93 @@ fn other_panes_draw_through_their_documents_profiles() {
|
||||
assert!(close(shown, device), "the back CMYK document draws through its Device CMYK: {shown:?}, not {device:?} (front: {front:?})");
|
||||
assert!(near(cms::active().display_rgb(&color).map(|v| (v * 255.0).round() as u8), p3), "the front document's profile stays active");
|
||||
}
|
||||
|
||||
/// With a display profile, the tiled pane of a document behind the front one blends its
|
||||
/// translucent art with that document's own simulated paper in sRGB, then converts the blend:
|
||||
/// drawn over its converted paper, the pane shows the converted blend, not the art converted alone
|
||||
/// and not a blend with the front document's paper. Opaque and empty pixels convert as before.
|
||||
#[test]
|
||||
fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_conversion() {
|
||||
use crate::display_profile::{Found, Reading};
|
||||
let mut app = app_with(2);
|
||||
app.canvas.panes.worker_started = true; // every pane renders on this thread
|
||||
let (front_paper, back_paper) = ([0x20, 0x40, 0xc0], [0xe0, 0xc0, 0x20]);
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("document.setup", json!({"gridColors": ["#2040c0", "#ffffff"], "simulatePaper": true})).unwrap();
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
app.run("document.setup", json!({"gridColors": ["#e0c020", "#ffffff"], "simulatePaper": true})).unwrap();
|
||||
let half = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap()["id"].clone();
|
||||
app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap();
|
||||
app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
let uid = app.session.documents()[1].uid;
|
||||
let ctx = egui::Context::default();
|
||||
// The second document's pane: the raster one frame uploads, its width, and the key it was rendered for.
|
||||
let pane = |app: &mut VectorcraftApp| -> (Vec<Color32>, usize, CacheKey) {
|
||||
let raw = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))),
|
||||
max_texture_side: Some(8192),
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = ctx.run_ui(raw, |ui| app.canvas_area(ui));
|
||||
let (key, tex) = app.canvas.panes.shown.iter().find(|(slot, _)| slot.0 == uid).map(|(_, s)| s).expect("the second document's pane rendered");
|
||||
let id = tex.id();
|
||||
let up = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| {
|
||||
let egui::ImageData::Color(img) = &d.image;
|
||||
(img.pixels.clone(), img.width())
|
||||
});
|
||||
let key = key.clone();
|
||||
out.textures_delta.clear();
|
||||
let (pixels, width) = up.expect("the pane uploads");
|
||||
(pixels, width, key)
|
||||
};
|
||||
app.session.prefs.monitor_profile_display = false;
|
||||
let (srgb, width, key) = pane(&mut app);
|
||||
assert!(key.backdrop.is_none(), "no display profile: nothing to blend");
|
||||
let p3 = crate::display_profile::tests::p3();
|
||||
let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap();
|
||||
app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } });
|
||||
app.session.prefs.monitor_profile_display = true;
|
||||
let (shown, _, key) = pane(&mut app);
|
||||
let backdrop = key.backdrop.as_deref().expect("the pane's Preview blends with its paper");
|
||||
assert!(
|
||||
!backdrop.artboards.is_empty() && backdrop.artboards.iter().all(|(_, c)| *c == back_paper),
|
||||
"the pane blends with its own document's paper: {backdrop:?}"
|
||||
);
|
||||
assert_eq!(srgb.len(), shown.len());
|
||||
// What the canvas shows of pixel `c` over the converted paper `under`, as egui blends it.
|
||||
let over = |c: Color32, under: [u8; 3]| {
|
||||
let k = 255 - u32::from(c.a());
|
||||
[0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255)
|
||||
};
|
||||
let plain = |s: Color32| {
|
||||
let mut px = s.to_array();
|
||||
t.apply_premultiplied(&mut px);
|
||||
Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3])
|
||||
};
|
||||
// Pixel `s` over the paper `paper` in sRGB, converted.
|
||||
let blend = |s: Color32, paper: [u8; 3]| {
|
||||
let k = 255 - u32::from(s.a());
|
||||
t.apply8([0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (u32::from(paper[j]) * k + 127) / 255).min(255) as u8)).map(u32::from)
|
||||
};
|
||||
let differs = |a: [u32; 3], b: [u32; 3]| (0..3).any(|j| a[j].abs_diff(b[j]) > 2);
|
||||
let under = t.apply8(back_paper);
|
||||
for (s, c) in srgb.iter().zip(&shown) {
|
||||
if s.a() == 0 || s.a() == 255 {
|
||||
assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before");
|
||||
}
|
||||
}
|
||||
// The middle of the pane is the middle of the document, inside the 50% fill.
|
||||
let at = srgb.len() / width / 2 * width + width / 2;
|
||||
let (s, c) = (srgb[at], shown[at]);
|
||||
assert!((50..=205).contains(&s.a()), "the 50% fill at the middle: {s:?}");
|
||||
assert_eq!(c.a(), s.a(), "the alpha is kept");
|
||||
let want = blend(s, back_paper);
|
||||
let got = over(c, under);
|
||||
assert!((0..3).all(|j| got[j].abs_diff(want[j]) <= 1), "{got:?} shown, {want:?} wanted");
|
||||
// The check tells the two papers and the plain conversion apart.
|
||||
assert!(differs(want, blend(s, front_paper)), "the front document's paper blends to another color");
|
||||
assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color");
|
||||
}
|
||||
@@ -777,6 +777,61 @@ fn bucket_modifier_only_hover_updates_the_visible_cursor() {
|
||||
assert!(chips(&mut app) > 0);
|
||||
}
|
||||
|
||||
/// A press between a Live Paint Bucket triple-click's clicks that the view tools take (a
|
||||
/// middle-button pan, a pan with Space held) counts as a press that paints nothing: the
|
||||
/// triple-click matches the fill the face had before the first click.
|
||||
#[test]
|
||||
fn bucket_triple_click_with_a_view_tool_press_between_matches_the_fill_before() {
|
||||
use egui::{Event, Modifiers, PointerButton};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
for case in ["middle", "space"] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let ids: Vec<u64> = [0.0, 50.0, 100.0]
|
||||
.iter()
|
||||
.map(|x| app.session.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap())
|
||||
.collect();
|
||||
app.session.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = app.session.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
for (x, hex) in [(25, "#ff0000"), (75, "#ff0000"), (125, "#0000ff")] {
|
||||
app.session.execute("livePaint.fill", &json!({"group": g, "point": [x, 125], "color": hex})).unwrap();
|
||||
}
|
||||
app.session.execute("select.none", &json!({})).unwrap();
|
||||
app.select_tool("livePaintBucket");
|
||||
app.session.paint.fill = green.clone();
|
||||
if let Some(v) = app.view_mut() {
|
||||
v.center = Point::new(200.0, 150.0);
|
||||
v.zoom = 1.0;
|
||||
v.fitted = true;
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let at = xf.to_screen(Point::new(25.0, 125.0));
|
||||
let click = |app: &mut VectorcraftApp, button, pos, modifiers| {
|
||||
let b = |pressed| Event::PointerButton { pos, button, pressed, modifiers };
|
||||
frame(app, &ctx, vec![Event::PointerMoved(pos), b(true)]);
|
||||
frame(app, &ctx, vec![b(false)]);
|
||||
};
|
||||
click(&mut app, PointerButton::Primary, at, Modifiers::NONE);
|
||||
if case == "middle" {
|
||||
click(&mut app, PointerButton::Middle, at, Modifiers::NONE);
|
||||
} else {
|
||||
let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE };
|
||||
frame(&mut app, &ctx, vec![space(true)]);
|
||||
click(&mut app, PointerButton::Primary, at, Modifiers::NONE);
|
||||
frame(&mut app, &ctx, vec![space(false)]);
|
||||
}
|
||||
click(&mut app, PointerButton::Primary, at, Modifiers::NONE);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let group = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(g)).unwrap().clone();
|
||||
let fill = |x: f64| vectorcraft_tools::builder::face_at(&group, Point::new(x, 125.0)).unwrap().appearance.fill_paint();
|
||||
assert_eq!([fill(25.0), fill(75.0)], [green.clone(), green.clone()], "{case}: the faces that were red");
|
||||
assert_eq!(fill(125.0), Paint::solid(Color::from_hex("#0000ff").unwrap()), "{case}: the blue face");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Image Trace panel's eye-button hold ends when the pointer is released, even when the
|
||||
/// panel stopped drawing while the button was held, so a later press on the canvas does not
|
||||
/// show the source image.
|
||||
|
||||
@@ -592,6 +592,7 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool {
|
||||
/// Options setting set this way for several rows is sent to every row (Template also sets Lock
|
||||
/// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as
|
||||
/// one picked from its menu does, and the preset it shows follows the DXF options set this way.
|
||||
/// A Graph Data Column Width set this way sets every column, as Cell Style's does.
|
||||
pub fn set_field(d: &mut Dialog, field: String, value: Value) {
|
||||
if d.kind == brush_options::KIND {
|
||||
brush_art_options::note_set(d, &field);
|
||||
@@ -605,11 +606,18 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) {
|
||||
if d.kind == "preferences" {
|
||||
crate::prefs_dialog::note_set(d, &field, &value);
|
||||
}
|
||||
if d.kind == new_document::KIND || new_document::popup_open(d) {
|
||||
new_document::note_set(d, &field);
|
||||
}
|
||||
let dxf = (d.kind == dxf_options::KIND).then(|| field.clone());
|
||||
let graph = (d.kind == graph_data::KIND).then(|| field.clone());
|
||||
d.fields.insert(field, value);
|
||||
if let Some(field) = dxf {
|
||||
dxf_options::note_set(d, &field);
|
||||
}
|
||||
if let Some(field) = graph {
|
||||
graph_data::note_set(d, &field);
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
//! Fields: what `file.info` reports (and takes back) plus `__keyword`, the keyword being typed
|
||||
//! (Enter or Add turns it into chips; OK keeps it too). OK runs `file.info` with them: one undo
|
||||
//! step. On an error the dialog stays open.
|
||||
//!
|
||||
//! The ≡ menu at the top saves the fields as a metadata template (`file.info.saveTemplate`), imports
|
||||
//! one (`file.info.applyTemplate`, after a choice of how to merge it into the fields), lists the
|
||||
//! templates of the metadata templates folder and shows that folder.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::CopyrightStatus;
|
||||
@@ -11,18 +15,38 @@ use vectorcraft_doc::metadata::MAX_RATING;
|
||||
|
||||
use super::document_setup::{LABEL, choice};
|
||||
use super::{DialogSpec, form};
|
||||
use crate::picks::PickRequest;
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, icons, widgets};
|
||||
use crate::{FilePick, VectorcraftApp, icons, widgets};
|
||||
|
||||
pub(super) const KIND: &str = "fileInfo";
|
||||
/// The keyword being typed.
|
||||
const PENDING: &str = "__keyword";
|
||||
/// The template waiting for a merge choice: `{path}` or `{name}`.
|
||||
const IMPORT: &str = "__import";
|
||||
/// The merge choice for [`IMPORT`]: `file.info.applyTemplate`'s `mode`.
|
||||
const IMPORT_MODE: &str = "__importMode";
|
||||
/// The templates in the metadata templates folder, listed when the menu opens: `[label, file]`
|
||||
/// pairs, the label being the name, or the file name where two templates share a name.
|
||||
const TEMPLATES: &str = "__templates";
|
||||
/// The merge choices, as `file.info.applyTemplate` names them.
|
||||
const MODES: [&str; 3] = ["replace", "keep", "append"];
|
||||
/// The extension of a metadata template file.
|
||||
const XMP_EXT: &str = "xmp";
|
||||
/// Width of the text fields.
|
||||
const FIELD: f32 = 320.0;
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("File Info").into(), body, confirm, min_width: 500.0, max_width: Some(500.0), ..DialogSpec::FORM };
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("File Info").into(),
|
||||
body,
|
||||
confirm,
|
||||
// OK and Enter wait while a template being imported waits for its merge choice.
|
||||
ok_enabled: Some(|_, d| !d.fields.get(IMPORT).is_some_and(Value::is_object)),
|
||||
min_width: 500.0,
|
||||
max_width: Some(500.0),
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
|
||||
/// Open File Info on the active document's.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
@@ -60,8 +84,193 @@ fn add_keywords(d: &mut Dialog) {
|
||||
d.fields.insert(PENDING.into(), json!(""));
|
||||
}
|
||||
|
||||
fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
/// What the templates menu asked for, done once the menu is drawn.
|
||||
enum Act {
|
||||
Save,
|
||||
Import,
|
||||
Template(String),
|
||||
Folder,
|
||||
}
|
||||
|
||||
/// A file dialog for metadata templates.
|
||||
fn xmp_pick() -> FilePick {
|
||||
FilePick { filters: vec![FilePick::filter("XMP metadata templates", &[XMP_EXT])], ..Default::default() }
|
||||
}
|
||||
|
||||
/// Whether the session has a metadata templates folder for Templates Folder to show (the web build
|
||||
/// has none).
|
||||
fn has_templates_folder(app: &VectorcraftApp) -> bool {
|
||||
app.session.metadata_templates_dir().is_some()
|
||||
}
|
||||
|
||||
/// The ≡ templates menu at the top right, and the merge choice for a template it picked.
|
||||
fn templates_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let can_save = crate::picks::can(app, &PickRequest::Save(xmp_pick()));
|
||||
let can_open = crate::picks::can(app, &PickRequest::Open(xmp_pick()));
|
||||
let has_folder = has_templates_folder(app);
|
||||
let mut act = None;
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover());
|
||||
let resp = ui.interact(rect, ui.scope_id().with("file-info-templates"), egui::Sense::click());
|
||||
icons::paint(ui, "menu", rect.shrink(1.0), if resp.hovered() { t.text_strong } else { t.text_dim });
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Templates")));
|
||||
let resp = resp.on_hover_text(tl!("Templates"));
|
||||
if resp.clicked() {
|
||||
// Listed once as the menu opens, not on every frame it shows.
|
||||
let listed = app.session.execute("file.info.templates", &json!({})).map(|r| r["templates"].clone()).unwrap_or_default();
|
||||
let listed: Vec<(&str, &str)> =
|
||||
listed.as_array().into_iter().flatten().filter_map(|t| Some((t.get("name")?.as_str()?, t.get("file")?.as_str()?))).collect();
|
||||
let entries: Vec<Value> = listed
|
||||
.iter()
|
||||
.map(|&(name, file)| {
|
||||
let shared = listed.iter().filter(|(n, _)| *n == name).count() > 1;
|
||||
json!([if shared { file } else { name }, file])
|
||||
})
|
||||
.collect();
|
||||
d.fields.insert(TEMPLATES.into(), json!(entries));
|
||||
}
|
||||
egui::Popup::menu(&resp).show(|ui| {
|
||||
ui.set_min_width(220.0);
|
||||
if can_save && widgets::menu_item(ui, tl!("Save Metadata Template…"), true, false) {
|
||||
act = Some(Act::Save);
|
||||
}
|
||||
if can_open && widgets::menu_item(ui, tl!("Import…"), true, false) {
|
||||
act = Some(Act::Import);
|
||||
}
|
||||
let entries: Vec<(String, String)> = d
|
||||
.fields
|
||||
.get(TEMPLATES)
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string())))
|
||||
.collect();
|
||||
if !entries.is_empty() {
|
||||
ui.separator();
|
||||
widgets::menu_scroll(ui, |ui| {
|
||||
for (label, file) in entries {
|
||||
if widgets::menu_item_name(ui, &label, true, false) {
|
||||
act = Some(Act::Template(file));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if has_folder {
|
||||
ui.separator();
|
||||
if widgets::menu_item(ui, tl!("Templates Folder"), true, false) {
|
||||
act = Some(Act::Folder);
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
});
|
||||
let r = match act {
|
||||
None => Ok(()),
|
||||
// The file dialogs, shown off the UI thread, act on the dialog as it is then.
|
||||
Some(Act::Save) => crate::picks::in_dialog(app, d, save_template),
|
||||
Some(Act::Import) => crate::picks::in_dialog(app, d, pick_template),
|
||||
// `file.info.applyTemplate` takes a listed template's file name as its `name`.
|
||||
Some(Act::Template(file)) => {
|
||||
d.fields.insert(IMPORT.into(), json!({ "name": file }));
|
||||
Ok(())
|
||||
}
|
||||
Some(Act::Folder) => show_folder(app),
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
import_options(app, ui, d);
|
||||
}
|
||||
|
||||
/// Save Metadata Template…: the fields as they are in the dialog, to a file picked in a save
|
||||
/// dialog that starts in the metadata templates folder. A name typed without `.xmp` takes it, so
|
||||
/// the templates list shows the file; a file already there under that name is replaced only after
|
||||
/// a question.
|
||||
fn save_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
let mut d2 = d.clone();
|
||||
add_keywords(&mut d2);
|
||||
let folder = app.session.execute("file.info.templates", &json!({ "create": true })).ok().and_then(|r| r["folder"].as_str().map(str::to_string));
|
||||
let name = format!("{}.{XMP_EXT}", d2.str("title").trim());
|
||||
let pick = FilePick { name, folder, ..xmp_pick() };
|
||||
// None: canceled, or the dialog is still open off the UI thread and runs this again.
|
||||
let Some(picked) = crate::picks::save(app, &pick) else { return Ok(()) };
|
||||
let path = if picked.to_ascii_lowercase().ends_with(&format!(".{XMP_EXT}")) { picked.clone() } else { format!("{picked}.{XMP_EXT}") };
|
||||
// The save dialog did not ask about the completed name: ask here, and the answer runs this again.
|
||||
if path != picked && crate::picks::ask_to_replace(app, PickRequest::Save(pick), &picked, None, &path) {
|
||||
return Ok(());
|
||||
}
|
||||
app.run("file.info.saveTemplate", json!({ "path": path, "fields": form::params(&d2) })).map(|_| ())
|
||||
}
|
||||
|
||||
/// Import…: a template picked in an open dialog waits for its merge choice.
|
||||
fn pick_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
// None: canceled, or the dialog is still open off the UI thread and runs this again.
|
||||
let Some(path) = crate::picks::open(app, &xmp_pick()) else { return Ok(()) };
|
||||
d.fields.insert(IMPORT.into(), json!({ "path": path }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Templates Folder: the metadata templates folder (made when it is missing) in the file manager.
|
||||
fn show_folder(app: &mut VectorcraftApp) -> Result<(), String> {
|
||||
let r = app.session.execute("file.info.templates", &json!({ "create": true })).map_err(|e| e.to_string())?;
|
||||
let folder = r["folder"].as_str().ok_or("no metadata templates folder here")?.to_string();
|
||||
crate::io::open_in_app(app, &folder)
|
||||
}
|
||||
|
||||
/// The merge choice for the template [`IMPORT`] names: OK merges it into the dialog's fields
|
||||
/// (nothing changes in the document until the dialog's own OK), Cancel drops it.
|
||||
fn import_options(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let Some(source) = d.fields.get(IMPORT).and_then(Value::as_object).cloned() else { return };
|
||||
widgets::subheader(ui, tl!("Import Options"));
|
||||
let mode = d.fields.get(IMPORT_MODE).and_then(Value::as_str).filter(|m| MODES.contains(m)).unwrap_or("keep").to_string();
|
||||
let labels = [
|
||||
tl!("Clear existing fields and use the template's"),
|
||||
tl!("Keep existing fields, but replace those the template has"),
|
||||
tl!("Keep existing fields, but append those the template has"),
|
||||
];
|
||||
for (value, label) in MODES.into_iter().zip(labels) {
|
||||
if widgets::radio(ui, label, mode == value, true) {
|
||||
d.fields.insert(IMPORT_MODE.into(), json!(value));
|
||||
}
|
||||
}
|
||||
let mut ok = false;
|
||||
let mut cancel = false;
|
||||
ui.horizontal(|ui| {
|
||||
ok = widgets::flat_button(ui, tl!("OK"), 64.0).clicked();
|
||||
cancel = widgets::flat_button(ui, tl!("Cancel"), 64.0).clicked();
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
if ok {
|
||||
if let Err(e) = import(app, d, source, &mode) {
|
||||
app.status(e);
|
||||
}
|
||||
} else if cancel {
|
||||
d.fields.remove(IMPORT);
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge the template `source` names into the dialog's fields as `mode` says.
|
||||
fn import(app: &mut VectorcraftApp, d: &mut Dialog, source: serde_json::Map<String, Value>, mode: &str) -> Result<(), String> {
|
||||
let mut p = Value::Object(source);
|
||||
p["mode"] = json!(mode);
|
||||
p["apply"] = json!(false);
|
||||
let mut d2 = d.clone();
|
||||
add_keywords(&mut d2);
|
||||
p["base"] = form::params(&d2);
|
||||
let merged = app.session.execute("file.info.applyTemplate", &p).map_err(|e| e.to_string())?;
|
||||
for (k, v) in merged.as_object().into_iter().flatten() {
|
||||
d.fields.insert(k.clone(), v.clone());
|
||||
}
|
||||
d.fields.insert(PENDING.into(), json!(""));
|
||||
d.fields.remove(IMPORT);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
templates_menu(app, ui, d);
|
||||
for (key, label) in [("title", tl!("Document Title:")), ("author", tl!("Author:")), ("authorTitle", tl!("Author Title:"))] {
|
||||
widgets::label_row(ui, label, LABEL, |ui| {
|
||||
form::text(ui, d, key, FIELD);
|
||||
@@ -233,4 +442,86 @@ mod tests {
|
||||
assert!(crate::dialogs::confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template");
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.attach_metadata_templates_dir(dir.join("Metadata Templates"));
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("file.info.saveTemplate", json!({"name": "Studio", "fields": {"author": "Grace", "keywords": ["print"], "rating": 3}})).unwrap();
|
||||
app.run("ui.fileInfoDialog", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("author".into(), json!("Ada"));
|
||||
d.fields.insert(super::PENDING.into(), json!("fair"));
|
||||
// A listed template waits for its merge choice; the choice draws.
|
||||
d.fields.insert(super::IMPORT.into(), json!({"name": "Studio"}));
|
||||
d.fields.insert(super::IMPORT_MODE.into(), json!("append"));
|
||||
frame(&mut app);
|
||||
let mut d = app.ui.dialog.clone().unwrap();
|
||||
super::import(&mut app, &mut d, json!({"name": "Studio"}).as_object().unwrap().clone(), "append").unwrap();
|
||||
assert!(!d.fields.contains_key(super::IMPORT));
|
||||
// Appended: the typed author stays, the typed keyword is kept and the template's added.
|
||||
assert_eq!(
|
||||
(d.fields["author"].clone(), d.fields["keywords"].clone(), d.fields["rating"].clone()),
|
||||
(json!("Ada"), json!(["fair", "print"]), json!(3))
|
||||
);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "nothing changes before OK");
|
||||
app.ui.dialog = Some(d);
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!((st.doc.metadata.author.as_str(), st.doc.metadata.rating), ("Ada", 3));
|
||||
assert_eq!(st.history.undo.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn templates_folder_is_offered_only_where_there_is_one() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("ui-file-info-folder");
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
assert!(!super::has_templates_folder(&app), "a session without a folder, as on the web, offers no Templates Folder");
|
||||
app.session.attach_metadata_templates_dir(dir.join("Metadata Templates"));
|
||||
assert!(super::has_templates_folder(&app));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ok_waits_for_the_merge_choice_of_a_template_being_imported() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("ui.fileInfoDialog", json!({})).unwrap();
|
||||
let mut d = app.ui.dialog.clone().unwrap();
|
||||
let ok = |app: &VectorcraftApp, d: &crate::state::Dialog| super::SPEC.ok_enabled.is_none_or(|f| f(app, d));
|
||||
assert!(ok(&app, &d));
|
||||
d.fields.insert(super::IMPORT.into(), json!({"name": "Studio"}));
|
||||
assert!(!ok(&app, &d), "OK and Enter wait while the merge choice is shown");
|
||||
d.fields.remove(super::IMPORT);
|
||||
assert!(ok(&app, &d));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_saved_without_an_extension_gets_xmp_and_is_listed() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("ui-file-info-save-ext");
|
||||
let folder = dir.join("Metadata Templates");
|
||||
let typed = folder.join("Studio").to_string_lossy().into_owned();
|
||||
let services = crate::Services {
|
||||
write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),
|
||||
exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
pick_save: Some(Box::new(move |_: &crate::FilePick| Some(typed.clone()))),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = VectorcraftApp::new(Session::new(), services);
|
||||
app.session.attach_metadata_templates_dir(folder.clone());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("ui.fileInfoDialog", json!({})).unwrap();
|
||||
let mut d = app.ui.dialog.clone().unwrap();
|
||||
d.fields.insert("author".into(), json!("Ada"));
|
||||
crate::picks::in_dialog(&mut app, &mut d, super::save_template).unwrap();
|
||||
assert!(folder.join("Studio.xmp").is_file() && !folder.join("Studio").exists(), "the typed name takes .xmp");
|
||||
let listed = app.session.execute("file.info.templates", &json!({})).unwrap();
|
||||
assert!(listed.to_string().contains("Studio"), "{listed}");
|
||||
// A file already there under the completed name is not replaced without asking.
|
||||
std::fs::write(folder.join("Studio.xmp"), b"kept").unwrap();
|
||||
crate::picks::in_dialog(&mut app, &mut d, super::save_template).unwrap();
|
||||
assert_eq!(std::fs::read(folder.join("Studio.xmp")).unwrap(), b"kept");
|
||||
assert_eq!(d.kind, crate::dialogs::confirm::REPLACE, "the dialog asks before replacing it");
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,15 @@
|
||||
//! don't move the caret in the entry box). Pasting tab- or line-separated text fills the cells from
|
||||
//! the picked one. Import Data reads a tab-separated text file, Transpose row/column swaps rows and
|
||||
//! columns, Switch x/y swaps a scatter graph's y and x columns, Cell Style sets the number of
|
||||
//! decimals the sheet shows and its columns' width, and Revert reads the graph's data again. Apply
|
||||
//! (`graph.setData` with its series, categories and rows) redraws the graph and leaves the window
|
||||
//! open.
|
||||
//! decimals the sheet shows and the width of every column, dragging a column's right edge sets that
|
||||
//! column's width (in whole digits, 0 to 20, as Cell Style), and Revert reads the graph's data
|
||||
//! again. Apply (`graph.setData` with its series, categories and rows) redraws the graph and leaves
|
||||
//! the window open.
|
||||
//!
|
||||
//! Fields: `grid` (rows of cell texts), `sel` ([row, column]), `entry` (the picked cell's text
|
||||
//! being edited), `decimals` (null: as typed), `width` (digits), `__graph` (the graph's id) and
|
||||
//! `__scatter`.
|
||||
//! being edited), `decimals` (null: as typed), `width` (digits), `widths` (a column's own width in
|
||||
//! digits by its index, null or missing: `width`; setting `width` empties it), `__graph` (the graph's
|
||||
//! id) and `__scatter`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES};
|
||||
@@ -62,7 +64,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let entry = cell(&grid, 0, 1);
|
||||
app.ui.dialog = Some(Dialog::new(
|
||||
KIND,
|
||||
json!({ "grid": grid, "sel": [0, 1], "entry": entry, "decimals": null, "width": 7, "__graph": id, "__scatter": scatter }),
|
||||
json!({ "grid": grid, "sel": [0, 1], "entry": entry, "decimals": null, "width": 7, "widths": [], "__graph": id, "__scatter": scatter }),
|
||||
));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -355,7 +357,7 @@ fn import(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// Draw the graph-data sheet: keyboard cell movement, block paste, import, transpose, switch-x/y
|
||||
/// and revert actions, decimals and column width, and only the cells in view.
|
||||
/// and revert actions, decimals and column widths, and only the cells in view.
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let entry_id = egui::Id::unique("graph-data-entry");
|
||||
if ui.memory(|m| m.has_focus(entry_id)) {
|
||||
@@ -435,37 +437,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.add_space(12.0);
|
||||
widgets::dim_label(ui, tl!("Column Width:"));
|
||||
let mut w = d.fields.get("width").and_then(Value::as_u64).unwrap_or(7);
|
||||
if ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)).changed() {
|
||||
d.fields.insert("width".into(), json!(w));
|
||||
let r = ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH));
|
||||
// A value entered with Enter sets every column, also when it is the width shown. Leaving the
|
||||
// field without a new value keeps the columns' own widths.
|
||||
if r.changed() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) {
|
||||
set_width(d, w);
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
let at = sel(d);
|
||||
let (rows, cols) = extent(d, at);
|
||||
let decimals = d.fields.get("decimals").and_then(Value::as_u64);
|
||||
let w = (d.fields.get("width").and_then(Value::as_u64).unwrap_or(7).min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0);
|
||||
let mut clicked = None;
|
||||
widgets::list_box(ui, |ui| {
|
||||
// Only the cells in view are drawn: a graph's sheet can be 10,001 × 257.
|
||||
egui::ScrollArea::both().id_salt("graph-data-sheet").max_height(280.0).auto_shrink([false, false]).show_viewport(ui, |ui, view| {
|
||||
let (cw, ch) = (w + 1.0, ROW_H);
|
||||
ui.set_min_size(egui::vec2(cols as f32 * cw, rows as f32 * ch));
|
||||
let origin = ui.max_rect().min;
|
||||
let span = |lo: f32, hi: f32, size: f32, n: usize| ((lo / size).floor().max(0.0) as usize, ((hi / size).ceil().max(0.0) as usize).min(n));
|
||||
let (r0, r1) = span(view.min.y, view.max.y, ch, rows);
|
||||
let (c0, c1) = span(view.min.x, view.max.x, cw, cols);
|
||||
for r in r0..r1 {
|
||||
for c in c0..c1 {
|
||||
let rect = egui::Rect::from_min_size(origin + egui::vec2(c as f32 * cw, r as f32 * ch), egui::vec2(w, ch - 1.0));
|
||||
let text = shown(cell_at(d, r, c), decimals);
|
||||
let b = egui::Button::selectable((r, c) == at, egui::RichText::new(text).monospace()).truncate();
|
||||
if ui.put(rect, b).clicked() && (r, c) != (0, 0) {
|
||||
clicked = Some((r, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let (clicked, resized) = sheet(ui, d);
|
||||
if let Some((c, n)) = resized
|
||||
&& n != col_digits(d, c)
|
||||
{
|
||||
set_col_digits(d, c, n);
|
||||
}
|
||||
if let Some(to) = clicked {
|
||||
pick(d, to);
|
||||
ui.memory_mut(|mem| mem.request_focus(entry_id));
|
||||
@@ -479,6 +464,143 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Cell Style's Column Width in digits.
|
||||
fn width(d: &Dialog) -> u64 {
|
||||
d.fields.get("width").and_then(Value::as_u64).unwrap_or(7).min(MAX_WIDTH)
|
||||
}
|
||||
|
||||
/// A column's width in digits: its own when its edge was dragged, else Cell Style's.
|
||||
fn col_digits(d: &Dialog, c: usize) -> u64 {
|
||||
d.fields.get("widths").and_then(|w| w.get(c)).and_then(Value::as_u64).unwrap_or_else(|| width(d)).min(MAX_WIDTH)
|
||||
}
|
||||
|
||||
/// Cell Style's Column Width: every column `n` digits wide, the ones given their own width too.
|
||||
fn set_width(d: &mut Dialog, n: u64) {
|
||||
d.fields.insert("width".into(), json!(n.min(MAX_WIDTH)));
|
||||
note_set(d, "width");
|
||||
}
|
||||
|
||||
/// `ui.dialog.set` set `field`: a Column Width sets every column, as Cell Style's does.
|
||||
pub(super) fn note_set(d: &mut Dialog, field: &str) {
|
||||
if field == "width" {
|
||||
d.fields.insert("widths".into(), json!([]));
|
||||
}
|
||||
}
|
||||
|
||||
/// Set column `c`'s own width in digits (at most MAX_WIDTH).
|
||||
fn set_col_digits(d: &mut Dialog, c: usize, n: u64) {
|
||||
if c >= MAX_COLS {
|
||||
return;
|
||||
}
|
||||
let widths = d.fields.entry("widths").or_insert_with(|| json!([]));
|
||||
if !widths.is_array() {
|
||||
*widths = json!([]);
|
||||
}
|
||||
let Some(widths) = widths.as_array_mut() else { return };
|
||||
if widths.len() <= c {
|
||||
widths.resize(c + 1, Value::Null);
|
||||
}
|
||||
if let Some(w) = widths.get_mut(c) {
|
||||
*w = json!(n.min(MAX_WIDTH));
|
||||
}
|
||||
}
|
||||
|
||||
/// A column `n` digits wide, in points on the sheet.
|
||||
fn digits_px(n: u64) -> f32 {
|
||||
(n.min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0)
|
||||
}
|
||||
|
||||
/// The width in digits nearest to `px` points, within Cell Style's 0 to MAX_WIDTH.
|
||||
fn px_digits(px: f32) -> u64 {
|
||||
if px.is_finite() { ((px - 10.0) / 7.0).round().clamp(0.0, MAX_WIDTH as f32) as u64 } else { 0 }
|
||||
}
|
||||
|
||||
/// The id of column `c`'s right edge on the sheet.
|
||||
fn edge_id(c: usize) -> egui::Id {
|
||||
egui::Id::unique(("graph-data-column-edge", c))
|
||||
}
|
||||
|
||||
/// The cell clicked on the sheet ([row, column]), and the column whose edge is dragged with its width
|
||||
/// in digits.
|
||||
type SheetInput = (Option<(usize, usize)>, Option<(usize, u64)>);
|
||||
|
||||
/// Draw the sheet's cells in view, each column at its own width. Returns the cell clicked, and the
|
||||
/// column whose right edge is being dragged with the width in digits the pointer gives it.
|
||||
fn sheet(ui: &mut egui::Ui, d: &Dialog) -> SheetInput {
|
||||
let at = sel(d);
|
||||
let (rows, cols) = extent(d, at);
|
||||
let decimals = d.fields.get("decimals").and_then(Value::as_u64);
|
||||
// Each column's left edge, and the sheet's width last: a column is its width and a 1-point gap.
|
||||
let mut xs = Vec::with_capacity(cols + 1);
|
||||
let mut x = 0.0;
|
||||
xs.push(x);
|
||||
for c in 0..cols {
|
||||
x += digits_px(col_digits(d, c)) + 1.0;
|
||||
xs.push(x);
|
||||
}
|
||||
let left = |c: usize| xs.get(c).copied().unwrap_or(x);
|
||||
let (mut clicked, mut resized) = (None, None);
|
||||
widgets::list_box(ui, |ui| {
|
||||
// Only the cells in view are drawn: a graph's sheet can be 10,001 × 257.
|
||||
egui::ScrollArea::both().id_salt("graph-data-sheet").max_height(280.0).auto_shrink([false, false]).show_viewport(ui, |ui, view| {
|
||||
let ch = ROW_H;
|
||||
ui.set_min_size(egui::vec2(x, rows as f32 * ch));
|
||||
let origin = ui.max_rect().min;
|
||||
let (r0, r1) = ((view.min.y / ch).floor().max(0.0) as usize, ((view.max.y / ch).ceil().max(0.0) as usize).min(rows));
|
||||
// The columns that reach into the view.
|
||||
let c0 = (0..cols).find(|&c| left(c + 1) > view.min.x).unwrap_or(cols);
|
||||
let c1 = (c0..cols).find(|&c| left(c) >= view.max.x).unwrap_or(cols);
|
||||
for r in r0..r1 {
|
||||
for c in c0..c1 {
|
||||
let size = egui::vec2(left(c + 1) - left(c) - 1.0, ch - 1.0);
|
||||
let rect = egui::Rect::from_min_size(origin + egui::vec2(left(c), r as f32 * ch), size);
|
||||
let text = shown(cell_at(d, r, c), decimals);
|
||||
let b = egui::Button::selectable((r, c) == at, egui::RichText::new(text).monospace()).truncate();
|
||||
if ui.put(rect, b).clicked() && (r, c) != (0, 0) {
|
||||
clicked = Some((r, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A column's right edge, over the rows in view: dragging it sets that column's width. The
|
||||
// edge being dragged stays in the loop when it leaves the view, so the drag goes on, also in
|
||||
// the frame it is released.
|
||||
let (top, bottom) = (origin.y + r0 as f32 * ch, origin.y + r1 as f32 * ch);
|
||||
let dragged = ui
|
||||
.ctx()
|
||||
.dragged_id()
|
||||
.or_else(|| ui.ctx().drag_stopped_id())
|
||||
.and_then(|id| (0..cols).find(|&c| edge_id(c) == id))
|
||||
.filter(|c| !(c0..c1).contains(c));
|
||||
for c in (c0..c1).chain(dragged) {
|
||||
let gap = origin.x + left(c + 1) - 0.5;
|
||||
let edge = egui::Rect::from_x_y_ranges(gap - 3.0..=gap + 3.0, top..=bottom);
|
||||
let h = ui.interact(edge, edge_id(c), egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeColumn);
|
||||
// The width is the column's width when the drag started plus how far the pointer has
|
||||
// moved since, so a scroll offset that changes with the sheet's width doesn't change it.
|
||||
if h.drag_started()
|
||||
&& let Some(p) = ui.input(|i| i.pointer.press_origin()).or_else(|| h.interact_pointer_pos())
|
||||
{
|
||||
ui.data_mut(|m| m.insert_temp(edge_id(c), (p.x, left(c + 1) - left(c) - 1.0)));
|
||||
}
|
||||
if h.dragged() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeColumn);
|
||||
}
|
||||
// The release can come in the same frame as the last move: it sets the width too.
|
||||
if (h.dragged() || h.drag_stopped())
|
||||
&& let Some(p) = h.interact_pointer_pos()
|
||||
&& let Some((x0, w0)) = ui.data(|m| m.get_temp::<(f32, f32)>(edge_id(c)))
|
||||
{
|
||||
resized = Some((c, px_digits(w0 + p.x - x0)));
|
||||
}
|
||||
if h.drag_stopped() {
|
||||
ui.data_mut(|m| m.remove::<(f32, f32)>(edge_id(c)));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
(clicked, resized)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
@@ -685,6 +807,171 @@ mod tests {
|
||||
assert_eq!(sel(app.ui.dialog.as_ref().unwrap()), (0, 1), "Up");
|
||||
}
|
||||
|
||||
/// Dragging a column's right edge shows the column-resize pointer and sets that column's width in
|
||||
/// whole digits, the columns after it moving along; the other columns keep Cell Style's width.
|
||||
/// A drag past 20 digits stops at 20, and Cell Style's Column Width then sets every column.
|
||||
#[test]
|
||||
fn dragging_a_column_edge_sets_that_columns_width() {
|
||||
let (mut app, _) = app_with(",a,b\nQ1,1,2", "column");
|
||||
open(&mut app).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
out.platform_output.cursor_icon
|
||||
};
|
||||
let button =
|
||||
|pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
let edge = |c: usize| ctx.read_response(edge_id(c)).map(|r| r.rect).unwrap_or_else(|| panic!("column {c}'s edge is drawn"));
|
||||
let drag = |app: &mut VectorcraftApp, c: usize, dx: f32| {
|
||||
let at = edge(c).center();
|
||||
frame(app, vec![egui::Event::PointerMoved(at), button(at, true)]);
|
||||
for step in 1..=4 {
|
||||
frame(app, vec![egui::Event::PointerMoved(at + egui::vec2(dx * step as f32 / 4.0, 0.0))]);
|
||||
}
|
||||
frame(app, vec![button(at + egui::vec2(dx, 0.0), false)]);
|
||||
frame(app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]);
|
||||
};
|
||||
let digits = |app: &VectorcraftApp| {
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
(0..4).map(|c| col_digits(d, c)).collect::<Vec<_>>()
|
||||
};
|
||||
frame(&mut app, vec![]);
|
||||
frame(&mut app, vec![]);
|
||||
// The window takes its place over the first frames: hover where the edge is now.
|
||||
let hovered = (0..10).any(|_| frame(&mut app, vec![egui::Event::PointerMoved(edge(1).center())]) == egui::CursorIcon::ResizeColumn);
|
||||
assert!(hovered, "hovering an edge shows the column-resize pointer");
|
||||
let (one, two) = (edge(1).center().x, edge(2).center().x);
|
||||
// 70 points is 10 digits.
|
||||
drag(&mut app, 1, 70.0);
|
||||
assert_eq!(digits(&app), [7, 17, 7, 7]);
|
||||
let moved = [edge(1).center().x - one, edge(2).center().x - two];
|
||||
assert!(moved.iter().all(|m| (m - 70.0).abs() < 0.01), "the columns after it move along: {moved:?}");
|
||||
drag(&mut app, 2, -500.0);
|
||||
assert_eq!(digits(&app), [7, 17, 0, 7], "no narrower than 0 digits");
|
||||
drag(&mut app, 0, 500.0);
|
||||
assert_eq!(digits(&app), [20, 17, 0, 7], "no wider than 20 digits");
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
set_width(d, 9);
|
||||
assert_eq!(digits(&app), [9; 4], "Cell Style sets every column");
|
||||
}
|
||||
|
||||
/// A drag whose last move comes in the frame it is released sets the width to where it was
|
||||
/// released. A held drag on a sheet scrolled to its right end keeps its width while the scroll
|
||||
/// offset follows the narrower sheet. Entering the width that Column Width shows sets every
|
||||
/// column, the dragged ones too.
|
||||
#[test]
|
||||
fn a_column_drag_ends_where_released_and_the_shown_width_entered_sets_every_column() {
|
||||
let rows: Vec<Vec<f64>> = (0..3).map(|i| vec![i as f64; 30]).collect();
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "rows": rows})).unwrap();
|
||||
open(&mut app).unwrap();
|
||||
let cols = extent(app.ui.dialog.as_ref().unwrap(), (0, 1)).1;
|
||||
let ctx = egui::Context::default();
|
||||
ctx.enable_accesskit();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0));
|
||||
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut out =
|
||||
ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default()
|
||||
};
|
||||
let button =
|
||||
|pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
let edge = |c: usize| ctx.read_response(edge_id(c)).map(|r| r.rect).unwrap_or_else(|| panic!("column {c}'s edge is drawn"));
|
||||
let digits = |app: &VectorcraftApp, c: usize| col_digits(app.ui.dialog.as_ref().unwrap(), c);
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
// The last move and the release in one frame: 70 points is 10 digits.
|
||||
let at = edge(1).center();
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]);
|
||||
let to = at + egui::vec2(70.0, 0.0);
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(to), button(to, false)]);
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]);
|
||||
assert_eq!(digits(&app, 1), 17, "the width where the drag was released");
|
||||
// Scroll the sheet to its right end, then narrow a column by 5 digits and hold the pointer still.
|
||||
let over = edge(1).center() - egui::vec2(20.0, 0.0);
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(-100_000.0, 0.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Default::default(),
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
};
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(over), wheel]);
|
||||
for _ in 0..30 {
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
let c = cols - 2;
|
||||
let at = edge(c).center();
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]);
|
||||
for step in 1..=5 {
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(at - egui::vec2(7.0 * step as f32, 0.0))]);
|
||||
}
|
||||
for _ in 0..10 {
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
assert_eq!(digits(&app, c), 2, "a held drag keeps its width");
|
||||
let to = at - egui::vec2(35.0, 0.0);
|
||||
frame(&mut app, vec![button(to, false)]);
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]);
|
||||
assert_eq!(digits(&app, c), 2, "the width where the drag was released");
|
||||
// Column Width still shows 7: entering 7 there sets every column to 7.
|
||||
let nodes = frame(&mut app, vec![]);
|
||||
let label = nodes
|
||||
.iter()
|
||||
.find(|(_, n)| n.role() == egui::accesskit::Role::Label && n.value() == Some("Column Width:"))
|
||||
.and_then(|(_, n)| n.bounds())
|
||||
.expect("the Column Width label is drawn");
|
||||
let field = nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.role() == egui::accesskit::Role::SpinButton)
|
||||
.filter_map(|(_, n)| n.bounds())
|
||||
.filter(|b| b.x0 >= label.x1 && b.y0 < label.y1 && b.y1 > label.y0)
|
||||
.min_by(|a, b| a.x0.total_cmp(&b.x0))
|
||||
.expect("the Column Width field is drawn");
|
||||
let at = egui::pos2(((field.x0 + field.x1) / 2.0) as f32, ((field.y0 + field.y1) / 2.0) as f32);
|
||||
let click = |app: &mut VectorcraftApp, at| {
|
||||
frame(app, vec![egui::Event::PointerMoved(at), button(at, true)]);
|
||||
frame(app, vec![button(at, false)]);
|
||||
frame(app, vec![]);
|
||||
};
|
||||
// Clicking into the field and away from it, without a new value, keeps the columns' widths.
|
||||
click(&mut app, at);
|
||||
click(&mut app, egui::pos2(((label.x0 + label.x1) / 2.0) as f32, ((label.y0 + label.y1) / 2.0) as f32));
|
||||
assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (17, 2, 7), "leaving the field keeps the widths");
|
||||
click(&mut app, at);
|
||||
frame(&mut app, vec![egui::Event::Text("7".into())]);
|
||||
let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
|
||||
frame(&mut app, vec![enter]);
|
||||
frame(&mut app, vec![]);
|
||||
assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (7, 7, 7), "Column Width sets every column");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_width_in_points_maps_to_whole_digits() {
|
||||
for n in 0..=MAX_WIDTH {
|
||||
assert_eq!(px_digits(digits_px(n)), n);
|
||||
}
|
||||
assert_eq!((px_digits(-40.0), px_digits(1e9), px_digits(f32::NAN)), (0, MAX_WIDTH, 0));
|
||||
let mut d = Dialog::new(KIND, json!({ "width": 7 }));
|
||||
set_col_digits(&mut d, 3, 99);
|
||||
set_col_digits(&mut d, MAX_COLS, 5);
|
||||
assert_eq!((col_digits(&d, 2), col_digits(&d, 3)), (7, MAX_WIDTH));
|
||||
assert_eq!(d.fields["widths"].as_array().map(Vec::len), Some(4), "a column past the sheet is left alone");
|
||||
// `width` set by `ui.dialog.set` sets every column too, also when set back to the width before.
|
||||
for w in [12, 7] {
|
||||
crate::dialogs::set_field(&mut d, "width".into(), json!(w));
|
||||
assert_eq!((col_digits(&d, 2), col_digits(&d, 3)), (w, w));
|
||||
}
|
||||
set_col_digits(&mut d, 1, 4);
|
||||
assert_eq!((col_digits(&d, 1), col_digits(&d, 3)), (4, 7), "a drag after it gives that column its own width");
|
||||
}
|
||||
|
||||
/// How many buttons (the sheet's cells and the window's own) Graph Data draws in the second of two
|
||||
/// frames in a 1280 × 900 window, for a graph of `categories` rows of `series` values.
|
||||
fn buttons_drawn(categories: usize, series: usize) -> usize {
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
//! `artboardLayout`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`,
|
||||
//! `previewMode`, `alignNewObjectsToPixelGrid`, `profile`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and
|
||||
//! `presetName` (Save Preset's name). Setting `preset` fills the fields from that preset; changing
|
||||
//! any of them afterwards makes the settings custom.
|
||||
//! any of them afterwards makes the settings custom. The dialog opens in Preferences › Units ›
|
||||
//! General, also on a Recent entry made in other units (one in pixels, or a saved preset in the
|
||||
//! units it was saved in, keeps its units); units chosen
|
||||
//! in the Units menu or set with `ui.dialog.set` stay when another tab or preset is chosen.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
@@ -57,6 +60,9 @@ const SAVING: &str = "__saving";
|
||||
/// Preset Details has drawn the saving top: set from the mode's second frame, so the first one fills
|
||||
/// in the default name and focuses it.
|
||||
const SAVING_SHOWN: &str = "__savingShown";
|
||||
/// The units were chosen in the Units menu (or set with `ui.dialog.set`): presets chosen after that
|
||||
/// keep the chosen units.
|
||||
const UNITS_CHOSEN: &str = "__unitsChosen";
|
||||
/// The units New Document offers (all ten).
|
||||
const UNITS: [Unit; 10] = [
|
||||
Unit::Pixels,
|
||||
@@ -82,17 +88,49 @@ const HEADER: f32 = 100.0;
|
||||
const MORE_WIDTH: f32 = 310.0;
|
||||
|
||||
/// Open New Document on the most recent settings (or Letter), named after the next untitled
|
||||
/// document.
|
||||
/// document, in Preferences › Units › General.
|
||||
pub fn open(app: &mut VectorcraftApp) {
|
||||
let category = if app.session.prefs.recent_new_docs.is_empty() { "Print" } else { "Recent" };
|
||||
let first = newdoc::category(&app.session, category).and_then(|v| v.into_iter().next()).unwrap_or_default();
|
||||
let mut d = Dialog::new(KIND, json!({ "category": category, "name": app.session.peek_untitled(), "advanced": false }));
|
||||
apply(&mut d, &first);
|
||||
if !apply_first(app, &mut d, category) {
|
||||
apply(&mut d, &DocSettings { units: app.session.default_units(), ..DocSettings::default() });
|
||||
}
|
||||
app.ui.dialog = Some(d);
|
||||
}
|
||||
|
||||
/// Fill the fields from a preset.
|
||||
/// Fill the fields from the first preset of `category`, as opening the dialog and choosing a tab
|
||||
/// do; false when the category has none. The most recent entry keeps its size and takes
|
||||
/// Preferences › Units › General, as the built-in presets do, unless it is in pixels or it is a
|
||||
/// saved preset in the units it was saved in. Its card stays the chosen one and shows those units;
|
||||
/// choosing another card brings back that card's own units.
|
||||
fn apply_first(app: &VectorcraftApp, d: &mut Dialog, category: &str) -> bool {
|
||||
let Some(first) = newdoc::category(&app.session, category).and_then(|v| v.into_iter().next()) else { return false };
|
||||
// `file.new` reads a named preset in its own units, and names the entry Custom in others.
|
||||
let as_saved = newdoc::find(&app.session, &first.name).is_some_and(|p| p.units == first.units);
|
||||
if !category.eq_ignore_ascii_case("Recent") || first.units == Unit::Pixels || as_saved {
|
||||
apply(d, &first);
|
||||
return true;
|
||||
}
|
||||
let own = first.units;
|
||||
apply(d, &DocSettings { units: app.session.default_units(), ..first });
|
||||
// The card is still the entry it was: its own units say which entry it is.
|
||||
if let Some(Value::Object(a)) = d.fields.get_mut(APPLIED) {
|
||||
a.insert("units".into(), json!(own.label()));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `field` of New Document `d` is about to be set by `ui.dialog.set`: setting the units is a choice
|
||||
/// that presets chosen after it keep.
|
||||
pub(super) fn note_set(d: &mut Dialog, field: &str) {
|
||||
if field == "units" {
|
||||
d.fields.insert(UNITS_CHOSEN.into(), json!(true));
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill the fields from a preset, keeping the units when they were chosen in the Units menu.
|
||||
fn apply(d: &mut Dialog, s: &DocSettings) {
|
||||
let chosen = if d.bool(UNITS_CHOSEN) { d.fields.get("units").cloned() } else { None };
|
||||
let Value::Object(mut v) = s.to_json() else { return };
|
||||
for k in ["size", "orientation"] {
|
||||
v.remove(k);
|
||||
@@ -105,6 +143,9 @@ fn apply(d: &mut Dialog, s: &DocSettings) {
|
||||
d.fields.insert(k.clone(), val.clone());
|
||||
}
|
||||
d.fields.insert(APPLIED.into(), Value::Object(v));
|
||||
if let Some(u) = chosen {
|
||||
d.fields.insert("units".into(), u);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the fields and the chosen preset in step: a new `preset` (also from `ui.dialog.set`) fills
|
||||
@@ -305,8 +346,8 @@ fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
if let Some(i) = widgets::tab_bar(ui, &names, cat) {
|
||||
d.fields.insert("category".into(), json!(names[i]));
|
||||
// A tab opens on its first preset, so the details match its cards.
|
||||
if let Some(first) = names.get(i).and_then(|c| newdoc::category(&app.session, c)).and_then(|v| v.into_iter().next()) {
|
||||
apply(d, &first);
|
||||
if let Some(c) = names.get(i) {
|
||||
apply_first(app, d, c);
|
||||
}
|
||||
}
|
||||
let list = names.get(cat).and_then(|c| newdoc::category(&app.session, c)).unwrap_or_default();
|
||||
@@ -705,6 +746,7 @@ fn units_dropdown(ui: &mut egui::Ui, d: &mut Dialog, width: f32) {
|
||||
let labels = UNITS.map(Unit::label);
|
||||
if let Some(u) = widgets::dropdown(ui, "newdoc-units", unit(d).label(), &labels, width).and_then(|i| UNITS.get(i)) {
|
||||
d.fields.insert("units".into(), json!(u.label()));
|
||||
d.fields.insert(UNITS_CHOSEN.into(), json!(true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1569,6 +1611,103 @@ mod tests {
|
||||
assert!(h.state().session.active().unwrap().doc.setup.align_new_objects_to_pixel_grid);
|
||||
}
|
||||
|
||||
/// Create, then the new document's units.
|
||||
fn create(h: &mut Harness) -> vectorcraft_doc::Unit {
|
||||
h.get_by_label("Create").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.status);
|
||||
h.state().session.active().unwrap().doc.units
|
||||
}
|
||||
|
||||
/// With Preferences › Units › General in millimeters, New Document opens on the most recent
|
||||
/// entry in millimeters even though that entry was made in points, and New Without Dialog makes
|
||||
/// the same document. An entry in pixels stays in pixels, as the screen presets do.
|
||||
#[test]
|
||||
fn the_dialog_opens_in_the_general_units_over_a_recent_entry() {
|
||||
use vectorcraft_doc::Unit::{Millimeters as Mm, Pixels as Px};
|
||||
let mut h = big();
|
||||
h.state_mut().run("file.new", json!({"units": "Points"})).unwrap();
|
||||
h.state_mut().run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters", "documentUnits": false})).unwrap();
|
||||
assert_eq!(h.state().session.prefs.recent_new_docs[0].units, vectorcraft_doc::Unit::Points);
|
||||
h.state_mut().run("file.newDialog", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!("Recent"), json!("Millimeters")));
|
||||
assert_eq!(create(&mut h), Mm, "the dialog's Create");
|
||||
h.state_mut().run("file.new", json!({"units": "Points"})).unwrap();
|
||||
h.state_mut().run("file.newWithoutDialog", json!({})).unwrap();
|
||||
assert_eq!(h.state().session.active().unwrap().doc.units, Mm, "New Without Dialog");
|
||||
h.state_mut().run("file.new", json!({"preset": "Web 1920×1080"})).unwrap();
|
||||
h.state_mut().run("file.newDialog", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!(field(h.state(), "units"), json!("Pixels"));
|
||||
assert_eq!(create(&mut h), Px);
|
||||
}
|
||||
|
||||
/// A Recent entry that is a saved preset in the units it was saved in opens in those units, so
|
||||
/// Create keeps the preset's name in Recent; the General unit is millimeters.
|
||||
#[test]
|
||||
fn a_recent_saved_preset_keeps_its_units_and_name() {
|
||||
let mut h = big();
|
||||
h.state_mut().run("file.newPresets.save", json!({"name": "Zine", "width": "5.5 in", "height": "8.5 in", "units": "Inches"})).unwrap();
|
||||
h.state_mut().run("file.new", json!({"preset": "Zine"})).unwrap();
|
||||
h.state_mut().run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters", "documentUnits": false})).unwrap();
|
||||
h.state_mut().run("file.newDialog", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert_eq!((field(h.state(), "preset"), field(h.state(), "units")), (json!("Zine"), json!("Inches")));
|
||||
assert_eq!(create(&mut h), vectorcraft_doc::Unit::Inches);
|
||||
let recent = &h.state().session.prefs.recent_new_docs;
|
||||
assert_eq!((recent.len(), recent[0].name.as_str()), (1, "Zine"), "{recent:?}");
|
||||
}
|
||||
|
||||
/// Units set with `ui.dialog.set` while More Settings or Manage Profiles is open stay chosen
|
||||
/// when a preset is chosen after them.
|
||||
#[test]
|
||||
fn units_set_over_a_popup_stay_chosen() {
|
||||
for popup in [super::MORE, super::PROFILES] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.newDialog", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.kind = popup.into();
|
||||
crate::dialogs::set_field(d, "units".into(), json!("Millimeters"));
|
||||
crate::dialogs::set_field(d, "preset".into(), json!("A4"));
|
||||
d.kind = super::KIND.into();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
assert_eq!((field(&app, "preset"), field(&app, "units")), (json!("A4"), json!("Millimeters")), "{popup}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Millimeters chosen in the Units menu stay chosen when another tab or preset is chosen after
|
||||
/// them, and reach the new document.
|
||||
#[test]
|
||||
fn units_chosen_in_the_menu_survive_tabs_and_presets() {
|
||||
use vectorcraft_doc::Unit::Millimeters as Mm;
|
||||
let mut h = big();
|
||||
assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!("Print"), json!("Points")));
|
||||
h.get_by_role_and_label(Role::ComboBox, "Units").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Millimeters").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(field(h.state(), "units"), json!("Millimeters"));
|
||||
// A Recent entry made in inches, which the Recent tab opens on.
|
||||
h.state_mut().run("file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})).unwrap();
|
||||
for tab in ["Web", "Recent", "Print"] {
|
||||
h.get_by_role_and_label(Role::Button, tab).click();
|
||||
h.run_steps(3);
|
||||
assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!(tab), json!("Millimeters")), "the {tab} tab");
|
||||
}
|
||||
// A preset chosen by name, as `ui.dialog.set` chooses it.
|
||||
crate::dialogs::set_field(h.state_mut().ui.dialog.as_mut().unwrap(), "preset".into(), json!("A4"));
|
||||
h.run_steps(3);
|
||||
assert_eq!(
|
||||
(field(h.state(), "width"), field(h.state(), "units")),
|
||||
(json!(vectorcraft_doc::Unit::Millimeters.to_pt(210.0)), json!("Millimeters"))
|
||||
);
|
||||
assert_eq!(create(&mut h), Mm);
|
||||
}
|
||||
|
||||
/// A long translation of Align New Objects to Pixel Grid wraps inside the Preset Details column.
|
||||
#[test]
|
||||
fn align_new_objects_label_wraps_inside_the_details_column() {
|
||||
|
||||
@@ -248,7 +248,7 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
|
||||
number(ui, d, "taper", tl!("Taper"), (1.0, 100.0), "%", 1, None);
|
||||
choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]);
|
||||
ui.add_space(10.0);
|
||||
heading(ui, c3("Bevel"));
|
||||
bevel_heading(ui, d);
|
||||
let shapes: Vec<(Value, &str)> =
|
||||
super::effect::own_choices(EXTRUDE, "bevel", false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect();
|
||||
choice(ui, d, "bevel", tl!("Bevel Shape"), &shapes);
|
||||
@@ -262,6 +262,53 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Extrude & Bevel's bevel settings (every parameter named `bevel…`) with their defaults.
|
||||
fn bevel_defaults() -> serde_json::Map<String, Value> {
|
||||
match vectorcraft_effects::default_params(EXTRUDE) {
|
||||
Some(Value::Object(m)) => m.into_iter().filter(|(k, _)| k.starts_with("bevel")).collect(),
|
||||
_ => serde_json::Map::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does any setting in `defaults` differ from its default in `d`? A setting the 3D and Materials
|
||||
/// panel's selected effects hold with different values (null) counts as changed.
|
||||
fn differs_from(d: &Dialog, defaults: &serde_json::Map<String, Value>) -> bool {
|
||||
defaults.iter().any(|(k, v)| match (d.fields.get(k), v.as_f64()) {
|
||||
(Some(Value::Null), _) => true,
|
||||
(_, Some(default)) => (d.f64(k, default) - default).abs() > 1e-6,
|
||||
(field, None) => field.is_some_and(|f| f != v),
|
||||
})
|
||||
}
|
||||
|
||||
/// The Bevel heading with its Reset button, which puts every bevel setting back to its default and
|
||||
/// leaves the other settings as they are. The button is off while every bevel setting is at its
|
||||
/// default.
|
||||
fn bevel_heading(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let defaults = bevel_defaults();
|
||||
let changed = differs_from(d, &defaults);
|
||||
let mut reset = false;
|
||||
ui.horizontal(|ui| {
|
||||
heading(ui, c3("Bevel"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.add_enabled_ui(changed, |ui| {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (r, _) = ui.allocate_exact_size(vec2(56.0, 20.0), Sense::hover());
|
||||
let response = ui.interact(r, Id::unique("revolve-reset-bevel"), Sense::click());
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Reset")));
|
||||
if response.hovered() {
|
||||
ui.painter().rect_filled(r, 3.0, t.hover);
|
||||
}
|
||||
let color = if ui.is_enabled() { t.text } else { t.text_disabled };
|
||||
ui.painter().text(r.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, tl!("Reset"), FontId::proportional(11.5), color);
|
||||
reset = response.clicked();
|
||||
});
|
||||
});
|
||||
});
|
||||
if reset {
|
||||
d.fields.extend(defaults);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotation presets, rotation and perspective for Extrude & Bevel, Inflate and Rotate, and the
|
||||
/// classic 3D effects, which have the track cube below the presets.
|
||||
fn view_controls(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
|
||||
@@ -578,6 +578,42 @@ fn extrude_bevel_options_enable_with_a_bevel_shape() {
|
||||
assert_eq!(h.response(("revolve-reset", "bevelWidth")), width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bevel_reset_restores_the_bevel_settings_and_keeps_the_others() {
|
||||
let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", vectorcraft_effects::EXTRUDE, vec2(1400.0, 1000.0));
|
||||
let before = h.app.session.doc().unwrap().doc.clone();
|
||||
h.settle();
|
||||
let enabled = |h: &Harness| h.ctx.read_response(Id::unique("revolve-reset-bevel")).unwrap().enabled();
|
||||
assert!(!enabled(&h), "every bevel setting at its default: Reset is off");
|
||||
let changed = json!({"bevel": "step", "bevelWidth": 12.0, "bevelHeight": 3.0, "bevelRepeat": 4, "bevelSpace": 30.0, "bevelInside": true, "bevelBothSides": true, "depth": 90.0, "twist": 45.0, "rotationX": 10.0});
|
||||
h.app.ui.dialog.as_mut().unwrap().fields.extend(changed.as_object().unwrap().clone());
|
||||
h.settle();
|
||||
assert!(enabled(&h));
|
||||
h.click(h.response("revolve-reset-bevel").center());
|
||||
let defaults = vectorcraft_effects::default_params(vectorcraft_effects::EXTRUDE).unwrap();
|
||||
let dialog = h.app.ui.dialog.as_ref().unwrap();
|
||||
for key in ["bevel", "bevelWidth", "bevelHeight", "bevelRepeat", "bevelSpace", "bevelInside", "bevelBothSides"] {
|
||||
assert_eq!(dialog.fields.get(key), defaults.get(key), "reset: {key}");
|
||||
}
|
||||
for key in ["depth", "twist", "rotationX"] {
|
||||
assert_eq!(dialog.fields.get(key), changed.get(key), "kept: {key}");
|
||||
}
|
||||
assert!(!enabled(&h), "Reset turns itself off");
|
||||
// One bevel setting off its default is enough to turn Reset on again.
|
||||
h.app.ui.dialog.as_mut().unwrap().fields.insert("bevelBothSides".into(), json!(true));
|
||||
h.settle();
|
||||
assert!(enabled(&h));
|
||||
dialogs::confirm(&mut h.app).unwrap();
|
||||
let state = h.app.session.doc().unwrap();
|
||||
let params = vectorcraft_effects::merged_params(
|
||||
vectorcraft_effects::EXTRUDE,
|
||||
&state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0].params,
|
||||
);
|
||||
assert_eq!((params["depth"].clone(), params["bevelBothSides"].clone(), params["bevel"].clone()), (json!(90.0), json!(true), json!("none")));
|
||||
h.app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(h.app.session.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cap_checkbox_previews_resets_and_respects_cancel_and_one_step_undo() {
|
||||
for confirm in [false, true] {
|
||||
|
||||
@@ -306,6 +306,9 @@ fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
|
||||
if d.kind == "roundedRectangle" {
|
||||
form::length_field(ui, d, "radius", &form::humanized("radius"), unit);
|
||||
}
|
||||
if d.kind == "ellipse" {
|
||||
form::field(ui, d, "anchors", "Anchors:");
|
||||
}
|
||||
});
|
||||
let Some(rows) = rows else { return };
|
||||
let on = d.bool(LINK);
|
||||
@@ -358,6 +361,13 @@ fn follow_link(d: &mut Dialog, typed: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Ellipse dialog's Anchors: the nearest whole number from 2 to 1000 (4, a live ellipse, when
|
||||
/// left empty or not a number).
|
||||
fn ellipse_anchors(d: &Dialog) -> u64 {
|
||||
let n = d.f64("anchors", 4.0);
|
||||
if n.is_finite() { n.round().clamp(2.0, 1000.0) as u64 } else { 4 }
|
||||
}
|
||||
|
||||
/// The top-left corner of a rectangle or ellipse: the click itself, or with Alt held (draw from centre) the click minus half the size.
|
||||
fn box_origin(d: &Dialog) -> (f64, f64) {
|
||||
let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0));
|
||||
@@ -386,11 +396,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
values[key] = json!(d.f64(key, default).clamp(min, 1000.0) as u64);
|
||||
values
|
||||
})
|
||||
.or_else(|| (d.kind == "ellipse").then(|| json!({"anchors": ellipse_anchors(d)})))
|
||||
.or_else(|| OPTION_TOOLS.contains(&d.kind.as_str()).then(|| tool_options(d)));
|
||||
let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0));
|
||||
let (bx, by) = box_origin(d);
|
||||
let (id, params) = match d.kind.as_str() {
|
||||
"ellipse" => ("shape.ellipse", json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0)})),
|
||||
"ellipse" => (
|
||||
"shape.ellipse",
|
||||
json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0), "anchors": ellipse_anchors(d)}),
|
||||
),
|
||||
"polygon" => ("shape.polygon", json!({"cx": x, "cy": y, "radius": d.f64("radius", 50.0), "sides": d.f64("sides", 6.0) as u64})),
|
||||
"star" => (
|
||||
"shape.star",
|
||||
@@ -649,6 +663,85 @@ mod tests {
|
||||
assert!((b.width() - 80.0).abs() < 1e-6 && (b.height() - 40.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// The Ellipse dialog opens with Anchors 4, which draws a live ellipse; OK with 6 draws a plain
|
||||
/// path of 6 anchors, and the next Ellipse dialog opens on 6.
|
||||
#[test]
|
||||
fn the_ellipse_dialog_draws_and_keeps_its_anchor_count() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
app.run("tool.select", json!({"tool": "ellipse"})).unwrap();
|
||||
let last = |app: &VectorcraftApp| {
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
doc.layers[0].children().unwrap().last().cloned().expect("an ellipse")
|
||||
};
|
||||
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 4.0);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let n = last(&app);
|
||||
assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape());
|
||||
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 150.0, "y": 150.0}));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("anchors".into(), json!("6"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let n = last(&app);
|
||||
assert!(n.live_shape().is_none());
|
||||
assert_eq!(n.path_data().unwrap().anchor_count(), 6);
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 100.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{b:?}");
|
||||
|
||||
// Kept as the Ellipse tool's `anchors` option for the next click, after another tool too.
|
||||
assert_eq!(app.session.tool_options_of("ellipse")["anchors"], json!(6));
|
||||
app.run("tool.select", json!({"tool": "rectangle"})).unwrap();
|
||||
app.run("tool.select", json!({"tool": "ellipse"})).unwrap();
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0);
|
||||
app.ui.dialog = None;
|
||||
// `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps.
|
||||
for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] {
|
||||
app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap();
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}");
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog's Anchors field is named, under Height, and typing into it sets the count.
|
||||
#[test]
|
||||
fn the_ellipse_dialog_shows_an_anchors_field() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0}));
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state(
|
||||
move |ui, app: &mut VectorcraftApp| {
|
||||
if !std::mem::replace(&mut fonts, true) {
|
||||
crate::theme::install_fonts(ui.ctx());
|
||||
return;
|
||||
}
|
||||
super::super::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.check_accessibility();
|
||||
let height = h.get_by_role_and_label(Role::TextInput, "Height:").rect();
|
||||
let anchors = h.get_by_role_and_label(Role::TextInput, "Anchors:").rect();
|
||||
assert!(anchors.center().y > height.center().y, "Anchors is below Height: {anchors:?} {height:?}");
|
||||
assert_eq!(ellipse_anchors(h.state().ui.dialog.as_ref().unwrap()), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_anchors_take_the_nearest_whole_number_from_2_to_1000() {
|
||||
let d = |v: Value| Dialog::new("ellipse", json!({ "anchors": v }));
|
||||
for (v, want) in [(json!(6), 6), (json!("7"), 7), (json!(5.6), 6), (json!(1), 2), (json!(0), 2), (json!(-3), 2), (json!(5000), 1000)] {
|
||||
assert_eq!(ellipse_anchors(&d(v.clone())), want, "{v}");
|
||||
}
|
||||
assert_eq!(ellipse_anchors(&Dialog::new("ellipse", json!({}))), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_line_length_draws_and_keeps_the_same_direction() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
//! (percent of the symbol's size, -1600..1600: below 0 or above 100 for a guide outside the art),
|
||||
//! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` |
|
||||
//! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid;
|
||||
//! 4 = centre), `__edit` (true when editing an existing symbol). Help:
|
||||
//! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an
|
||||
//! existing symbol). Help:
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html>.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -75,7 +76,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
return Err("nothing selected".into());
|
||||
}
|
||||
let name = st.doc.unique_symbol_name("New Symbol");
|
||||
let mut fields = json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "__edit": false });
|
||||
let mut fields =
|
||||
json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false });
|
||||
if let Some(o) = fields.as_object_mut() {
|
||||
o.extend(slice_fields(None));
|
||||
}
|
||||
@@ -107,6 +109,7 @@ pub fn open_edit(app: &mut VectorcraftApp, name: Option<&str>) -> Result<Value,
|
||||
"exportType": export,
|
||||
"type": kind,
|
||||
"registration": registration,
|
||||
"alignToPixelGrid": st.doc.symbol_pixel_aligned(&name),
|
||||
"__edit": true,
|
||||
"__from": name,
|
||||
});
|
||||
@@ -160,6 +163,9 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.end_row();
|
||||
}
|
||||
}
|
||||
label(ui, "");
|
||||
form::check(ui, d, "alignToPixelGrid", tl!("Align to Pixel Grid"));
|
||||
ui.end_row();
|
||||
});
|
||||
false
|
||||
}
|
||||
@@ -175,16 +181,17 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let kind = d.str("type");
|
||||
let registration = d.fields.get("registration").and_then(Value::as_u64).unwrap_or(4);
|
||||
let edit = d.fields.get("__edit").and_then(Value::as_bool).unwrap_or(false);
|
||||
let pixel = d.bool("alignToPixelGrid");
|
||||
let r = if edit {
|
||||
let from = d.fields.get("__from").and_then(Value::as_str).unwrap_or(name);
|
||||
let mut params = json!({ "name": from, "exportType": export, "type": kind, "registration": registration });
|
||||
let mut params = json!({ "name": from, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel });
|
||||
merge(&mut params, slice_params(d));
|
||||
if from != name {
|
||||
params["newName"] = json!(name);
|
||||
}
|
||||
app.run("symbol.options", params)
|
||||
} else {
|
||||
let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration });
|
||||
let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel });
|
||||
merge(&mut params, slice_params(d));
|
||||
app.run("symbol.new", params)
|
||||
};
|
||||
|
||||
@@ -13,7 +13,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) {
|
||||
let y = p.get("y").and_then(Value::as_f64).unwrap_or(0.0);
|
||||
let alt = p.get("alt").and_then(Value::as_bool).unwrap_or(false);
|
||||
let d = match kind {
|
||||
"rectangle" | "ellipse" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt"})),
|
||||
"rectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt"})),
|
||||
"ellipse" => Dialog::new(
|
||||
kind,
|
||||
json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "anchors": app.session.tool_options_of(kind)["anchors"]}),
|
||||
),
|
||||
"roundedRectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": "12 pt"})),
|
||||
"polygon" => Dialog::new(kind, json!({"x": x, "y": y, "radius": "50 pt", "sides": app.session.tool_options_of(kind)["sides"]})),
|
||||
"star" => {
|
||||
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user