mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 20:46:22 +01:00
Merge remote-tracking branch 'upstream/main' into pencil-redraw-extend
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
25c47fbddc
292 files changed
+15014
-1174
No files matched your search
@@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
|
||||
@@ -58,7 +58,12 @@ fn idle_control_socket_releases_its_worker() {
|
||||
fn idle_expiry_closes_without_writing_a_line() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected"));
|
||||
let mut got = Vec::new();
|
||||
client.read_to_end(&mut got).unwrap();
|
||||
match client.read_to_end(&mut got) {
|
||||
// On Windows the server's close can reach the client as a reset.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {}
|
||||
Ok(_) => {}
|
||||
Err(e) => panic!("reading the idle connection: {e}"),
|
||||
}
|
||||
assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection");
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
@@ -753,13 +753,22 @@ enum FirstFrame {
|
||||
Shown,
|
||||
/// Overdue.
|
||||
Hung,
|
||||
/// Overdue, but the UI is still building the first frame: the app's own work (on a slow
|
||||
/// machine, or with antivirus reading every font file), not the adapter, which has been given
|
||||
/// nothing to show yet.
|
||||
Busy,
|
||||
}
|
||||
|
||||
/// The window's start after `frames` frames run, `since` its first frame was due.
|
||||
fn first_frame(frames: u64, since: Duration, minimized: bool) -> FirstFrame {
|
||||
/// The window's start after `frames` frames run, `since` its first frame was due and
|
||||
/// `since_built` the first frame's UI pass ended (`None` while it runs). A frame counts once its
|
||||
/// UI pass ends, before it is painted, so the adapter's time starts there: with no frame run, the
|
||||
/// UI thread is in the app's code, and starting again without the adapter wouldn't help (#5160).
|
||||
fn first_frame(frames: u64, since: Duration, since_built: Option<Duration>, minimized: bool) -> FirstFrame {
|
||||
if frames >= 2 || minimized {
|
||||
FirstFrame::Shown
|
||||
} else if since >= FIRST_FRAME_TIMEOUT {
|
||||
} else if frames == 0 {
|
||||
if since >= FIRST_FRAME_TIMEOUT { FirstFrame::Busy } else { FirstFrame::Wait }
|
||||
} else if since_built.unwrap_or(since) >= FIRST_FRAME_TIMEOUT {
|
||||
FirstFrame::Hung
|
||||
} else {
|
||||
FirstFrame::Wait
|
||||
@@ -767,18 +776,34 @@ fn first_frame(frames: u64, since: Duration, minimized: bool) -> FirstFrame {
|
||||
}
|
||||
|
||||
/// Watch the window's first frame from another thread: once it reaches the screen, clear the start
|
||||
/// from [`START_FILE`]; when it hasn't reached the screen [`FIRST_FRAME_TIMEOUT`] after the app was
|
||||
/// created ([`Startup::ready`]), start the app again without the adapter, as [`finish`] does for
|
||||
/// one that failed, and end this process, whose UI thread is stuck in the graphics driver.
|
||||
/// from [`START_FILE`]; when it hasn't reached the screen [`FIRST_FRAME_TIMEOUT`] after its UI pass
|
||||
/// ended, start the app again without the adapter, as [`finish`] does for one that failed, and end
|
||||
/// this process, whose UI thread is stuck in the graphics driver. A first frame still being built
|
||||
/// that long is waited for, with a note in the log.
|
||||
pub fn watch_first_frame(startup: Arc<Startup>) {
|
||||
let mut built: Option<Instant> = None;
|
||||
let mut noted = false;
|
||||
let watch = move || loop {
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
let Some(due) = startup.ready.get() else { continue };
|
||||
let ui = startup.ui.get();
|
||||
let frames = ui.map_or(0, egui::Context::cumulative_frame_nr);
|
||||
if frames >= 1 && built.is_none() {
|
||||
built = Some(Instant::now());
|
||||
}
|
||||
let minimized = ui.and_then(|c| c.input(|i| i.viewport().minimized)).unwrap_or(false);
|
||||
match first_frame(frames, due.elapsed(), minimized) {
|
||||
match first_frame(frames, due.elapsed(), built.map(|t| t.elapsed()), minimized) {
|
||||
FirstFrame::Wait => continue,
|
||||
FirstFrame::Busy => {
|
||||
if !noted {
|
||||
log::warn!(
|
||||
"the window's first frame is still being built after {}s: waiting for it (the app's work, not the graphics adapter)",
|
||||
FIRST_FRAME_TIMEOUT.as_secs()
|
||||
);
|
||||
noted = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
FirstFrame::Shown => {
|
||||
startup.presented();
|
||||
return;
|
||||
|
||||
@@ -366,14 +366,19 @@ fn gpus_without_pci_ids_are_told_apart_by_name() {
|
||||
fn a_first_frame_that_never_reaches_the_screen_hangs_its_adapter() {
|
||||
let s = Duration::from_secs;
|
||||
// The second frame began: the first was presented.
|
||||
assert_eq!(first_frame(2, s(60), false), FirstFrame::Shown);
|
||||
// Still drawing (or presenting) the first frame: waited for, then given up on (#964).
|
||||
for frames in [0, 1] {
|
||||
assert_eq!(first_frame(frames, s(3), false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(frames, FIRST_FRAME_TIMEOUT, false), FirstFrame::Hung);
|
||||
}
|
||||
assert_eq!(first_frame(2, s(60), Some(s(1)), false), FirstFrame::Shown);
|
||||
// The first frame built and not yet presented: waited for, then given up on (#964), counting
|
||||
// from when its UI pass ended.
|
||||
assert_eq!(first_frame(1, s(3), Some(s(1)), false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(1, FIRST_FRAME_TIMEOUT, Some(FIRST_FRAME_TIMEOUT), false), FirstFrame::Hung);
|
||||
assert_eq!(first_frame(1, s(45), Some(s(5)), false), FirstFrame::Wait, "a first frame built slowly gets its full time to show");
|
||||
assert_eq!(first_frame(1, FIRST_FRAME_TIMEOUT, None, false), FirstFrame::Hung);
|
||||
// The first frame still being built: the app's work, not the adapter's (#5160).
|
||||
assert_eq!(first_frame(0, s(3), None, false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(0, FIRST_FRAME_TIMEOUT, None, false), FirstFrame::Busy);
|
||||
assert_eq!(first_frame(0, s(600), None, false), FirstFrame::Busy, "never a restart without an adapter");
|
||||
// A window minimized at the start may not draw again until restored.
|
||||
assert_eq!(first_frame(1, s(60), true), FirstFrame::Shown);
|
||||
assert_eq!(first_frame(1, s(60), Some(s(60)), true), FirstFrame::Shown);
|
||||
// A hung adapter is left out once, like one that failed.
|
||||
let skip = vec!["Dx12:10de:28a0".to_string()];
|
||||
assert_eq!(restart_without(true, 1, Some("Dx12:10de:28a0"), &skip), None);
|
||||
|
||||
@@ -44,19 +44,50 @@ macro_rules! dialog_settings {
|
||||
|
||||
dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog);
|
||||
|
||||
/// On Linux and the BSDs the dialog is GTK's or the desktop portal's, which match a file type's
|
||||
/// `*.ext` patterns case-sensitively.
|
||||
const CASE_SENSITIVE_FILTERS: bool =
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"));
|
||||
|
||||
/// The extensions an open dialog's filter is given for `exts`: with `any_case`, each extension
|
||||
/// that has a letter is followed by a pattern with each letter as a `[xX]` pair, so the filter for
|
||||
/// `dib` also lists `image.DIB` and `image.Dib`.
|
||||
fn open_extensions(exts: &[impl AsRef<str>], any_case: bool) -> Vec<String> {
|
||||
let mut out = Vec::with_capacity(exts.len() * 2);
|
||||
for e in exts {
|
||||
let e = e.as_ref();
|
||||
out.push(e.to_string());
|
||||
if any_case && e.chars().any(|c| c.is_ascii_alphabetic()) {
|
||||
out.push(
|
||||
e.chars()
|
||||
.map(|c| if c.is_ascii_alphabetic() { format!("[{}{}]", c.to_ascii_lowercase(), c.to_ascii_uppercase()) } else { c.to_string() })
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `d` set up for `request`: its title, file types, folder and suggested name.
|
||||
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::OpenMany => {
|
||||
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
|
||||
d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name),
|
||||
&open_extensions(exts, CASE_SENSITIVE_FILTERS),
|
||||
)
|
||||
});
|
||||
}
|
||||
PickRequest::Folder => return d,
|
||||
};
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_));
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
|
||||
d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), exts)
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()),
|
||||
&open_extensions(exts, any_case),
|
||||
)
|
||||
});
|
||||
let d = match &pick.folder {
|
||||
Some(folder) => d.folder(folder),
|
||||
@@ -663,3 +694,84 @@ mod open_with_tests {
|
||||
assert_eq!(super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key), None, "deleted");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dialog_tests {
|
||||
use super::{CASE_SENSITIVE_FILTERS, DialogSettings, FilePick, PickRequest, dialog_for, fileio, open_extensions};
|
||||
|
||||
/// The file types a dialog was given, by label.
|
||||
#[derive(Default)]
|
||||
struct Filters(Vec<(String, Vec<String>)>);
|
||||
|
||||
impl DialogSettings for Filters {
|
||||
fn parent(self, _window: &winit::window::Window) -> Self {
|
||||
self
|
||||
}
|
||||
fn title(self, _title: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn filter(mut self, name: &str, exts: &[impl ToString]) -> Self {
|
||||
self.0.push((name.to_string(), exts.iter().map(ToString::to_string).collect()));
|
||||
self
|
||||
}
|
||||
fn folder(self, _folder: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn file_name(self, _name: &str) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the case-sensitive pattern `*.{ext}` match `name`? `ext` may hold literal characters,
|
||||
/// `*` and `[..]` sets.
|
||||
fn matches(ext: &str, name: &str) -> bool {
|
||||
fn here(p: &[char], n: &[char]) -> bool {
|
||||
match p.split_first() {
|
||||
None => n.is_empty(),
|
||||
Some(('*', rest)) => (0..=n.len()).any(|i| here(rest, &n[i..])),
|
||||
Some(('[', rest)) => {
|
||||
let Some(end) = rest.iter().position(|&c| c == ']') else { return false };
|
||||
n.split_first().is_some_and(|(c, n)| rest[..end].contains(c) && here(&rest[end + 1..], n))
|
||||
}
|
||||
Some((c, rest)) => n.split_first().is_some_and(|(d, n)| d == c && here(rest, n)),
|
||||
}
|
||||
}
|
||||
let pattern: Vec<char> = format!("*.{ext}").chars().collect();
|
||||
here(&pattern, &name.chars().collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Where filters match case-sensitively, every extension of File › Open and Place lists files
|
||||
/// whose extension is in capitals or mixed case, `image.DIB` and `image.Pns` included.
|
||||
#[test]
|
||||
fn open_and_place_filters_list_extensions_in_any_case() {
|
||||
let all = fileio::open_filters().chain(fileio::place_filters());
|
||||
for (label, exts) in all {
|
||||
let patterns = open_extensions(exts, true);
|
||||
for ext in exts {
|
||||
let mut mixed = ext.to_ascii_uppercase();
|
||||
mixed.replace_range(..1, &ext[..1]);
|
||||
for name in [format!("a.{ext}"), format!("a.{}", ext.to_ascii_uppercase()), format!("a.{mixed}")] {
|
||||
assert!(patterns.iter().any(|p| matches(p, &name)), "{label}: {patterns:?} don't match {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(open_extensions(&["dib", "jp2", "*"], true), ["dib", "[dD][iI][bB]", "jp2", "[jJ][pP]2", "*"]);
|
||||
assert_eq!(open_extensions(&["dib", "PNS"], false), ["dib", "PNS"]);
|
||||
}
|
||||
|
||||
/// Open and Place dialogs get the any-case patterns on Linux and the BSDs; a save dialog's file
|
||||
/// types stay as listed.
|
||||
#[test]
|
||||
fn open_dialogs_get_any_case_patterns_where_filters_are_case_sensitive() {
|
||||
let dib = vec![FilePick::filter("BMP", &["bmp", "dib"])];
|
||||
let pick = FilePick { filters: dib.clone(), ..Default::default() };
|
||||
let expected = |any_case: bool| open_extensions(&["bmp", "dib"], any_case);
|
||||
let opened = dialog_for(Filters::default(), &PickRequest::Open(pick.clone())).0;
|
||||
assert_eq!(opened[0].1, expected(CASE_SENSITIVE_FILTERS));
|
||||
let saved = dialog_for(Filters::default(), &PickRequest::Save(pick)).0;
|
||||
assert_eq!(saved, dib);
|
||||
let placed = dialog_for(Filters::default(), &PickRequest::OpenMany).0;
|
||||
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
|
||||
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
|
||||
}
|
||||
}
|
||||
@@ -201,3 +201,11 @@ sync_github_name = false
|
||||
|
||||
[people.FrancoJacquet]
|
||||
real_name = "Franco Jacquet"
|
||||
|
||||
[people.FractalEncrypt]
|
||||
sync_github_name = true
|
||||
|
||||
[people.sadkotheguest]
|
||||
real_name = "Alexander Buraga"
|
||||
display_name = "Alexander Buraga"
|
||||
sync_github_name = false
|
||||
@@ -86,6 +86,9 @@ const TINT_STEPS: u32 = 16;
|
||||
const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0;
|
||||
/// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for.
|
||||
const MAX_INK_TINTS: usize = 4096;
|
||||
/// How many even steps [`Gradient::ink_mixes`] checks the lightness of two stops' display RGB mix
|
||||
/// at, to tell whether it moves steadily from one stop's lightness to the other's.
|
||||
const INK_MIX_STEPS: u32 = 64;
|
||||
|
||||
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
|
||||
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
|
||||
@@ -401,8 +404,10 @@ impl Gradient {
|
||||
/// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab
|
||||
/// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix
|
||||
/// position itself when the two colors' lightness differs by less than
|
||||
/// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than
|
||||
/// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
/// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere
|
||||
/// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even
|
||||
/// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more
|
||||
/// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> {
|
||||
use crate::libraries::srgb_to_oklab;
|
||||
if self.method.is_classic() || !self.fits_ink_tints() {
|
||||
@@ -414,8 +419,16 @@ impl Gradient {
|
||||
out.push((s.offset, i, 0.0, s.opacity));
|
||||
let Some(n) = self.stops.get(i + 1) else { continue };
|
||||
let (l0, l1) = (lightness(&s.color), lightness(&n.color));
|
||||
let mixed_lightness = |w: f32| lightness(&GradientMethod::Classic.mix(&s.color, &n.color, w));
|
||||
// The mix position itself when the lightness doesn't tell the mixes apart.
|
||||
let by_position = (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN
|
||||
|| !(0..=INK_MIX_STEPS)
|
||||
.map(|k| mixed_lightness(k as f32 / INK_MIX_STEPS as f32))
|
||||
.collect::<Vec<_>>()
|
||||
.windows(2)
|
||||
.all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0);
|
||||
for v in perceptual_mixes(s, n) {
|
||||
let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN {
|
||||
let weight = if by_position {
|
||||
v
|
||||
} else {
|
||||
let want = lightness(&self.method.mix(&s.color, &n.color, v));
|
||||
@@ -423,7 +436,7 @@ impl Gradient {
|
||||
for _ in 0..TINT_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
// The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one.
|
||||
if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 {
|
||||
if (mixed_lightness(mid) - want) * (l1 - l0) < 0.0 {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
|
||||
@@ -585,3 +585,22 @@ fn ink_mixes_follow_the_perceptual_curve() {
|
||||
g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect();
|
||||
assert_eq!(g.ink_mixes(), None);
|
||||
}
|
||||
|
||||
/// From red to blue the display RGB mix darkens past blue's lightness and comes back, so a
|
||||
/// weight found by lightness near the blue stop would be a red-side one and the inks would jump
|
||||
/// there. The weights are the mix positions instead, and reach the blue stop's inks steadily.
|
||||
#[test]
|
||||
fn ink_mixes_use_the_mix_position_when_the_lightness_turns_back() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red), GradientStop::new(1.0, blue)]);
|
||||
g.method = GradientMethod::Perceptual;
|
||||
let mixes = g.ink_mixes().expect("a Perceptual gradient's curve");
|
||||
assert_eq!(mixes[mixes.len() - 1], (1.0, 1, 0.0, 1.0), "the blue stop");
|
||||
let between: Vec<_> = mixes.iter().filter(|m| m.1 == 0 && m.0 > 0.0).collect();
|
||||
assert!(!between.is_empty(), "stops on the curve between red and blue: {mixes:?}");
|
||||
// With the midpoint at ½, a stop's offset on the curve is its mix position.
|
||||
for (t, _, w, _) in &between {
|
||||
assert!((w - t).abs() < 1e-6, "at {t}: weight {w}");
|
||||
}
|
||||
assert!(mixes.windows(2).filter(|p| p[1].1 == 0).all(|p| p[0].2 <= p[1].2), "the weights rise: {mixes:?}");
|
||||
}
|
||||
@@ -99,13 +99,15 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working
|
||||
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit).
|
||||
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The
|
||||
/// layer is removed wherever it is, also as a sublayer of another layer; an id that names
|
||||
/// anything other than a layer is left alone.
|
||||
pub fn drop_edit_modes(&mut self) {
|
||||
if let Some(me) = self.mask_edit.take() {
|
||||
self.layers.retain(|l| l.id != me.layer);
|
||||
}
|
||||
if let Some(se) = self.symbol_edit.take() {
|
||||
self.layers.retain(|l| l.id != se.layer);
|
||||
let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)];
|
||||
for id in layers.into_iter().flatten() {
|
||||
if self.node(id).is_some_and(Node::is_layer) {
|
||||
let _ = self.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ pub mod live;
|
||||
pub mod live_paint;
|
||||
pub mod marks;
|
||||
mod mem;
|
||||
pub use mem::{appearance_heap_bytes, paint_heap_bytes};
|
||||
pub mod metadata;
|
||||
pub mod node;
|
||||
pub mod objects_on_path;
|
||||
@@ -67,6 +68,7 @@ mod symbols;
|
||||
pub use symbols::SymbolBoxes;
|
||||
pub mod text;
|
||||
pub mod trace;
|
||||
pub mod twist;
|
||||
pub mod variables;
|
||||
pub mod xml_id;
|
||||
|
||||
@@ -110,6 +112,7 @@ pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
|
||||
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
|
||||
pub use style_libs::StyleLibrary;
|
||||
pub use text::FontHeightReference;
|
||||
pub use text::GlyphChoice;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition,
|
||||
@@ -226,8 +229,9 @@ pub struct Document {
|
||||
#[serde(default, skip_serializing)]
|
||||
pub mask_edit: Option<MaskEdit>,
|
||||
/// Symbol editing mode, while active. Never saved (see [`Document::without_edit_modes`]): the
|
||||
/// symbol already holds the art of its editing layer.
|
||||
#[serde(default, skip_serializing)]
|
||||
/// symbol already holds the art of its editing layer. Never read either: a value in file data
|
||||
/// is dropped, so the layer it names is kept and saving does not write the value again.
|
||||
#[serde(default, skip_serializing, deserialize_with = "skip::read_as_none")]
|
||||
pub symbol_edit: Option<SymbolEdit>,
|
||||
next_id: u64,
|
||||
/// Foreign data preserved on round-trip.
|
||||
|
||||
@@ -13,7 +13,9 @@ pub enum DocError {
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
pub const FORMAT_VERSION: u32 = 1;
|
||||
/// The document version new documents get. Version 2: a positive Twist angle turns clockwise
|
||||
/// ([`crate::twist`]).
|
||||
pub const FORMAT_VERSION: u32 = 2;
|
||||
|
||||
/// Node, slice and asset ids are handed out below this: no document gets near it by counting, so
|
||||
/// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718).
|
||||
|
||||
+33
-12
@@ -98,7 +98,7 @@ impl Document {
|
||||
vec_bytes(g) + g.iter().map(|g: &SwatchGroup| g.name.capacity() + swatches_bytes(&g.swatches)).sum::<usize>()
|
||||
});
|
||||
n += shared(&self.graphic_styles, &newer.graphic_styles, |g| {
|
||||
vec_bytes(g) + g.iter().map(|g: &GraphicStyle| g.name.capacity() + appearance_heap(&g.appearance)).sum::<usize>()
|
||||
vec_bytes(g) + g.iter().map(|g: &GraphicStyle| g.name.capacity() + appearance_heap_bytes(&g.appearance)).sum::<usize>()
|
||||
});
|
||||
let styles = |s: &Vec<TextStyleDef>| vec_bytes(s) + s.iter().map(|s| s.name.capacity() + map_bytes(&s.attrs)).sum::<usize>();
|
||||
n += shared(&self.char_styles, &newer.char_styles, styles);
|
||||
@@ -245,7 +245,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize {
|
||||
let mut b = ALLOC + ARC + size_of::<Node>();
|
||||
b += n.name.as_ref().map_or(0, String::capacity);
|
||||
if !other.is_some_and(|m| Shared::ptr_eq(&m.appearance, &n.appearance)) {
|
||||
b += ALLOC + ARC + appearance_heap(&n.appearance);
|
||||
b += ALLOC + ARC + appearance_heap_bytes(&n.appearance);
|
||||
}
|
||||
if let Some(e) = n.extras_box() {
|
||||
b += ALLOC + size_of::<NodeExtras>();
|
||||
@@ -293,32 +293,53 @@ fn text_bytes(t: &TextObject) -> usize {
|
||||
+ vec_bytes(&t.cached_baselines)
|
||||
}
|
||||
|
||||
/// The heap an appearance owns (not the appearance itself).
|
||||
fn appearance_heap(a: &Appearance) -> usize {
|
||||
/// Approximate retained memory of an appearance and its owned buffers, without serialization.
|
||||
pub fn appearance_heap_bytes(a: &Appearance) -> usize {
|
||||
size_of::<Appearance>()
|
||||
+ vec_bytes(&a.items)
|
||||
+ a.items
|
||||
.iter()
|
||||
.map(|i| match i {
|
||||
AppearanceItem::Fill(f) => paint_heap(&f.paint),
|
||||
AppearanceItem::Stroke(s) => paint_heap(&s.paint),
|
||||
.map(|item| {
|
||||
let paint = paint_heap_bytes(item.paint());
|
||||
let effects = effects_heap(item.effects());
|
||||
let stroke = match item {
|
||||
AppearanceItem::Stroke(s) => {
|
||||
s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern))
|
||||
+ s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points))
|
||||
+ s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points))
|
||||
+ s.brush.as_ref().map_or(0, String::capacity)
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
paint + effects + stroke
|
||||
})
|
||||
.sum::<usize>()
|
||||
+ vec_bytes(&a.effects)
|
||||
+ a.effects.iter().map(|e: &Effect| e.id.capacity() + json_bytes(&e.params)).sum::<usize>()
|
||||
+ effects_heap(&a.effects)
|
||||
}
|
||||
|
||||
fn paint_heap(p: &Paint) -> usize {
|
||||
fn effects_heap(effects: &Vec<Effect>) -> usize {
|
||||
vec_bytes(effects) + effects.iter().map(|e| e.id.capacity() + json_bytes(&e.params)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// Approximate heap retained by one paint, without serializing it.
|
||||
pub fn paint_heap_bytes(p: &Paint) -> usize {
|
||||
match p {
|
||||
Paint::Solid { swatch, .. } => swatch.as_ref().map_or(0, String::capacity),
|
||||
Paint::Gradient(g) => ALLOC + size_of_val(&**g) + vec_bytes(&g.gradient.stops),
|
||||
Paint::Gradient(g) => {
|
||||
ALLOC
|
||||
+ size_of_val(&**g)
|
||||
+ vec_bytes(&g.gradient.stops)
|
||||
+ g.gradient.stops.iter().map(|s| s.swatch.as_ref().map_or(0, String::capacity)).sum::<usize>()
|
||||
+ g.swatch.as_ref().map_or(0, String::capacity)
|
||||
+ g.freeform.as_ref().map_or(0, |f| vec_bytes(&f.points) + vec_bytes(&f.lines) + f.lines.iter().map(vec_bytes).sum::<usize>())
|
||||
}
|
||||
Paint::Pattern { pattern, .. } => pattern.capacity(),
|
||||
Paint::None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn swatches_bytes(s: &[Swatch]) -> usize {
|
||||
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap(&w.paint)).sum::<usize>()
|
||||
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// A vector's buffer (not what its elements own).
|
||||
|
||||
@@ -212,7 +212,10 @@ impl Node {
|
||||
/// [`Node::reach_bounds`] with symbol instances measured by their symbol's art box from
|
||||
/// `symbols`. An instance that only moves its art is measured as the art's visual box moved,
|
||||
/// and any other instance is measured as its geometric box ([`Node::geometric_bounds_with`])
|
||||
/// grown by the farthest a stroke in the art can reach.
|
||||
/// grown by the farthest a stroke in the art can reach. For an instance placed through 9-slice
|
||||
/// guides, that box also holds the art box placed by each cell's map
|
||||
/// ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an instance of a
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform.
|
||||
pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
symbols.quickly(|| self.reach(Some(symbols)))
|
||||
}
|
||||
@@ -367,9 +370,14 @@ impl Node {
|
||||
Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual),
|
||||
Some((s, art)) => {
|
||||
let placed = xf.transform_rect_bbox(art.geometric);
|
||||
match s.placed_visual(symbol, *xf) {
|
||||
match s.placed_visual(symbol, *xf).or_else(|| s.sliced_visual(symbol, *xf)) {
|
||||
Some(v) => v.union(placed),
|
||||
None => placed.inflate(art.reach, art.reach),
|
||||
// Art placed through 9-slice guides can draw outside `placed`.
|
||||
None => s
|
||||
.document()
|
||||
.symbol_slice_map_of(symbol, art.geometric, *xf)
|
||||
.map_or(placed, |m| m.placement_bounds(art.geometric).union(placed))
|
||||
.inflate(art.reach, art.reach),
|
||||
}
|
||||
}
|
||||
None => xf.transform_rect_bbox(SYMBOL_SQUARE),
|
||||
|
||||
@@ -13,3 +13,8 @@ pub fn is_empty_vec<T>(v: &[T]) -> bool {
|
||||
pub fn is_empty_map(v: &serde_json::Map<String, serde_json::Value>) -> bool {
|
||||
v.is_empty()
|
||||
}
|
||||
/// Read a field's value and drop it, giving `None`: for state that is never taken from a file.
|
||||
pub fn read_as_none<'de, D: serde::Deserializer<'de>, T>(d: D) -> Result<Option<T>, D::Error> {
|
||||
<serde::de::IgnoredAny as serde::Deserialize>::deserialize(d)?;
|
||||
Ok(None)
|
||||
}
|
||||
@@ -98,6 +98,10 @@ impl GraphicStyle {
|
||||
/// The extension (and `format` header) of graphic style library files.
|
||||
pub const STYLES_EXT: &str = "vcstyles";
|
||||
|
||||
/// The version of the `.vcstyles` files [`write`] writes. Version 2: a positive Twist angle turns
|
||||
/// clockwise ([`crate::twist`]).
|
||||
const STYLES_VERSION: u32 = crate::twist::TWIST_CLOCKWISE_SINCE;
|
||||
|
||||
/// The file: a header around the library.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct NativeFile {
|
||||
@@ -109,17 +113,21 @@ struct NativeFile {
|
||||
|
||||
/// `lib` as a `.vcstyles` file.
|
||||
pub fn write(lib: &StyleLibrary) -> String {
|
||||
let file = NativeFile { format: STYLES_EXT.into(), version: 1, library: lib.clone() };
|
||||
let file = NativeFile { format: STYLES_EXT.into(), version: STYLES_VERSION, library: lib.clone() };
|
||||
serde_json::to_string_pretty(&file).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Read a `.vcstyles` file; an unnamed library is called `name`.
|
||||
/// Read a `.vcstyles` file; an unnamed library is called `name`. A version 1 file was written by
|
||||
/// an app that turned Twist counterclockwise: its Twist angles are negated.
|
||||
pub fn read(text: &str, name: &str) -> Result<StyleLibrary, String> {
|
||||
let f: NativeFile = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("not a graphic style library: {e}"))?;
|
||||
if f.format != STYLES_EXT {
|
||||
return Err(format!("not a graphic style library (format `{}`)", f.format));
|
||||
}
|
||||
let mut lib = f.library;
|
||||
if f.version < STYLES_VERSION {
|
||||
crate::twist::negate_library(&mut lib);
|
||||
}
|
||||
if lib.name.trim().is_empty() {
|
||||
lib.name = name.into();
|
||||
}
|
||||
|
||||
@@ -343,6 +343,20 @@ impl NineSliceMap {
|
||||
self.cell_xf(self.x.cell(q.x), self.y.cell(q.y))
|
||||
}
|
||||
|
||||
/// A box that holds everything [`Self::place`] draws of art whose geometric box in symbol space
|
||||
/// is `art`, before strokes and effects: `art` placed by each of the nine cells' maps. An object
|
||||
/// that crosses a guide and draws symbol art is placed by the map of the cell its center is in,
|
||||
/// so it can draw outside the box the corner cells place `art` in.
|
||||
pub fn placement_bounds(&self, art: Rect) -> Rect {
|
||||
let mut b = self.cell_xf(0, 0).transform_rect_bbox(art);
|
||||
for j in 0..3 {
|
||||
for i in 0..3 {
|
||||
b = b.union(self.cell_xf(i, j).transform_rect_bbox(art));
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The guides in symbol space: the two x values and the two y values.
|
||||
fn cuts(&self) -> ([f64; 2], [f64; 2]) {
|
||||
let inv = self.natural.inverse();
|
||||
@@ -704,6 +718,12 @@ impl Document {
|
||||
NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf)
|
||||
}
|
||||
|
||||
/// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already
|
||||
/// measured.
|
||||
pub(crate) fn symbol_slice_map_of(&self, name: &str, art: Rect, xf: Affine) -> Option<NineSliceMap> {
|
||||
NineSliceMap::new(self.symbol_nine_slice(name)?, art, self.symbol_natural_xf(name), xf)
|
||||
}
|
||||
|
||||
/// Art `art` of symbol `name` (stained as the caller draws it) placed by an instance's
|
||||
/// transform `xf`, with strokes at their own weight: through the symbol's 9-slice guides when
|
||||
/// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through
|
||||
|
||||
+171
-3
@@ -23,6 +23,9 @@ const MAX_DEPTH: usize = 32;
|
||||
/// holding instances: past it, an estimate stands in ([`SymbolBoxes::effects_reach`]).
|
||||
const MAX_REACHES: usize = 4096;
|
||||
|
||||
/// A symbol's name and the bits of the linear part of a transform that places its art.
|
||||
type Placing = (String, [u64; 4]);
|
||||
|
||||
/// A symbol's art measured in symbol space.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct ArtBox {
|
||||
@@ -37,6 +40,9 @@ pub(crate) struct ArtBox {
|
||||
/// The widest stroke of the objects with a visible brushed stroke in the art, or in the art
|
||||
/// of a symbol an instance in it shows: `None` when no object there has one.
|
||||
pub(crate) brush: Option<f64>,
|
||||
/// Whether the art holds an instance of a symbol with 9-slice guides, or of a symbol whose art
|
||||
/// holds one at any depth.
|
||||
pub(crate) sliced: bool,
|
||||
}
|
||||
|
||||
/// The art boxes of a document's symbols, which [`Node::geometric_bounds_with`],
|
||||
@@ -73,6 +79,14 @@ pub struct SymbolBoxes<'a> {
|
||||
unplaced: RefCell<HashMap<String, f64>>,
|
||||
/// How many times [`Self::measure_art`] has run a measure on symbol art ([`Self::art_measured`]).
|
||||
runs: Cell<usize>,
|
||||
/// The boxes [`Self::sliced_visual`] has measured, by symbol name and the bits of the linear
|
||||
/// part of the transform that placed the art.
|
||||
sliced: RefCell<HashMap<Placing, Option<Rect>>>,
|
||||
/// How many objects of symbol art [`Self::sliced_visual`] has placed, the art of opacity masks
|
||||
/// included.
|
||||
sliced_placed: Cell<u64>,
|
||||
/// The most objects of symbol art [`Self::sliced_visual`] places: [`MAX_SYMBOL_NODES`].
|
||||
sliced_most: u64,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
@@ -90,6 +104,9 @@ impl Document {
|
||||
farthest: RefCell::default(),
|
||||
unplaced: RefCell::default(),
|
||||
runs: Cell::new(0),
|
||||
sliced: RefCell::default(),
|
||||
sliced_placed: Cell::new(0),
|
||||
sliced_most: MAX_SYMBOL_NODES,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,7 +119,11 @@ impl<'a> SymbolBoxes<'a> {
|
||||
|
||||
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
|
||||
/// art box alone. An instance that scales or turns stroked art then measures a little larger
|
||||
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it.
|
||||
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
|
||||
/// visual box of an instance placed through 9-slice guides holds the art box placed by each
|
||||
/// cell's map ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an
|
||||
/// instance of a symbol with 9-slice guides at any depth is measured as its art placed by its
|
||||
/// transform ([`Self::sliced_visual`]).
|
||||
pub fn quick(self) -> Self {
|
||||
self.quick.set(true);
|
||||
self
|
||||
@@ -319,13 +340,64 @@ impl<'a> SymbolBoxes<'a> {
|
||||
if self.quick.get() {
|
||||
return None;
|
||||
}
|
||||
self.place_and_measure(name, xf, most)
|
||||
}
|
||||
|
||||
/// [`Self::placed_visual`] in boxes made by [`Self::quick`] and while symbol art is measured
|
||||
/// too, for a symbol whose art holds an instance of a symbol with 9-slice guides at any depth:
|
||||
/// where that instance draws its art depends on the transform of each instance above it. The
|
||||
/// art is placed once for each symbol and linear part of `xf`, and the box is moved by the rest
|
||||
/// of `xf`. `None` for other symbols, when [`Self::placed_visual`] is `None` outside quick
|
||||
/// boxes, and when placing the art would take the objects of the art these boxes have placed
|
||||
/// for it past [`MAX_SYMBOL_NODES`], the art placed to measure the instances in placed art
|
||||
/// included. The renderer draws no more objects of symbol art than that in one frame.
|
||||
pub(crate) fn sliced_visual(&self, name: &str, xf: Affine) -> Option<Rect> {
|
||||
if !self.art(name)?.sliced {
|
||||
return None;
|
||||
}
|
||||
let [a, b, c, d, e, f] = xf.as_coeffs();
|
||||
let (linear, moved) = (Affine::new([a, b, c, d, 0.0, 0.0]), Affine::translate((e, f)));
|
||||
let key = (name.to_string(), [a, b, c, d].map(f64::to_bits));
|
||||
let cached = self.sliced.borrow().get(&key).copied();
|
||||
let v = match cached {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
// The most objects placing makes, the art of opacity masks included, is set aside
|
||||
// while the art is placed and measured, and what placing did not make is given back.
|
||||
let art = &self.doc.symbols.iter().find(|s| s.name == name)?.art;
|
||||
let most = match self.doc.symbol_slice_map(name, linear) {
|
||||
Some(m) => m.most_placed(art, self.doc),
|
||||
None => art.count_with_masks() as u64,
|
||||
};
|
||||
let used = self.sliced_placed.get();
|
||||
if used.saturating_add(most) > self.sliced_most {
|
||||
return None;
|
||||
}
|
||||
self.sliced_placed.set(used + most);
|
||||
let (v, placed) = self.place_and_count(name, linear, MAX_SYMBOL_NODES).unwrap_or((None, 0));
|
||||
self.sliced_placed.set(self.sliced_placed.get().saturating_sub(most.saturating_sub(placed)));
|
||||
self.sliced.borrow_mut().insert(key, v);
|
||||
v
|
||||
}
|
||||
};
|
||||
v.map(|v| moved.transform_rect_bbox(v))
|
||||
}
|
||||
|
||||
/// The box [`Self::placed_visual_within`] returns outside quick boxes.
|
||||
fn place_and_measure(&self, name: &str, xf: Affine, most: u64) -> Option<Rect> {
|
||||
self.place_and_count(name, xf, most).and_then(|(v, _)| v)
|
||||
}
|
||||
|
||||
/// [`Self::place_and_measure`], with the number of objects of the placed art, the art of
|
||||
/// opacity masks included. `None` when the art is not placed.
|
||||
fn place_and_count(&self, name: &str, xf: Affine, most: u64) -> Option<(Option<Rect>, u64)> {
|
||||
self.measure_art(name, |art| {
|
||||
let art = match self.doc.symbol_slice_map(name, xf) {
|
||||
Some(m) if m.most_placed(art, self.doc) > most => return None,
|
||||
Some(m) => m.place(art, self.doc),
|
||||
None => self.doc.place_symbol_art(name, art, xf)?,
|
||||
};
|
||||
self.in_art(|| art.visual(Some(self)))
|
||||
Some((self.in_art(|| art.visual(Some(self))), art.count_with_masks() as u64))
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
@@ -383,6 +455,7 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
|
||||
let reach = crate::live::max_outset(std::slice::from_ref(art), Some(symbols));
|
||||
let mut effects = false;
|
||||
let mut brush: Option<f64> = None;
|
||||
let mut sliced = false;
|
||||
art.walk(&mut |n| {
|
||||
let mut own = n.appearance.effects.iter().chain(n.appearance.items.iter().flat_map(|i| i.effects().iter()));
|
||||
effects |= own.any(|e| e.visible);
|
||||
@@ -395,9 +468,10 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
|
||||
if let Some(w) = symbols.brush_width(symbol) {
|
||||
brush = Some(brush.map_or(w, |b| b.max(w)));
|
||||
}
|
||||
sliced |= symbols.doc.symbol_nine_slice(symbol).is_some() || symbols.art(symbol).is_some_and(|a| a.sliced);
|
||||
}
|
||||
});
|
||||
Some(ArtBox { geometric, visual, reach, effects, brush })
|
||||
Some(ArtBox { geometric, visual, reach, effects, brush, sliced })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -447,6 +521,100 @@ mod tests {
|
||||
assert_eq!(scaled.reach_bounds_with(&s), Some(Rect::new(0.0, 0.0, 60.0, 30.0).inflate(reach, reach)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_boxes_hold_art_that_9_slice_guides_move_past_the_instance() {
|
||||
// A 100 × 100 frame with guides a quarter in, holding an instance of a bar from x 10 to 70.
|
||||
// Scaled 2 times across, the bar crosses the left guide and is placed by the middle
|
||||
// column's map, x → 3x − 50: it draws from x −20 to 160, past the frame's left edge at 0.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0);
|
||||
symbol(&mut d, "Bar", vec![bar]);
|
||||
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
|
||||
let inner = instance(&mut d, "Bar", Affine::IDENTITY);
|
||||
symbol(&mut d, "Panel", vec![frame, inner]);
|
||||
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
|
||||
let panel = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
let exact = panel.visual_bounds_with(&d.symbol_boxes()).unwrap();
|
||||
assert_eq!(exact, Rect::new(-20.0, 0.0, 200.0, 100.0));
|
||||
let quick = panel.visual_bounds_with(&d.symbol_boxes().quick()).unwrap();
|
||||
assert_eq!(quick.union(exact), quick, "{quick:?} holds {exact:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_boxes_hold_art_that_nested_9_slice_guides_move_past_the_instance() {
|
||||
// The panel of the test above, in a symbol without guides: once at its natural size and
|
||||
// once scaled 2 times across. Where the bar draws depends on the transform the holder's
|
||||
// instance adds to the panel's.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0);
|
||||
symbol(&mut d, "Bar", vec![bar]);
|
||||
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
|
||||
let inner = instance(&mut d, "Bar", Affine::IDENTITY);
|
||||
symbol(&mut d, "Panel", vec![frame, inner]);
|
||||
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
|
||||
let natural = instance(&mut d, "Panel", Affine::IDENTITY);
|
||||
symbol(&mut d, "Holder", vec![natural]);
|
||||
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
symbol(&mut d, "Wide holder", vec![wide]);
|
||||
// The holder scaled 2 times across scales the panel 2 times across: the bar draws from x
|
||||
// −20 to 160, as in the test above.
|
||||
let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(2.0, 1.0));
|
||||
let quick = holder.visual_bounds_with(&d.symbol_boxes().quick()).unwrap();
|
||||
let drawn = Rect::new(-20.0, 40.0, 160.0, 60.0);
|
||||
assert_eq!(quick.union(drawn), quick, "{quick:?} holds {drawn:?}");
|
||||
let wide_holder = instance(&mut d, "Wide holder", Affine::scale(2.0));
|
||||
for n in [&holder, &wide_holder] {
|
||||
let exact = n.visual_bounds_with(&d.symbol_boxes()).unwrap();
|
||||
assert!(exact.x0 < 0.0, "{exact:?} reaches past the frame's left edge");
|
||||
let quick = n.visual_bounds_with(&d.symbol_boxes().quick()).unwrap();
|
||||
assert_eq!(quick.union(exact), quick, "{quick:?} holds {exact:?}");
|
||||
let reach = n.reach_bounds_with(&d.symbol_boxes()).unwrap();
|
||||
assert_eq!(reach.union(exact), reach, "{reach:?} holds {exact:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_boxes_place_art_that_holds_9_slice_instances_a_bounded_number_of_times() {
|
||||
// A frame with guides, and 16 levels of symbols that each hold an instance of the level
|
||||
// below a little taller and one turned a little: the transforms that place the frame differ
|
||||
// for each of the 2^16 ways down, so measuring every one would place art 2^17 times.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
|
||||
symbol(&mut d, "Level 0", vec![frame]);
|
||||
d.set_symbol_nine_slice("Level 0", Some(crate::SymbolNineSlice::default()));
|
||||
let (taller, turned) = (Affine::scale_non_uniform(1.0, 1.01), Affine::rotate(0.1));
|
||||
for i in 1..=16 {
|
||||
let below = format!("Level {}", i - 1);
|
||||
let pair = vec![instance(&mut d, &below, taller), instance(&mut d, &below, turned)];
|
||||
symbol(&mut d, &format!("Level {i}"), pair);
|
||||
}
|
||||
let top = instance(&mut d, "Level 16", taller);
|
||||
// With room for 5,000 objects: each placement places at least one.
|
||||
let s = SymbolBoxes { sliced_most: 5000, ..d.symbol_boxes().quick() };
|
||||
assert!(top.visual_bounds_with(&s).is_some());
|
||||
assert!(s.sliced_placed.get() <= 5000, "{} objects", s.sliced_placed.get());
|
||||
assert!(s.art_measured() <= 5000 + d.symbols.len(), "{} measures", s.art_measured());
|
||||
// Instances whose transforms differ only by a move place the art once.
|
||||
let level = instance(&mut d, "Level 1", taller);
|
||||
let moved = instance(&mut d, "Level 1", Affine::translate((5.0, 7.0)) * taller);
|
||||
let s = d.symbol_boxes().quick();
|
||||
let b = level.visual_bounds_with(&s).unwrap();
|
||||
let measured = s.art_measured();
|
||||
assert_eq!(moved.visual_bounds_with(&s), Some(Affine::translate((5.0, 7.0)).transform_rect_bbox(b)));
|
||||
assert_eq!(s.art_measured(), measured);
|
||||
// The art of an opacity mask counts toward the limit: a group holding the framed
|
||||
// instance, masked by a group of 10 rectangles, is 13 objects.
|
||||
let mut framed = instance(&mut d, "Level 0", Affine::IDENTITY);
|
||||
let squares = (0..10).map(|_| Arc::new(rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0))).collect();
|
||||
let mask = Node::group(d.alloc_id(), squares);
|
||||
framed.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(mask, true)));
|
||||
symbol(&mut d, "Masked", vec![framed]);
|
||||
let masked = instance(&mut d, "Masked", taller);
|
||||
let s = d.symbol_boxes().quick();
|
||||
assert!(masked.visual_bounds_with(&s).is_some());
|
||||
assert_eq!(s.sliced_placed.get(), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
|
||||
@@ -451,3 +451,64 @@ fn pica_form_rejects_exponent_notation() {
|
||||
assert_eq!(Unit::Points.parse(s), None, "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol editing of symbol "S" on `layer`.
|
||||
fn symbol_edit_on(layer: NodeId) -> SymbolEdit {
|
||||
SymbolEdit {
|
||||
symbol: "S".into(),
|
||||
layer,
|
||||
instance: None,
|
||||
xf: Affine::IDENTITY,
|
||||
group: false,
|
||||
changed: false,
|
||||
back_isolation: None,
|
||||
back_layer: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity-mask and symbol editing layers are left out of the saved document wherever they
|
||||
/// are, also when `layer.move` made them sublayers of another layer.
|
||||
#[test]
|
||||
fn edit_mode_layers_are_dropped_as_sublayers_too() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let host = d.layers[0].id;
|
||||
let mask = d.add_layer(Some("Mask"));
|
||||
let symbol = d.add_layer(Some("Symbol"));
|
||||
d.move_node(mask, Some(host), 0).unwrap();
|
||||
d.move_node(symbol, Some(host), usize::MAX).unwrap();
|
||||
let object = d.alloc_id();
|
||||
d.mask_edit = Some(MaskEdit { object, layer: mask });
|
||||
d.symbol_edit = Some(symbol_edit_on(symbol));
|
||||
let saved = d.without_edit_modes();
|
||||
assert!(saved.node(mask).is_none(), "the mask editing layer is left out");
|
||||
assert!(saved.node(symbol).is_none(), "the symbol editing layer is left out");
|
||||
assert!(saved.node(host).is_some_and(|l| l.children().is_some_and(|c| c.is_empty())));
|
||||
assert!(saved.mask_edit.is_none() && saved.symbol_edit.is_none());
|
||||
}
|
||||
|
||||
/// Symbol editing is never read from a file, so a layer that file data names as the editing layer
|
||||
/// loads and stays in the document, and saving does not write the value again.
|
||||
#[test]
|
||||
fn symbol_edit_is_not_read_from_a_file() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
let mut v = serde_json::to_value(&d).unwrap();
|
||||
v["symbol_edit"] = serde_json::to_value(symbol_edit_on(layer)).unwrap();
|
||||
d = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(d.symbol_edit, None);
|
||||
assert!(d.extra.is_empty(), "not kept as an unknown key");
|
||||
d.drop_edit_modes();
|
||||
assert!(d.node(layer).is_some(), "the layer is kept");
|
||||
assert!(serde_json::to_value(&d).unwrap().get("symbol_edit").is_none(), "not saved again");
|
||||
}
|
||||
|
||||
/// An opacity-mask editing id in file data that names art inside a layer, not a layer, leaves the
|
||||
/// art in place.
|
||||
#[test]
|
||||
fn mask_edit_naming_art_leaves_it() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
d.mask_edit = Some(MaskEdit { object: b, layer: a });
|
||||
d.drop_edit_modes();
|
||||
assert!(d.node(a).is_some() && d.node(b).is_some());
|
||||
assert_eq!(d.mask_edit, None);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ mod wrap;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, ScriptMetrics};
|
||||
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection,
|
||||
ParaStyle, SingleWordJustify,
|
||||
|
||||
@@ -147,6 +147,28 @@ pub struct CharStyle {
|
||||
/// document's language (Document Setup). Saved only when set.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub language: Option<String>,
|
||||
/// Another glyph of the font for the run's first character (Glyphs panel › Show › Alternates
|
||||
/// for Current Selection). The text keeps the character; layout draws the chosen glyph while
|
||||
/// the run starts with that character and is set in the face the choice names, and the
|
||||
/// default glyph otherwise. Saved only when set.
|
||||
#[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")]
|
||||
pub glyph_alternate: Option<GlyphChoice>,
|
||||
}
|
||||
|
||||
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
|
||||
/// belongs to, named by its PostScript name and version string, so that a glyph id is never used
|
||||
/// in another font or another version of the font.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct GlyphChoice {
|
||||
/// The character the glyph is drawn for.
|
||||
pub ch: char,
|
||||
/// The glyph id in the face.
|
||||
pub gid: u32,
|
||||
/// The face's PostScript name (`SourceSans3-Regular`).
|
||||
pub font: String,
|
||||
/// The face's version string (`Version 3.052`); empty when it has none.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// What a character's font size measures ([`CharStyle::font_height_reference`]): the em square
|
||||
@@ -420,6 +442,7 @@ impl Default for CharStyle {
|
||||
font_height_reference: FontHeightReference::EmBox,
|
||||
no_break: false,
|
||||
language: None,
|
||||
glyph_alternate: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! The Twist effect's angle in saved documents. A positive angle turns clockwise on the page in
|
||||
//! VectorCraft 0.21.0 and later; earlier releases turned it counterclockwise. Documents of version
|
||||
//! 2 ([`TWIST_CLOCKWISE_SINCE`]) turn clockwise. Version 1 documents written before 0.21.0 have
|
||||
//! their Twist angles negated when they open, so they draw as they were saved
|
||||
//! ([`Document::migrate_twist_angles`], [`written_clockwise`]), and a save for an earlier app
|
||||
//! negates them back ([`Document::store_legacy_twist_angles`]). Graphic style library files
|
||||
//! (`.vcstyles`) of version 1 have their Twist angles negated when they are read
|
||||
//! ([`crate::style_libs::read`]); [`crate::style_libs::write`] writes version 2.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::style_libs::StyleLibrary;
|
||||
use crate::{Appearance, Document, Effect, Node};
|
||||
|
||||
/// The Twist effect's id.
|
||||
pub const TWIST: &str = "distort.twist";
|
||||
|
||||
/// The first document version whose Twist angles turn clockwise for a positive value.
|
||||
pub const TWIST_CLOCKWISE_SINCE: u32 = 2;
|
||||
|
||||
/// The first release (major, minor) whose Twist turned clockwise for a positive angle.
|
||||
const CLOCKWISE_RELEASE: (u64, u64) = (0, 21);
|
||||
|
||||
/// Did the app named by a native file's `generator` (`"VectorCraft 0.21.0"`) turn Twist effects
|
||||
/// clockwise for a positive angle? It did from 0.21.0. Any other value, or none, is an earlier
|
||||
/// app (DrawCraft included).
|
||||
pub fn written_clockwise(generator: Option<&str>) -> bool {
|
||||
let Some(version) = generator.and_then(|g| g.strip_prefix("VectorCraft ")) else { return false };
|
||||
let mut parts = version.split('.').map(|p| p.parse::<u64>().ok());
|
||||
match (parts.next().flatten(), parts.next().flatten()) {
|
||||
(Some(major), Some(minor)) => (major, minor) >= CLOCKWISE_RELEASE,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle a Twist effect without a readable one draws with (`vectorcraft-effects` reads a
|
||||
/// missing or unreadable `angle` as this).
|
||||
const DEFAULT_ANGLE: f64 = 10.0;
|
||||
|
||||
/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s
|
||||
/// `DOC_KEY`), whose art can carry effects.
|
||||
const BRUSHES_KEY: &str = "brushes";
|
||||
|
||||
/// The angle a Twist effect with `params` draws with, read as `vectorcraft-effects` reads it: a
|
||||
/// number, the number a string starts with, or a boolean as 1 or 0; anything else (or a value
|
||||
/// that is not finite) is [`DEFAULT_ANGLE`].
|
||||
fn angle(params: &Value) -> f64 {
|
||||
let v = match params.get("angle") {
|
||||
Some(Value::Number(n)) => n.as_f64(),
|
||||
Some(Value::String(s)) => {
|
||||
let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect();
|
||||
t.parse().ok()
|
||||
}
|
||||
Some(Value::Bool(b)) => Some(if *b { 1.0 } else { 0.0 }),
|
||||
_ => None,
|
||||
};
|
||||
v.filter(|v| v.is_finite()).unwrap_or(DEFAULT_ANGLE)
|
||||
}
|
||||
|
||||
/// Write the negated angle a Twist effect with `params` draws with into `params`, as a number.
|
||||
fn negate_params(params: &mut Value) {
|
||||
// `0.0 - a` rather than `-a`: an angle of 0 stays 0, not -0.
|
||||
let turned = Value::from(0.0 - angle(params));
|
||||
match params {
|
||||
Value::Object(m) => {
|
||||
m.insert("angle".into(), turned);
|
||||
}
|
||||
p => *p = json!({ "angle": turned }),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_twist(fx: &[Effect]) -> bool {
|
||||
fx.iter().any(|e| e.id == TWIST)
|
||||
}
|
||||
|
||||
fn appearance_has_twist(a: &Appearance) -> bool {
|
||||
has_twist(&a.effects) || a.items.iter().any(|i| has_twist(i.effects()))
|
||||
}
|
||||
|
||||
fn negate_appearance(a: &mut Appearance) {
|
||||
for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
|
||||
if e.id == TWIST {
|
||||
negate_params(&mut e.params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The appearances a Shaper Group's face and edge edits paint with.
|
||||
fn shaper_appearances(n: &Node) -> impl Iterator<Item = &Appearance> {
|
||||
let s = n.extras().shaper.as_deref();
|
||||
let faces = s.into_iter().flat_map(|s| s.faces.iter().filter_map(|f| f.paint.as_ref()));
|
||||
let edges = s.into_iter().flat_map(|s| s.edges.iter().filter_map(|e| e.paint.as_ref()));
|
||||
faces.chain(edges)
|
||||
}
|
||||
|
||||
/// Does `n`'s subtree (opacity-mask art and Shaper edits included) hold a Twist effect?
|
||||
fn node_has_twist(n: &Node) -> bool {
|
||||
appearance_has_twist(&n.appearance)
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| node_has_twist(&m.art))
|
||||
|| shaper_appearances(n).any(appearance_has_twist)
|
||||
|| n.children().is_some_and(|c| c.iter().any(|c| node_has_twist(c)))
|
||||
}
|
||||
|
||||
/// Negate the Twist angles of `a`'s subtree, copying only the nodes on the way to them.
|
||||
fn negate_node(a: &mut Arc<Node>) {
|
||||
if !node_has_twist(a) {
|
||||
return;
|
||||
}
|
||||
let n = Arc::make_mut(a);
|
||||
if appearance_has_twist(&n.appearance) {
|
||||
negate_appearance(&mut n.appearance);
|
||||
}
|
||||
if let Some(x) = n.extras_if_any() {
|
||||
if let Some(m) = x.mask.as_mut() {
|
||||
negate_node(&mut m.art);
|
||||
}
|
||||
if let Some(s) = x.shaper.as_mut() {
|
||||
let faces = s.faces.iter_mut().filter_map(|f| f.paint.as_mut());
|
||||
for p in faces.chain(s.edges.iter_mut().filter_map(|e| e.paint.as_mut())) {
|
||||
negate_appearance(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
negate_node(c);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_twist_json(m: &Map<String, Value>) -> bool {
|
||||
m.get("id").and_then(Value::as_str) == Some(TWIST)
|
||||
}
|
||||
|
||||
/// Does JSON `v` (brush definitions) hold a Twist effect?
|
||||
fn json_has_twist(v: &Value) -> bool {
|
||||
match v {
|
||||
Value::Object(m) => is_twist_json(m) || m.values().any(json_has_twist),
|
||||
Value::Array(a) => a.iter().any(json_has_twist),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Negate the Twist angles in JSON `v`: every object whose `id` is [`TWIST`] is a serialized
|
||||
/// [`Effect`] (object ids are numbers).
|
||||
fn negate_json(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) if is_twist_json(m) => negate_params(m.entry("params").or_insert(Value::Null)),
|
||||
Value::Object(m) => m.values_mut().for_each(negate_json),
|
||||
Value::Array(a) => a.iter_mut().for_each(negate_json),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Negate every Twist angle of a graphic style library: its styles' and its patterns' art.
|
||||
pub(crate) fn negate_library(lib: &mut StyleLibrary) {
|
||||
for g in &mut lib.styles {
|
||||
negate_appearance(&mut g.appearance);
|
||||
}
|
||||
for p in &mut lib.patterns {
|
||||
p.art.iter_mut().for_each(negate_node);
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// A document before version [`TWIST_CLOCKWISE_SINCE`] that holds a Twist effect: when
|
||||
/// `written_clockwise` (asked only then; see [`written_clockwise`]) says the app that saved it
|
||||
/// turned Twist counterclockwise, negate its Twist angles, so it draws as it was saved. A later
|
||||
/// version is left as it is, and the document's version is not changed. It recurses through
|
||||
/// the art, once per level of nesting.
|
||||
pub fn migrate_twist_angles(&mut self, written_clockwise: impl FnOnce() -> bool) {
|
||||
if self.version >= TWIST_CLOCKWISE_SINCE || !self.has_twist() || written_clockwise() {
|
||||
return;
|
||||
}
|
||||
self.negate_twist_angles();
|
||||
}
|
||||
|
||||
/// The reverse of [`Document::migrate_twist_angles`], for saving for an app that turned Twist
|
||||
/// counterclockwise: negate the Twist angles and mark the document version 1. Call it on a
|
||||
/// document whose angles turn clockwise, as every opened or new document's do, whatever
|
||||
/// version another conversion for that save has marked it already.
|
||||
pub fn store_legacy_twist_angles(&mut self) {
|
||||
self.version = TWIST_CLOCKWISE_SINCE - 1;
|
||||
if self.has_twist() {
|
||||
self.negate_twist_angles();
|
||||
}
|
||||
}
|
||||
|
||||
/// Does any Twist effect sit where [`Document::negate_twist_angles`] negates them?
|
||||
fn has_twist(&self) -> bool {
|
||||
let mut roots = self
|
||||
.layers
|
||||
.iter()
|
||||
.chain(self.symbols.iter().map(|s| &s.art))
|
||||
.chain(self.graph_designs.iter().map(|g| &g.art))
|
||||
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
|
||||
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()));
|
||||
roots.any(|r| node_has_twist(r))
|
||||
|| self.graphic_styles.iter().any(|g| appearance_has_twist(&g.appearance))
|
||||
|| self.unknown.get(BRUSHES_KEY).is_some_and(json_has_twist)
|
||||
}
|
||||
|
||||
/// Negate every Twist angle: in the art of the layers, symbols, graph designs, pattern
|
||||
/// swatches and the pattern definition that pattern editing's Cancel puts back (opacity-mask
|
||||
/// art and Shaper edits included), in the graphic styles and in the brush definitions.
|
||||
fn negate_twist_angles(&mut self) {
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
negate_node(root);
|
||||
}
|
||||
if self.graphic_styles.iter().any(|g| appearance_has_twist(&g.appearance)) {
|
||||
for g in self.graphic_styles.iter_mut() {
|
||||
negate_appearance(&mut g.appearance);
|
||||
}
|
||||
}
|
||||
if self.unknown.get(BRUSHES_KEY).is_some_and(json_has_twist)
|
||||
&& let Some(b) = self.unknown.get_mut(BRUSHES_KEY)
|
||||
{
|
||||
negate_json(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,186 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::{Point, Rect, shapes};
|
||||
|
||||
use super::*;
|
||||
use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec};
|
||||
use crate::{GraphicStyle, OpacityMask, PatternDef, Symbol};
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
}
|
||||
|
||||
/// An appearance with a Twist of `params` on the object and on its fill, and a Roughen.
|
||||
fn twisted_appearance(params: &Value) -> Appearance {
|
||||
let mut a = Appearance::default_art();
|
||||
a.effects.push(fx(TWIST, params.clone()));
|
||||
a.effects.push(fx("distort.roughen", json!({"size": 5})));
|
||||
a.items[0].effects_mut().push(fx(TWIST, params.clone()));
|
||||
a
|
||||
}
|
||||
|
||||
fn twisted(d: &mut Document, params: &Value) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), twisted_appearance(params))
|
||||
}
|
||||
|
||||
/// A version 1 document with Twist effects of `params` everywhere one is stored: on a path, in a
|
||||
/// group, in an opacity mask's art, in a Shaper edit, in a symbol, a pattern swatch and a graphic
|
||||
/// style, and `brush` in a brush definition. Its first layer holds the art; its last has no
|
||||
/// Twist.
|
||||
fn document(params: &Value, brush: &Value) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let path = twisted(&mut d, params);
|
||||
d.insert(Some(l), 0, path).unwrap();
|
||||
let inner = twisted(&mut d, params);
|
||||
let group = Node::group(d.alloc_id(), vec![Arc::new(inner)]);
|
||||
d.insert(Some(l), 1, group).unwrap();
|
||||
let mask_art = twisted(&mut d, params);
|
||||
let mut masked = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art());
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, true)));
|
||||
d.insert(Some(l), 2, masked).unwrap();
|
||||
let mut shaper = Node::group(d.alloc_id(), vec![]);
|
||||
let face = FaceEdit {
|
||||
selector: FaceSelector { sources: vec![0], anchor: Point::ZERO },
|
||||
erase: false,
|
||||
erase_edges: false,
|
||||
paint_source: None,
|
||||
merge: None,
|
||||
paint: Some(twisted_appearance(params)),
|
||||
};
|
||||
shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] }));
|
||||
d.insert(Some(l), 3, shaper).unwrap();
|
||||
let art = twisted(&mut d, params);
|
||||
d.symbols.push(Symbol { name: "S".into(), art: Arc::new(art), dynamic: false });
|
||||
let art = twisted(&mut d, params);
|
||||
d.patterns.push(PatternDef::new("P", vec![Arc::new(art)]));
|
||||
d.graphic_styles.push(GraphicStyle::new("G", twisted_appearance(params)));
|
||||
d.unknown.insert(BRUSHES_KEY.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [brush]}}}]));
|
||||
d.add_layer(None);
|
||||
d.version = 1;
|
||||
d
|
||||
}
|
||||
|
||||
/// The angle each Twist effect of the saved document draws with, in the order the JSON lists them.
|
||||
fn angles(d: &Document) -> Vec<f64> {
|
||||
fn walk(v: &Value, out: &mut Vec<f64>) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
if is_twist_json(m) {
|
||||
out.push(angle(m.get("params").unwrap_or(&Value::Null)));
|
||||
}
|
||||
m.values().for_each(|c| walk(c, out));
|
||||
}
|
||||
Value::Array(a) => a.iter().for_each(|c| walk(c, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(&serde_json::to_value(d).unwrap(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_1_document_from_before_0_21_has_its_twist_angles_negated() {
|
||||
let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST}));
|
||||
let before = angles(&d);
|
||||
// Two per path, shaper edit and style; one in the brush.
|
||||
assert_eq!(before.len(), 15, "{before:?}");
|
||||
assert_eq!(before.iter().filter(|&&a| a == DEFAULT_ANGLE).count(), 1, "{before:?}");
|
||||
d.migrate_twist_angles(|| false);
|
||||
assert_eq!(d.version, 1, "the caller sets the version");
|
||||
assert_eq!(angles(&d), before.iter().map(|a| -a).collect::<Vec<_>>());
|
||||
let roughen = serde_json::to_string(&d).unwrap().matches(r#""id":"distort.roughen","params":{"size":5}"#).count();
|
||||
assert_eq!(roughen, 7, "other effects are left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_that_turned_clockwise_is_left_as_it_is() {
|
||||
let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST, "params": {"angle": 30}}));
|
||||
let before = d.clone();
|
||||
d.migrate_twist_angles(|| true);
|
||||
assert_eq!(d, before, "version 1, written by 0.21.0 or later");
|
||||
d.version = 2;
|
||||
let before = d.clone();
|
||||
d.migrate_twist_angles(|| panic!("a version 2 document's writer is not asked about"));
|
||||
assert_eq!(d, before, "version 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_writer_is_asked_about_only_when_a_twist_is_stored() {
|
||||
let mut d = Document::new(10.0, 10.0);
|
||||
d.version = 1;
|
||||
let before = d.clone();
|
||||
d.migrate_twist_angles(|| panic!("a document without a Twist needs no answer"));
|
||||
assert_eq!(d, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angles_are_read_as_the_effect_reads_them() {
|
||||
let read = |params: Value| {
|
||||
let mut e = fx(TWIST, params);
|
||||
negate_params(&mut e.params);
|
||||
e.params
|
||||
};
|
||||
assert_eq!(read(json!({"angle": 30, "x": 1})), json!({"angle": -30.0, "x": 1}));
|
||||
assert_eq!(read(json!({"angle": "45 deg"})), json!({"angle": -45.0}));
|
||||
assert_eq!(read(json!({"angle": true})), json!({"angle": -1.0}));
|
||||
assert_eq!(read(json!({})), json!({"angle": -10.0}));
|
||||
assert_eq!(read(Value::Null), json!({"angle": -10.0}));
|
||||
let zero = read(json!({"angle": 0}));
|
||||
assert!(zero["angle"].as_f64().is_some_and(|a| a == 0.0 && a.is_sign_positive()), "{zero}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_art_holding_a_twist_is_copied() {
|
||||
let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST}));
|
||||
let plain = d.layers.last().cloned().unwrap();
|
||||
let twisted = d.layers[0].clone();
|
||||
d.migrate_twist_angles(|| false);
|
||||
assert!(Arc::ptr_eq(d.layers.last().unwrap(), &plain), "a layer without a Twist is not copied");
|
||||
assert!(!Arc::ptr_eq(&d.layers[0], &twisted));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storing_for_an_earlier_app_and_reading_back_round_trips() {
|
||||
let original = document(&json!({"angle": 30.0}), &json!({"id": TWIST, "params": {"angle": -12.5}}));
|
||||
let mut d = original.clone();
|
||||
d.migrate_twist_angles(|| false);
|
||||
d.version = 2;
|
||||
let current = d.clone();
|
||||
assert_eq!(angles(¤t), angles(&original).iter().map(|a| -a).collect::<Vec<_>>());
|
||||
d.store_legacy_twist_angles();
|
||||
assert_eq!(d, original);
|
||||
d.migrate_twist_angles(|| false);
|
||||
d.version = 2;
|
||||
assert_eq!(d, current);
|
||||
// Another conversion for the same save may have marked the document version 1 already.
|
||||
d.version = 1;
|
||||
d.store_legacy_twist_angles();
|
||||
assert_eq!(d, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_1_style_library_has_its_twist_angles_negated() {
|
||||
let lib = StyleLibrary { name: "L".into(), styles: vec![GraphicStyle::new("G", twisted_appearance(&json!({"angle": 30.0})))], patterns: vec![] };
|
||||
let text = crate::style_libs::write(&lib);
|
||||
assert!(text.contains(r#""version": 2"#), "{text}");
|
||||
assert_eq!(crate::style_libs::read(&text, "x").unwrap(), lib, "a version 2 file reads as written");
|
||||
let old = crate::style_libs::read(&text.replacen(r#""version": 2"#, r#""version": 1"#, 1), "x").unwrap();
|
||||
let fx = &old.styles[0].appearance.effects;
|
||||
assert_eq!(fx[0].params, json!({"angle": -30.0}));
|
||||
assert_eq!(fx[1], lib.styles[0].appearance.effects[1]);
|
||||
assert_eq!(old.styles[0].appearance.items[0].effects()[0].params, json!({"angle": -30.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn releases_from_0_21_turned_twist_clockwise() {
|
||||
for g in ["VectorCraft 0.21.0", "VectorCraft 0.21.4", "VectorCraft 0.22.0-dev", "VectorCraft 1.0.0"] {
|
||||
assert!(written_clockwise(Some(g)), "{g}");
|
||||
}
|
||||
for g in ["VectorCraft 0.20.0", "VectorCraft 0.9.12", "DrawCraft 0.1.0", "VectorCraft", "VectorCraft x.y", "vectorcraft 0.21.0"] {
|
||||
assert!(!written_clockwise(Some(g)), "{g}");
|
||||
}
|
||||
assert!(!written_clockwise(None));
|
||||
}
|
||||
@@ -77,7 +77,7 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, outset, raster_effects};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint,
|
||||
needs_outline, outline_art, outline_text, reshape,
|
||||
|
||||
@@ -366,7 +366,7 @@ pub fn blend_mode(s: &str) -> BlendMode {
|
||||
}
|
||||
|
||||
/// An effect's `color` parameter (`"#rrggbb"`, `[r, g, b]` 0..1 or a colour object).
|
||||
pub(crate) fn color_param(p: &Value, default: Color) -> Color {
|
||||
pub fn color_param(p: &Value, default: Color) -> Color {
|
||||
match p.get("color") {
|
||||
Some(Value::String(s)) => Color::from_hex(s).unwrap_or(default),
|
||||
Some(Value::Array(a)) if a.len() >= 3 => {
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example anchor_bench` prints the wall time of the
|
||||
//! engine steps of editing anchors with Direct Selection, on three synthetic documents: one closed path of
|
||||
//! 50,000 anchors, 2,000 closed paths of 50 anchors each, and one open path of 200,000 anchors.
|
||||
//! `ITERS` sets the runs per step (default 7); each row is the median in ms.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
|
||||
use vectorcraft_engine::{Session, ViewInfo};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, SubPath, Vec2};
|
||||
use vectorcraft_render::{RenderOptions, Renderer};
|
||||
|
||||
/// Anchors are 10 pt apart and their handles 3 pt long, along the path.
|
||||
const STEP: f64 = 10.0;
|
||||
const HANDLE: f64 = 3.0;
|
||||
|
||||
/// A test document: its paths, an anchor to hover, click and drag, a point on a segment, and a
|
||||
/// marquee from an empty point over about 10,000 anchors.
|
||||
struct Shape {
|
||||
name: &'static str,
|
||||
doc: Document,
|
||||
ids: Vec<NodeId>,
|
||||
anchor: (NodeId, usize),
|
||||
segment: Point,
|
||||
marquee: (Point, Point),
|
||||
}
|
||||
|
||||
/// A closed path of `n` smooth anchors around `center`.
|
||||
fn circle(center: Point, n: usize) -> PathData {
|
||||
let r = n as f64 * STEP / std::f64::consts::TAU;
|
||||
let anchors = (0..n)
|
||||
.map(|i| {
|
||||
let t = i as f64 / n as f64 * std::f64::consts::TAU;
|
||||
let p = center + Vec2::new(r * t.cos(), r * t.sin());
|
||||
Anchor::smooth(p, p + Vec2::new(-t.sin(), t.cos()) * HANDLE)
|
||||
})
|
||||
.collect();
|
||||
PathData::single(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
fn add(doc: &mut Document, path: PathData) -> NodeId {
|
||||
let l = doc.layers.first().map(|l| l.id);
|
||||
let id = doc.alloc_id();
|
||||
doc.insert(l, usize::MAX, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn one_outline() -> Shape {
|
||||
let n = 50_000;
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let id = add(&mut doc, circle(Point::ZERO, n));
|
||||
let r = n as f64 * STEP / std::f64::consts::TAU;
|
||||
let a = 72f64.to_radians();
|
||||
let mid = (n / 2) as f64 / n as f64 * std::f64::consts::TAU;
|
||||
let next = (n / 2 + 1) as f64 / n as f64 * std::f64::consts::TAU;
|
||||
let segment = Point::new(r * (mid.cos() + next.cos()) / 2.0, r * (mid.sin() + next.sin()) / 2.0);
|
||||
Shape {
|
||||
name: "one closed path, 50,000 anchors",
|
||||
doc,
|
||||
ids: vec![id],
|
||||
anchor: (id, n / 2),
|
||||
segment,
|
||||
marquee: (Point::new(r + 50.0, -5.0), Point::new(r * a.cos() - 1.0, r * a.sin() + 1.0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn many_paths() -> Shape {
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let ids: Vec<NodeId> =
|
||||
(0..2000).map(|i| add(&mut doc, circle(Point::new((i % 50) as f64 * 200.0 + 100.0, (i / 50) as f64 * 200.0 + 100.0), 50))).collect();
|
||||
let r = 50.0 * STEP / std::f64::consts::TAU;
|
||||
// Path 1,025 (row 20, column 25), its anchors 0 and 1.
|
||||
let c = Point::new(25.0 * 200.0 + 100.0, 20.0 * 200.0 + 100.0);
|
||||
let t = std::f64::consts::TAU / 50.0;
|
||||
let segment = c + Vec2::new(r * (1.0 + t.cos()) / 2.0, r * t.sin() / 2.0);
|
||||
Shape {
|
||||
name: "2,000 closed paths, 50 anchors each",
|
||||
doc,
|
||||
anchor: (ids[1025], 0),
|
||||
ids,
|
||||
segment,
|
||||
marquee: (Point::ZERO, Point::new(10_000.0, 800.0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn long_open_path() -> Shape {
|
||||
let n = 200_000;
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let anchors = (0..n)
|
||||
.map(|i| {
|
||||
let p = Point::new(i as f64 * STEP, 0.0);
|
||||
Anchor::smooth(p, p + Vec2::new(HANDLE, 0.0))
|
||||
})
|
||||
.collect();
|
||||
let id = add(&mut doc, PathData::single(SubPath::new(anchors, false)));
|
||||
Shape {
|
||||
name: "one open path, 200,000 anchors",
|
||||
doc,
|
||||
ids: vec![id],
|
||||
anchor: (id, n / 2),
|
||||
segment: Point::new((n / 2) as f64 * STEP + STEP / 2.0, 0.0),
|
||||
marquee: (Point::new(-5.0, -20.0), Point::new(99_995.0, 30.0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
fn median(mut ms: Vec<f64>) -> f64 {
|
||||
ms.sort_by(f64::total_cmp);
|
||||
ms[ms.len() / 2]
|
||||
}
|
||||
|
||||
fn time(mut f: impl FnMut()) -> f64 {
|
||||
median(
|
||||
(0..iters())
|
||||
.map(|_| {
|
||||
let t = Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn ev(kind: PointerKind, p: Point) -> PointerEvent {
|
||||
PointerEvent::new(kind, p.x, p.y)
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, cmd: &str, p: Value) {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
|
||||
}
|
||||
|
||||
fn anchor_at(s: &Session, (id, ai): (NodeId, usize)) -> Anchor {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[ai]
|
||||
}
|
||||
|
||||
/// The anchors selected: those direct-selected, and every anchor of a path selected whole.
|
||||
fn selected_anchors(s: &Session) -> usize {
|
||||
let st = s.doc().unwrap();
|
||||
let count = |id: &NodeId| st.doc.node(*id).and_then(|n| n.path_data()).map_or(0, |pd| pd.anchors().count());
|
||||
st.selection.objects.iter().map(|id| st.selection.partial(*id).map_or_else(|| count(id), |set| set.len())).sum()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<58} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
/// Select `count` anchors: the first ones of the first path, or the first anchors of as many
|
||||
/// paths as needed.
|
||||
fn select_count(s: &mut Session, shape: &Shape, count: usize) {
|
||||
exec(s, "select.none", json!({}));
|
||||
let mut left = count;
|
||||
for id in &shape.ids {
|
||||
if left == 0 {
|
||||
break;
|
||||
}
|
||||
let n = s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len();
|
||||
let take = left.min(n);
|
||||
let refs: Vec<[usize; 2]> = (0..take).map(|i| [0, i]).collect();
|
||||
exec(s, "select.anchors", json!({"id": id.0, "anchors": refs, "mode": "add"}));
|
||||
left -= take;
|
||||
}
|
||||
}
|
||||
|
||||
fn bench(shape: Shape) {
|
||||
println!("{}", shape.name);
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
let mut s = Session::new();
|
||||
s.add_document(shape.doc.clone(), None);
|
||||
s.select_tool("directSelection", view).unwrap();
|
||||
let a = anchor_at(&s, shape.anchor).p;
|
||||
let none = Mods::default();
|
||||
{
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let opt = vectorcraft_doc::hit::HitOptions { tol: 3.0, clip_outlines: true, ..Default::default() };
|
||||
row("hit test at an anchor", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, a, opt)))));
|
||||
row("hit test at a segment", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment, opt)))));
|
||||
row("hit test beside the path", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment + Vec2::new(0.0, 40.0), opt)))));
|
||||
}
|
||||
|
||||
// Hover with nothing selected, then with one anchor of the path selected.
|
||||
for selected in [false, true] {
|
||||
if selected {
|
||||
exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"}));
|
||||
}
|
||||
let what = if selected { "one anchor selected" } else { "nothing selected" };
|
||||
row(&format!("hover over an anchor, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, a), view).unwrap())));
|
||||
row(&format!("cursor over an anchor, {what}"), time(|| _ = black_box(s.cursor(a, none, view))));
|
||||
row(&format!("hover over a segment, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, shape.segment), view).unwrap())));
|
||||
row(&format!("cursor over a segment, {what}"), time(|| _ = black_box(s.cursor(shape.segment, none, view))));
|
||||
}
|
||||
|
||||
// A click that selects one anchor.
|
||||
exec(&mut s, "select.none", json!({}));
|
||||
row(
|
||||
"click that selects one anchor",
|
||||
time(|| {
|
||||
s.pointer(&ev(PointerKind::Down, a), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, a), view).unwrap();
|
||||
}),
|
||||
);
|
||||
assert_eq!(selected_anchors(&s), 1, "the click selects one anchor");
|
||||
|
||||
// One anchor dragged: each pointer move, then the release.
|
||||
let undo = undo_len(&s);
|
||||
s.pointer(&ev(PointerKind::Down, a), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, 20.0)), view).unwrap();
|
||||
let mut y = 20.0;
|
||||
row(
|
||||
"anchor drag, one pointer move",
|
||||
time(|| {
|
||||
y += 1.0;
|
||||
s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, y)), view).unwrap();
|
||||
}),
|
||||
);
|
||||
let t = Instant::now();
|
||||
s.pointer(&ev(PointerKind::Up, a + Vec2::new(0.0, y)), view).unwrap();
|
||||
row("anchor drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0);
|
||||
assert_eq!(undo_len(&s), undo + 1, "the anchor drag records one step");
|
||||
exec(&mut s, "edit.undo", json!({}));
|
||||
|
||||
// The selected anchor's outgoing handle dragged.
|
||||
exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"}));
|
||||
let h = anchor_at(&s, shape.anchor).h_out;
|
||||
let undo = undo_len(&s);
|
||||
s.pointer(&ev(PointerKind::Down, h), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, 20.0)), view).unwrap();
|
||||
let mut y = 20.0;
|
||||
row(
|
||||
"handle drag, one pointer move",
|
||||
time(|| {
|
||||
y += 1.0;
|
||||
s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, y)), view).unwrap();
|
||||
}),
|
||||
);
|
||||
let t = Instant::now();
|
||||
s.pointer(&ev(PointerKind::Up, h + Vec2::new(0.0, y)), view).unwrap();
|
||||
row("handle drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0);
|
||||
assert_eq!(undo_len(&s), undo + 1, "the handle drag records one step");
|
||||
assert_eq!(anchor_at(&s, shape.anchor).p, a, "the handle drag leaves the anchor in place");
|
||||
exec(&mut s, "edit.undo", json!({}));
|
||||
|
||||
// A marquee over about 10,000 anchors.
|
||||
let (m0, m1) = shape.marquee;
|
||||
let ms = time(|| {
|
||||
exec(&mut s, "select.none", json!({}));
|
||||
s.pointer(&ev(PointerKind::Down, m0), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, m0.lerp(m1, 0.5)), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, m1), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, m1), view).unwrap();
|
||||
});
|
||||
row(&format!("marquee over {} anchors (press to release)", selected_anchors(&s)), ms);
|
||||
|
||||
// Select All with Direct Selection.
|
||||
row("Select All", time(|| exec(&mut s, "select.all", json!({}))));
|
||||
row("tool overlays, everything selected", time(|| drop(s.overlays(view))));
|
||||
|
||||
// Nudges of 1, 1,000 and every anchor, and Undo and Redo of each.
|
||||
let total: usize = shape.ids.iter().map(|id| s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len()).sum();
|
||||
for count in [1, 1000, total] {
|
||||
select_count(&mut s, &shape, count);
|
||||
row(&format!("nudge of {count} anchors"), time(|| exec(&mut s, "path.moveAnchors", json!({"dx": 1, "dy": 0}))));
|
||||
row(&format!("undo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.undo", json!({}))));
|
||||
row(&format!("redo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.redo", json!({}))));
|
||||
}
|
||||
|
||||
// The render of the document after one anchor moves (the renderer warm).
|
||||
exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"}));
|
||||
let opts = RenderOptions::default();
|
||||
let mut r = Renderer::new();
|
||||
let at = Affine::translate(Vec2::new(800.0 - a.x, 600.0 - a.y));
|
||||
r.render(&s.doc().unwrap().doc, 1600, 1200, at, &opts);
|
||||
let ms = median(
|
||||
(0..iters())
|
||||
.map(|_| {
|
||||
exec(&mut s, "path.moveAnchors", json!({"dx": 0, "dy": 1}));
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let t = Instant::now();
|
||||
drop(r.render(&doc, 1600, 1200, at, &opts));
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
row("render 1600x1200 around the anchor after it moves", ms);
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
row("render 1600x1200 around the anchor, nothing changed", time(|| drop(r.render(&doc, 1600, 1200, at, &opts))));
|
||||
|
||||
// Delete of one anchor, undone after each run.
|
||||
let ms = median(
|
||||
(0..iters())
|
||||
.map(|_| {
|
||||
exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"}));
|
||||
let t = Instant::now();
|
||||
exec(&mut s, "edit.clear", json!({}));
|
||||
let ms = t.elapsed().as_secs_f64() * 1000.0;
|
||||
exec(&mut s, "edit.undo", json!({}));
|
||||
ms
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
row("Delete of one anchor", ms);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
bench(one_outline());
|
||||
bench(many_paths());
|
||||
bench(long_open_path());
|
||||
}
|
||||
@@ -168,9 +168,9 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }
|
||||
}
|
||||
/// Objects are selected, or the Artboard tool is chosen (Copy and Cut take its artboard).
|
||||
pub fn has_selection_or_artboard_tool(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.tool_id() == "artboard" { has_doc(s) } else { has_selection(s) }
|
||||
/// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take).
|
||||
pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) }
|
||||
}
|
||||
/// Objects or ruler guides are selected (what Delete and the arrow keys act on).
|
||||
pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> {
|
||||
@@ -484,9 +484,10 @@ pub fn matrix_param(p: &Value, key: &str) -> Option<Affine> {
|
||||
}
|
||||
/// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1),
|
||||
/// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about
|
||||
/// −128..127).
|
||||
/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`).
|
||||
pub fn color_value(v: &Value) -> Option<Color> {
|
||||
match v {
|
||||
Value::String(s) if hex_with_alpha(s) => None,
|
||||
// A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours).
|
||||
Value::String(s) => Color::from_hex(s).or_else(|| vectorcraft_color::recolor::ColorKey::parse(s).map(|k| k.color())),
|
||||
Value::Array(a) if a.len() >= 3 => Some(Color::rgb(a[0].as_f64()? as f32, a[1].as_f64()? as f32, a[2].as_f64()? as f32)),
|
||||
@@ -512,6 +513,23 @@ pub fn color_value(v: &Value) -> Option<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `s` a hex color with an alpha part: eight or four hex digits, with or without the `#`?
|
||||
/// [`Color::from_hex`] reads `#rrggbbaa` as `#rrggbb`, without the alpha.
|
||||
pub(crate) fn hex_with_alpha(s: &str) -> bool {
|
||||
let s = s.trim();
|
||||
let h = s.strip_prefix('#').unwrap_or(s);
|
||||
matches!(h.len(), 4 | 8) && h.chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// The color `p` gives for `key`, read by [`color_value`]: `None` when `p` leaves it out or gives
|
||||
/// null. Any other value that is not a color is an error: "bad color {v}".
|
||||
pub(crate) fn color_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Color>> {
|
||||
match p.get(key).filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(v) => color_value(v).map(Some).ok_or_else(|| bad(cmd, format!("bad color {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` as an object id: an error unless it is a non-negative integer.
|
||||
fn object_id(v: &Value) -> Result<NodeId> {
|
||||
v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}")))
|
||||
|
||||
@@ -7,6 +7,7 @@ mod color;
|
||||
mod document;
|
||||
mod pathtools;
|
||||
mod pen;
|
||||
mod select;
|
||||
mod typetools;
|
||||
|
||||
use super::CommandSpec;
|
||||
@@ -19,6 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(document::specs());
|
||||
v.extend(pathtools::specs());
|
||||
v.extend(pen::specs());
|
||||
v.extend(select::specs());
|
||||
v.extend(typetools::specs());
|
||||
v
|
||||
}
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Find Nearest Swatch",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}",
|
||||
"{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up, #rrggbbaa and #rgba refused; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}",
|
||||
has_doc,
|
||||
nearest::find
|
||||
),
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of
|
||||
//! the document named with the date and time through File › Save a Copy's save; New Symbols from
|
||||
//! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a
|
||||
//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins ›
|
||||
//! Document Tools) is the UI's.
|
||||
//! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces
|
||||
//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu
|
||||
//! (Object › Plug-ins › Document Tools) is the UI's.
|
||||
|
||||
mod batch_trace;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -14,7 +16,7 @@ use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration};
|
||||
|
||||
use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol};
|
||||
use super::super::fileio::{self, SaveMode};
|
||||
use super::super::{CommandSpec, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or};
|
||||
use super::super::{CommandSpec, always, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken.
|
||||
@@ -40,6 +42,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
export_all_open
|
||||
),
|
||||
cmd!(
|
||||
"addon.document.batchTraceFolder",
|
||||
"Batch Trace Folder",
|
||||
["Object", "Plug-ins", "Document Tools"],
|
||||
None,
|
||||
"{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as <name>.<ext> (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)",
|
||||
always,
|
||||
batch_trace::batch_trace_folder
|
||||
),
|
||||
cmd!(
|
||||
"addon.document.symbolsFromLayers",
|
||||
"New Symbols from Layers",
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Batch Trace Folder (`addon.document.batchTraceFolder`, #4921): each image in a folder is opened,
|
||||
//! traced with a preset (and expanded when asked), saved into a destination folder under its own
|
||||
//! name, and closed again, whether it traced or not.
|
||||
|
||||
use serde_json::Value;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use serde_json::json;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::super::super::fileio;
|
||||
use super::super::super::{Result, Session, bad};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::super::super::{bool_or, str_param};
|
||||
|
||||
/// The command id.
|
||||
pub(super) const ID: &str = "addon.document.batchTraceFolder";
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) fn batch_trace_folder(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad(ID, "no file system here"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The image files a batch traces, by extension.
|
||||
const IMAGE_EXTS: [&str; 10] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif", "webp", "psd", "psb"];
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// Caps on a batch (folders and MCP payloads are untrusted).
|
||||
pub(super) const MAX_FILES: usize = 500;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_DEPTH: usize = 8;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const FORMATS: [&str; 5] = ["vectorcraft", "svg", "pdf", "ai", "eps"];
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The image files in `folder` (and its subfolders with `deep`), sorted.
|
||||
fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec<String>) -> Result<()> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(bad(ID, format!("folders deeper than {MAX_DEPTH} levels")));
|
||||
}
|
||||
let max = MAX_FILES.saturating_mul(2);
|
||||
let (entries, truncated) = fileio::list_dir(folder, max)?;
|
||||
// The listing is cut before it is sorted, so a cut one could skip any image: refuse it.
|
||||
if truncated {
|
||||
return Err(bad(ID, format!("{folder}: more than {max} files and folders")));
|
||||
}
|
||||
let mut subdirs = vec![];
|
||||
for e in entries {
|
||||
let name = e.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
if name.is_empty() || name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let path = std::path::Path::new(folder).join(name).to_string_lossy().into_owned();
|
||||
match e.get("kind").and_then(Value::as_str) {
|
||||
Some("file") if IMAGE_EXTS.contains(&fileio::extension(&path).as_str()) => out.push(path),
|
||||
Some("folder") if deep => subdirs.push(path),
|
||||
_ => {}
|
||||
}
|
||||
if out.len() > MAX_FILES {
|
||||
return Err(bad(ID, format!("more than {MAX_FILES} images")));
|
||||
}
|
||||
}
|
||||
for d in subdirs {
|
||||
images(&d, deep, depth + 1, out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?;
|
||||
let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?;
|
||||
let format = str_param(p, "format").unwrap_or("vectorcraft");
|
||||
if !FORMATS.contains(&format) {
|
||||
return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", "))));
|
||||
}
|
||||
let preset = str_param(p, "preset").unwrap_or("Default").to_string();
|
||||
let presets = s.execute("imageTrace.presets", &json!({}))?;
|
||||
if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) {
|
||||
return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)")));
|
||||
}
|
||||
let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
fileio::may_read(&folder)?;
|
||||
fileio::may_write(&dest)?;
|
||||
let mut files = vec![];
|
||||
images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?;
|
||||
files.sort();
|
||||
if files.is_empty() {
|
||||
return Err(bad(ID, "no images in the folder"));
|
||||
}
|
||||
std::fs::create_dir_all(&dest).map_err(|e| bad(ID, format!("{dest}: {e}")))?;
|
||||
let ext = fileio::save_format(Some(format), None).map_err(|e| bad(ID, e))?.extensions.first().copied().unwrap_or(format);
|
||||
let active = s.active_index();
|
||||
let (mut traced, mut failed, mut taken) = (vec![], vec![], Vec::<String>::new());
|
||||
for path in &files {
|
||||
let opened_before = s.documents().len();
|
||||
let one = |s: &mut Session| -> Result<String> {
|
||||
s.execute("document.open", &json!({ "path": path }))?;
|
||||
s.execute("select.all", &json!({}))?;
|
||||
s.execute(trace, &json!({ "preset": preset }))?;
|
||||
let stem = fileio::file_stem(path);
|
||||
// Names this batch already took count as taken, as do files on disk.
|
||||
let free = super::free_name(&dest, &stem, ext, |o| taken.iter().any(|t| t == o) || std::path::Path::new(o).exists())
|
||||
.ok_or_else(|| bad(ID, "every numbered name for the result is taken"))?;
|
||||
s.execute("document.save", &json!({ "path": free, "format": format }))?;
|
||||
Ok(free)
|
||||
};
|
||||
let result = one(s);
|
||||
// The image's document closes whatever happened, so a failure leaves no tab behind.
|
||||
if s.documents().len() > opened_before
|
||||
&& let Some(i) = s.active_index()
|
||||
{
|
||||
// A just-opened image has no work to lose; if closing fails, one extra tab stays open.
|
||||
let _ = s.execute("file.close", &json!({ "index": i }));
|
||||
}
|
||||
match result {
|
||||
Ok(out) => {
|
||||
taken.push(out.clone());
|
||||
traced.push(json!({ "path": path, "output": out }));
|
||||
}
|
||||
Err(e) => failed.push(json!({ "path": path, "error": e.to_string() })),
|
||||
}
|
||||
}
|
||||
if let Some(i) = active.filter(|i| *i < s.documents().len()) {
|
||||
s.set_active(i);
|
||||
}
|
||||
Ok(json!({ "traced": traced, "failed": failed, "format": format }))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Document Tools' commands: the timestamped copy's name and place with the document left as it
|
||||
//! was, symbols made of layers, and bad params refused.
|
||||
//! was, symbols made of layers, a folder of images traced, and bad params refused.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -276,3 +276,77 @@ fn export_all_open_documents_keeps_every_page_and_artboard() {
|
||||
assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A 24×24 white PNG with a dark (or red) square in it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn png(path: &Path, dark: bool) {
|
||||
let mut img = image::RgbaImage::from_pixel(24, 24, image::Rgba([255, 255, 255, 255]));
|
||||
for y in 6..18 {
|
||||
for x in 6..18 {
|
||||
img.put_pixel(x, y, if dark { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([200, 30, 30, 255]) });
|
||||
}
|
||||
}
|
||||
img.save(path).unwrap();
|
||||
}
|
||||
|
||||
/// #4921: each image of the folder is traced and saved under its own name; a file that isn't an
|
||||
/// image is left alone, one that can't be read is reported, and every document the batch opened
|
||||
/// is closed again, the active one staying active.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn batch_trace_folder_traces_and_saves_each_image() {
|
||||
const C: &str = "addon.document.batchTraceFolder";
|
||||
let dir = folder("batch-trace");
|
||||
let (src, out) = (dir.join("in"), dir.join("out"));
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
png(&src.join("logo.png"), true);
|
||||
png(&src.join("mark.png"), false);
|
||||
std::fs::write(src.join("notes.txt"), "not an image").unwrap();
|
||||
std::fs::write(src.join("broken.png"), b"not a png").unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let docs = s.documents().len();
|
||||
let r = s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "expand": true})).unwrap();
|
||||
assert_eq!(r["traced"].as_array().unwrap().len(), 2, "{r}");
|
||||
assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}");
|
||||
assert!(r["failed"][0]["path"].as_str().unwrap().ends_with("broken.png"));
|
||||
let mut names: Vec<String> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["logo.svg", "mark.svg"]);
|
||||
let svg = std::fs::read_to_string(out.join("logo.svg")).unwrap();
|
||||
assert!(svg.contains("<path") && !svg.contains("<image"), "traced and expanded, not the image");
|
||||
assert_eq!(s.documents().len(), docs, "the opened images are closed");
|
||||
assert_eq!(s.active_index(), Some(0));
|
||||
// Again: the taken names are numbered, nothing is replaced.
|
||||
s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg"})).unwrap();
|
||||
assert!(out.join("logo-2.svg").exists() && out.join("mark-2.svg").exists());
|
||||
// Refused: no folders, an unknown preset or format, a folder without images.
|
||||
for bad in [
|
||||
json!({"destinationFolder": out}),
|
||||
json!({"folder": src}),
|
||||
json!({"folder": src, "destinationFolder": out, "preset": "No Such Preset"}),
|
||||
json!({"folder": src, "destinationFolder": out, "format": "docx"}),
|
||||
json!({"folder": out.join("empty"), "destinationFolder": out}),
|
||||
] {
|
||||
assert!(s.execute(C, &bad).is_err(), "{bad}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A folder too big to list in full is refused rather than traced in part.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn batch_trace_folder_refuses_a_folder_it_cannot_list_in_full() {
|
||||
let dir = folder("batch-trace-big");
|
||||
let src = dir.join("in");
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
for i in 0..=super::batch_trace::MAX_FILES * 2 {
|
||||
std::fs::write(src.join(format!("note-{i}.txt")), "").unwrap();
|
||||
}
|
||||
png(&src.join("logo.png"), true);
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("addon.document.batchTraceFolder", &json!({"folder": src, "destinationFolder": dir.join("out")})).unwrap_err();
|
||||
assert!(e.to_string().contains("more than"), "{e}");
|
||||
assert!(!dir.join("out").exists(), "nothing traced");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects
|
||||
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu
|
||||
//! (Object › Plug-ins › Selection Tools) and dialog are the UI's.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::super::select::{on_artboard, selectable};
|
||||
use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
|
||||
pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.select.byArtboards",
|
||||
"Select by Artboards",
|
||||
["Object", "Plug-ins", "Selection Tools"],
|
||||
None,
|
||||
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
|
||||
has_doc,
|
||||
by_artboards
|
||||
)]
|
||||
}
|
||||
|
||||
fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.select.byArtboards";
|
||||
let relation = text_param(p, "relation", C)?.unwrap_or("overlap");
|
||||
if !RELATIONS.contains(&relation) {
|
||||
return Err(bad(C, "`relation` must be overlap, inside or outside"));
|
||||
}
|
||||
let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?;
|
||||
let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?;
|
||||
if indices.is_empty() {
|
||||
return Err(bad(C, "choose at least one artboard"));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let rects =
|
||||
indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::<Option<Vec<_>>>().ok_or_else(|| bad(C, "no such artboard"))?;
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
let Some(n) = st.doc.node(*id) else { return false };
|
||||
match relation {
|
||||
"inside" => n.geometric_bounds_with(&symbols).is_some_and(|b| {
|
||||
rects.iter().any(|r| {
|
||||
vectorcraft_doc::artboard_holds(*r, Point::new(b.x0, b.y0)) && vectorcraft_doc::artboard_holds(*r, Point::new(b.x1, b.y1))
|
||||
})
|
||||
}),
|
||||
"outside" => !rects.iter().any(|r| on_artboard(n, &symbols, *r)),
|
||||
_ => rects.iter().any(|r| on_artboard(n, &symbols, *r)),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Select by Artboards.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = "addon.select.byArtboards";
|
||||
|
||||
/// A document with three 100 × 100 artboards in a row, 50 pt apart: 0 at x 0, 1 at x 150, 2 at x 300.
|
||||
fn three_boards() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
for x in [150, 300] {
|
||||
s.execute("artboard.new", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn pick(s: &mut Session, p: Value) -> Vec<NodeId> {
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = s.execute(C, &p).unwrap();
|
||||
let mut ids = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(r["count"], json!(ids.len()));
|
||||
ids.sort();
|
||||
ids
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_by_overlap_inside_and_outside_several_artboards() {
|
||||
let mut s = three_boards();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); // inside 0
|
||||
let ab = rect(&mut s, 90.0, 40.0, 80.0, 20.0); // across 0 and 1
|
||||
let b = rect(&mut s, 160.0, 10.0, 20.0, 20.0); // inside 1
|
||||
let c = rect(&mut s, 310.0, 10.0, 20.0, 20.0); // inside 2
|
||||
let off = rect(&mut s, 0.0, 200.0, 20.0, 20.0); // on no board
|
||||
let edge = rect(&mut s, 0.0, 0.0, 100.0, 100.0); // flush with board 0
|
||||
let want = |mut v: Vec<NodeId>| {
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 1]})), want(vec![a, ab, b, edge]));
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "overlap"})), want(vec![a, ab, b, edge]));
|
||||
// Wholly within one board, edges included; straddling two boards is not inside either.
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "inside"})), want(vec![a, b, edge]));
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0, 1], "relation": "outside"})), want(vec![c, off]));
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [2], "relation": "outside"})), want(vec![a, ab, b, off, edge]));
|
||||
// One board does what All on Active Artboard does.
|
||||
for i in 0..3u64 {
|
||||
s.execute("select.allOnArtboard", &json!({"artboard": i})).unwrap();
|
||||
let mut on = s.doc().unwrap().selection.objects.clone();
|
||||
on.sort();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [i]})), on, "board {i}");
|
||||
}
|
||||
// A board listed twice counts once.
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [2, 2]})), vec![c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_locked_and_isolated_art_follow_select_all() {
|
||||
let mut s = three_boards();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let hidden = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
let locked = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
|
||||
let far = rect(&mut s, 0.0, 300.0, 20.0, 20.0);
|
||||
s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![a]);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![far]);
|
||||
// Art held by a locked artboard is left out.
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![]);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
|
||||
// In isolation mode only the isolated group's objects are looked at.
|
||||
let b = rect(&mut s, 20.0, 50.0, 10.0, 10.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("object.isolate", &json!({"id": g})).unwrap();
|
||||
let mut both = vec![a, b];
|
||||
both.sort();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), both);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [1]})), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_errors_and_leave_the_selection() {
|
||||
let mut s = three_boards();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"artboards": []}),
|
||||
json!({"artboards": [3]}),
|
||||
json!({"artboards": [-1]}),
|
||||
json!({"artboards": [0.5]}),
|
||||
json!({"artboards": "0"}),
|
||||
json!({"artboards": [0], "relation": "near"}),
|
||||
json!({"artboards": [0], "relation": 1}),
|
||||
json!({"artboards": [0], "relatoin": "inside"}),
|
||||
] {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert!(s.execute(C, &p).is_err(), "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symbol_instance_is_measured_by_its_art() {
|
||||
// The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on
|
||||
// the 200 × 120 artboard, while the 20 × 20 square around the instance's origin lies off it.
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120"><defs><symbol id="Far"><rect x="100" y="60" width="40" height="20" fill="#f00"/></symbol></defs><use href="#Far" x="-50" y="-50"/></svg>"##;
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "far.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap();
|
||||
let mut instance = None;
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }) {
|
||||
instance = Some(n.id);
|
||||
}
|
||||
});
|
||||
let instance = instance.unwrap();
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0]})), vec![instance]);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]);
|
||||
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]);
|
||||
}
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Text Tweaker",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
|
||||
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
|
||||
has_selection,
|
||||
text_tweaker
|
||||
)]
|
||||
@@ -97,6 +97,7 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (id, a, b, _) in ranges {
|
||||
let t = text_ref(s, id)?;
|
||||
let text = t.plain_text();
|
||||
let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b));
|
||||
let chars: Vec<usize> =
|
||||
text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect();
|
||||
seen += chars.len();
|
||||
|
||||
@@ -124,6 +124,16 @@ fn a_range_changes_only_its_characters() {
|
||||
assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_inside_a_multibyte_character_uses_character_boundaries() {
|
||||
let mut s = session();
|
||||
let id = text(&mut s, "éx");
|
||||
let out = s.execute(C, &json!({"id": id.0, "start": 1, "end": 2, "attribute": "tracking", "from": 100, "to": 300})).unwrap();
|
||||
assert_eq!(out["count"], 1);
|
||||
let tracking: Vec<f64> = styles(&s, id).iter().map(|(_, st)| st.tracking).collect();
|
||||
assert_eq!(tracking, [100.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_values_stay_in_range_and_repeat_with_the_seed() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill is a copy of that row, right above it, and becomes the active row",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row (a copy of its top stroke, else the default stroke)",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -357,11 +357,23 @@ pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId])
|
||||
|
||||
/// Indices `idx` of the first target's items (aligned with `aligned`) in each of `ids`: the first
|
||||
/// target's own, and in each other one the items equal to them there (see [`SharedStack`]), each
|
||||
/// index on its own: one the targets don't share is left out of the others (never taken as the
|
||||
/// same index there). Not aligned, or one target: the same indices in each.
|
||||
/// index and each target on its own: an index a target doesn't share with the first is left out
|
||||
/// of that target (never taken as the same index there), whatever the other targets have. Not
|
||||
/// aligned, or one target: the same indices in each.
|
||||
pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec<Vec<usize>> {
|
||||
match shared_stack(d, ids).filter(|_| aligned) {
|
||||
Some(sh) => (0..ids.len()).map(|k| if k == 0 { idx.to_vec() } else { idx.iter().filter_map(|i| sh.item_in(*i, k)).collect() }).collect(),
|
||||
let aps: Option<Vec<&Appearance>> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect();
|
||||
match aps.filter(|aps| aligned && aps.len() >= 2) {
|
||||
Some(aps) => aps
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, ap)| match aps.first() {
|
||||
Some(first) if k > 0 => {
|
||||
let sh = SharedStack::of(&[*first, *ap]);
|
||||
idx.iter().filter_map(|i| sh.item_in(*i, 1)).collect()
|
||||
}
|
||||
_ => idx.to_vec(),
|
||||
})
|
||||
.collect(),
|
||||
None => vec![idx.to_vec(); ids.len()],
|
||||
}
|
||||
}
|
||||
@@ -507,8 +519,8 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
|
||||
let defaults = s.paint.clone();
|
||||
// The panel's active Fill row, when the new fill goes on the selection: the new fill is a copy
|
||||
// of that row, right above it in each target that has it (others get a copy of their top fill).
|
||||
// The panel's active Fill row, when the new fill goes on the selection: the new fill takes that
|
||||
// row's paint, right above it in each target that has it (others take their top fill's paint).
|
||||
// Where the new item went in on the active item's object, when it is an image.
|
||||
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
|
||||
// The active row is a row of the active object's stack, which need not come first in `ids`
|
||||
@@ -547,8 +559,9 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A copy of the top fill (stroke); without one, type's characters' and otherwise the
|
||||
// default paint, so a new fill on a group or type shows.
|
||||
// The top fill's (stroke's) paint; without one, type's characters' and otherwise the
|
||||
// default paint, so a new fill on a group or type shows. A new stroke takes the top
|
||||
// stroke's weight when that stroke has paint, at least 1 pt.
|
||||
let paint = match (n.appearance.paint_at(None, fill), &n.kind) {
|
||||
(Some(p), _) => p.clone(),
|
||||
(None, NodeKind::Text(_)) => super::paint::proxy_paint(n, !fill, None),
|
||||
|
||||
@@ -19,7 +19,7 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::pathops::{remove_each, separate};
|
||||
use super::swatch::{anchor, names_param};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_value, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok,
|
||||
str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
@@ -304,7 +304,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbolism Tool",
|
||||
[],
|
||||
None,
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color?, keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}",
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}",
|
||||
has_doc,
|
||||
symbol_adjust
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::dynamic::{fit_overrides, type_id, type_param};
|
||||
use super::{
|
||||
Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result,
|
||||
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json,
|
||||
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json,
|
||||
name_param, number_or, ok, remove_each, roots, selection_art, separate, set_unknown, str_param, switch_or,
|
||||
};
|
||||
|
||||
@@ -834,7 +834,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0;
|
||||
let alt = switch_or(p, "alt", false, C)?;
|
||||
let st = s.doc()?;
|
||||
let color = match p.get("color").and_then(color_value) {
|
||||
let color = match color_param(p, "color", C)? {
|
||||
Some(c) => crate::cmd::paint::new_color(s, p, c),
|
||||
None => s.paint.fill.color().unwrap_or(Color::BLACK),
|
||||
};
|
||||
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gap Options",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
|
||||
"{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}",
|
||||
has_selection_or_ids,
|
||||
lp_gap_options
|
||||
),
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket",
|
||||
[],
|
||||
None,
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
|
||||
has_doc,
|
||||
lp_fill
|
||||
),
|
||||
|
||||
@@ -93,11 +93,28 @@ pub struct Clipboard {
|
||||
/// The artboards copied with the Artboard tool (`artboard.copy`); `nodes` are then their art.
|
||||
/// Pasting adds a copy of each with the art.
|
||||
pub artboards: Vec<vectorcraft_doc::Artboard>,
|
||||
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
|
||||
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
|
||||
pub guides: Vec<vectorcraft_doc::Guide>,
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty() && self.artboards.is_empty()
|
||||
self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty()
|
||||
}
|
||||
|
||||
/// Does it hold art (objects or artboards) for other apps? Ruler guides stay in VectorCraft:
|
||||
/// a Copy of guides alone empties the system clipboard (#3226).
|
||||
pub fn has_art(&self) -> bool {
|
||||
!self.nodes.is_empty() || !self.artboards.is_empty()
|
||||
}
|
||||
|
||||
/// One newly made clipboard object and the source document resources it uses. Type-range
|
||||
/// Copy builds an object from selected runs rather than copying a whole document node.
|
||||
pub fn from_node(st: &DocState, node: Node) -> Self {
|
||||
let mut clip = Self::gather(&st.doc, vec![node]);
|
||||
clip.source_doc = Some(st.uid);
|
||||
clip
|
||||
}
|
||||
|
||||
/// Objects `roots` of `st`'s document with their resources, source artboard and layers.
|
||||
@@ -195,7 +212,7 @@ impl Clipboard {
|
||||
|
||||
/// The objects as standalone SVG (`None` when there are none).
|
||||
pub fn svg(&self) -> Option<String> {
|
||||
if self.is_empty() {
|
||||
if !self.has_art() {
|
||||
return None;
|
||||
}
|
||||
let d = self.to_document();
|
||||
|
||||
@@ -286,7 +286,7 @@ impl Clipboard {
|
||||
|
||||
/// The MIME types of [`Self::flavours`], without making them.
|
||||
pub fn flavour_types(&self, svg: bool, pdf: bool) -> Vec<&'static str> {
|
||||
if self.is_empty() {
|
||||
if !self.has_art() {
|
||||
return vec![];
|
||||
}
|
||||
let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only);
|
||||
|
||||
@@ -116,7 +116,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Color Guide",
|
||||
[],
|
||||
None,
|
||||
"{color, rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}",
|
||||
"{color (#rrggbbaa and #rgba are refused), rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}",
|
||||
always,
|
||||
harmony
|
||||
),
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Color",
|
||||
[],
|
||||
None,
|
||||
"{color, to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
|
||||
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
|
||||
always,
|
||||
convert_color
|
||||
),
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gamut Warning",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, colors?: [color]} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
|
||||
"{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}",
|
||||
has_doc,
|
||||
gamut_check
|
||||
),
|
||||
@@ -319,17 +319,138 @@ pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
changed = set_color_mode(d, mode, convert, intent, grays);
|
||||
Ok(())
|
||||
})?;
|
||||
if convert {
|
||||
if s.in_interaction() && s.batch_stash.is_none() {
|
||||
if let Some(it) = &mut s.doc_mut()?.interaction {
|
||||
it.deferred_color_mode = Some(DeferredColorMode { mode, intent, grays });
|
||||
}
|
||||
} else {
|
||||
let before = new_art_colors_before(s)?;
|
||||
convert_new_art_colors(s, mode, intent, grays)?;
|
||||
record_new_art_colors(s, before)?;
|
||||
}
|
||||
} else if s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
|
||||
let before = new_art_colors_before(s)?;
|
||||
record_new_art_colors(s, before)?;
|
||||
}
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks
|
||||
/// included), symbols, graph designs, pattern tiles (the tile that pattern editing's Cancel puts
|
||||
/// back included), graphic styles, brushes (their art and a Hue Shift key color) and swatches
|
||||
/// through the color settings (`intent`, default: theirs) → how many colors of the art (opacity
|
||||
/// masks included), symbols, graph designs and pattern tiles changed; the colors of graphic
|
||||
/// styles and brushes convert without being counted. Gray colors stay
|
||||
/// Gray (they print on the black plate in either mode); RGB grays are colors like any other and
|
||||
/// separate through the CMYK profile, unless `grays` puts them on the black plate. Lab colors
|
||||
/// The validated conversion choices of the current tentative color-mode preview.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct DeferredColorMode {
|
||||
mode: ColorMode,
|
||||
intent: Option<Intent>,
|
||||
grays: Grays,
|
||||
}
|
||||
|
||||
/// Complete the deferred new-art conversion before the interaction becomes an Undo step.
|
||||
pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> {
|
||||
let pending =
|
||||
s.doc()?.interaction.as_ref().filter(|it| it.preview.is_some() && it.color_mode_paints.is_none()).and_then(|it| it.deferred_color_mode);
|
||||
if let Some(DeferredColorMode { mode, intent, grays }) = pending {
|
||||
let before = new_art_colors_before(s)?;
|
||||
convert_new_art_colors(s, mode, intent, grays)?;
|
||||
record_new_art_colors(s, before)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> {
|
||||
let after = s.paint.clone();
|
||||
if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
|
||||
let st = s.doc_mut()?;
|
||||
let slot = if let Some(it) = &mut st.interaction {
|
||||
Some(&mut it.color_mode_paints)
|
||||
} else {
|
||||
st.history.undo.last_mut().map(|e| &mut e.color_mode_paints)
|
||||
};
|
||||
if let Some(slot) = slot {
|
||||
match slot {
|
||||
Some((_, end)) => *end = after,
|
||||
slot => *slot = Some((before, after)),
|
||||
}
|
||||
}
|
||||
if st.interaction.is_none() {
|
||||
if let Some(e) = st.history.undo.last_mut() {
|
||||
e.recost_paints();
|
||||
}
|
||||
st.history.trim();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> {
|
||||
let st = s.doc()?;
|
||||
Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone()))
|
||||
}
|
||||
|
||||
/// Convert the fill and stroke that new art takes, and the colors of its template appearance
|
||||
/// (paints and effect colors), as [`set_color_mode`] converted the active document's art. The
|
||||
/// command records their original values for Undo. Previews defer this until acceptance;
|
||||
/// a batch converts immediately and restores the values itself when it fails.
|
||||
fn convert_new_art_colors(s: &mut Session, mode: ColorMode, intent: Option<Intent>, grays: Grays) -> Result<()> {
|
||||
let d = &s.doc()?.doc;
|
||||
let bases = global_bases(d);
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
let mut f = |col: &Color, link: proof::Link| mode_color(col, link, &bases, &conv);
|
||||
map_paint_colors(&mut s.paint.fill, &mut f);
|
||||
map_paint_colors(&mut s.paint.stroke, &mut f);
|
||||
if let Some(a) = s.paint.appearance.as_mut() {
|
||||
for it in &mut a.items {
|
||||
let paint = match it {
|
||||
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
|
||||
};
|
||||
map_paint_colors(paint, &mut f);
|
||||
}
|
||||
map_effect_colors(a, &mut f);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How Document Color Mode converts a color to `mode` through the color settings (`intent`,
|
||||
/// default: theirs): Gray and Lab colors stay as they are; with `grays` on the black plate, an RGB
|
||||
/// gray becomes K only in CMYK.
|
||||
fn mode_converter(mode: ColorMode, intent: Option<Intent>, grays: Grays) -> impl Fn(&Color) -> Color {
|
||||
let c = cms::active();
|
||||
let intent = intent.unwrap_or(c.settings().intent);
|
||||
let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb };
|
||||
let k_only = model == Model::Cmyk && grays == Grays::Black;
|
||||
move |col: &Color| match col {
|
||||
Color::Gray { .. } | Color::Lab { .. } => *col,
|
||||
// Grey ink percentage, then K only (a Gray colour's CMYK).
|
||||
Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent),
|
||||
_ => c.convert(col, model, intent),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name and color of each global swatch of `d`, for [`mode_color`].
|
||||
fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> {
|
||||
d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect()
|
||||
}
|
||||
|
||||
/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in
|
||||
/// `bases` (already converted) is that swatch's color at its tint; any other color goes through
|
||||
/// `conv` ([`mode_converter`]).
|
||||
fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color {
|
||||
match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
|
||||
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
|
||||
_ => conv(col),
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks,
|
||||
/// effect colors and the series paints and label styles that graphs keep included), symbols,
|
||||
/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included),
|
||||
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and
|
||||
/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art
|
||||
/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern
|
||||
/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray
|
||||
/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any
|
||||
/// other and separate through the CMYK profile, unless `grays` puts them on the black plate
|
||||
/// ([`mode_converter`]). Lab colors
|
||||
/// (spot color definitions) are device independent and fit either mode. A tint of a global
|
||||
/// swatch becomes the converted swatch's color at its tint. Document Color Mode and
|
||||
/// `document.open {colorMode}` both convert this way.
|
||||
@@ -338,16 +459,7 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
if !convert {
|
||||
return 0;
|
||||
}
|
||||
let c = cms::active();
|
||||
let intent = intent.unwrap_or(c.settings().intent);
|
||||
let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb };
|
||||
let k_only = model == Model::Cmyk && grays == Grays::Black;
|
||||
let conv = |col: &Color| match col {
|
||||
Color::Gray { .. } | Color::Lab { .. } => *col,
|
||||
// Grey ink percentage, then K only (a Gray colour's CMYK).
|
||||
Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent),
|
||||
_ => c.convert(col, model, intent),
|
||||
};
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
for sw in d.swatches_iter_mut() {
|
||||
match &mut sw.paint {
|
||||
Paint::Solid { color, .. } => *color = conv(color),
|
||||
@@ -360,13 +472,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
}
|
||||
}
|
||||
// Tints are their converted swatch's colour at their tint (exact ink percentages).
|
||||
let bases: Vec<(String, Color)> = d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect();
|
||||
let bases = global_bases(d);
|
||||
let changed = std::cell::Cell::new(0usize);
|
||||
let mut count = |col: &Color, link: proof::Link| {
|
||||
let n = match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
|
||||
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
|
||||
_ => conv(col),
|
||||
};
|
||||
let n = mode_color(col, link, &bases, &conv);
|
||||
if n != *col {
|
||||
changed.set(changed.get() + 1);
|
||||
}
|
||||
@@ -384,12 +493,15 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
}
|
||||
// The reply counts the colors of the document's art only, not those of the graphic styles and brushes.
|
||||
let in_art = changed.get();
|
||||
for it in d.graphic_styles.iter_mut().flat_map(|g| &mut g.appearance.items) {
|
||||
let paint = match it {
|
||||
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
|
||||
};
|
||||
map_paint_colors(paint, &mut count);
|
||||
for g in &mut d.graphic_styles {
|
||||
for it in &mut g.appearance.items {
|
||||
let paint = match it {
|
||||
vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint,
|
||||
};
|
||||
map_paint_colors(paint, &mut count);
|
||||
}
|
||||
map_effect_colors(&mut g.appearance, &mut count);
|
||||
}
|
||||
// Convert each brush's art. A Hue Shift key color takes the converted color of the art color
|
||||
// it matches (a tint of a global swatch included), so the key still matches the converted art;
|
||||
@@ -438,19 +550,28 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
in_art
|
||||
}
|
||||
|
||||
/// [`proof::map_node_colors`] over `n`'s subtree and the art of every opacity mask in it.
|
||||
/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`].
|
||||
fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
proof::map_node_colors(n, f);
|
||||
map_mask_colors(n, f);
|
||||
map_more_colors(n, f);
|
||||
}
|
||||
|
||||
fn map_mask_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
map_art_colors(Arc::make_mut(&mut mask.art), f);
|
||||
/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the
|
||||
/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps
|
||||
/// ([`map_graph_colors`]) and the art of every opacity mask.
|
||||
fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
map_effect_colors(&mut n.appearance, f);
|
||||
if let Some(e) = n.extras_if_any() {
|
||||
if let Some(g) = e.graph.as_deref_mut() {
|
||||
map_graph_colors(g, f);
|
||||
}
|
||||
if let Some(mask) = e.mask.as_deref_mut() {
|
||||
map_art_colors(Arc::make_mut(&mut mask.art), f);
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
map_mask_colors(Arc::make_mut(c), f);
|
||||
map_more_colors(Arc::make_mut(c), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -461,7 +582,46 @@ fn matches_key(c: &Color, key: &Color) -> bool {
|
||||
c.to_rgb().iter().zip(key.to_rgb()).map(|(a, b)| (a - b).abs()).sum::<f32>() < 0.02
|
||||
}
|
||||
|
||||
/// `f` applied to a solid paint's color or a gradient's stop colors, given their swatch link.
|
||||
/// `f` applied to the `color` of each effect in appearance `a` (the object's effects and those of
|
||||
/// each fill and stroke) that has one ([`super::params::effect_color`]). An effect that draws its
|
||||
/// default color stores the new color as its own. The light colors of the 3D effects stay as they
|
||||
/// are.
|
||||
fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
|
||||
for e in a.effects.iter_mut().chain(items) {
|
||||
if !(e.params.is_object() || e.params.is_null()) {
|
||||
continue;
|
||||
}
|
||||
let Some(color) = super::params::effect_color(&e.id, &e.params) else { continue };
|
||||
let n = f(&color, None);
|
||||
if n == color {
|
||||
continue;
|
||||
}
|
||||
match &mut e.params {
|
||||
Value::Object(m) => {
|
||||
m.insert("color".into(), json!(n));
|
||||
}
|
||||
p => *p = json!({ "color": n }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and
|
||||
/// labels take each time it is drawn again.
|
||||
fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
for p in g.series_paints.iter_mut() {
|
||||
for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() {
|
||||
map_paint_colors(paint, f);
|
||||
}
|
||||
}
|
||||
let styles = &mut g.label_styles;
|
||||
for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() {
|
||||
map_paint_colors(&mut st.fill, f);
|
||||
map_paint_colors(&mut st.stroke, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f` applied to solid, gradient-stop and freeform-control colors, with any swatch link.
|
||||
fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, tint } => *color = f(color, swatch.as_deref().map(|s| (s, *tint))),
|
||||
@@ -469,6 +629,11 @@ fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Col
|
||||
for st in &mut g.gradient.stops {
|
||||
st.color = f(&st.color, st.swatch.as_deref().map(|s| (s, st.tint)));
|
||||
}
|
||||
if let Some(freeform) = &mut g.freeform {
|
||||
for point in &mut freeform.points {
|
||||
point.color = f(&point.color, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -510,7 +675,9 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn gamut_check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut cols: Vec<Color> = vec![];
|
||||
if let Some(a) = p.get("colors").and_then(Value::as_array) {
|
||||
cols.extend(a.iter().filter_map(color_value));
|
||||
for v in a {
|
||||
cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?);
|
||||
}
|
||||
} else {
|
||||
let st = s.doc()?;
|
||||
let ids = targets(s, p)?;
|
||||
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save Theme",
|
||||
["Window", "Color Themes"],
|
||||
None,
|
||||
"{colors: [1–5 colours] | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}",
|
||||
"{colors: [1–5 colours] (#rrggbbaa and #rgba are refused) | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}",
|
||||
always,
|
||||
save
|
||||
),
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -706,6 +706,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::paint::check_keep_model(p, "text.create")?;
|
||||
check_numbers(p, &["size"], "text.create")?;
|
||||
check_switches(p, &["vertical", "placeholder"], "text.create")?;
|
||||
super::color_param(p, "color", "text.create")?;
|
||||
if let Some(a) = p.get("area") {
|
||||
check_numbers(a, &["width", "height"], "text.create")?;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Instance",
|
||||
["Select", "Same"],
|
||||
None,
|
||||
"{} select the instances of the symbol of the first selected object that can be selected; objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are passed over → {count}",
|
||||
"{} select the instances of the symbol of the first selected object that can be selected, including a group member selected on its own; when that object is not a symbol instance, such as a group, nothing is selected; objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated (new art while it stays selected excepted), or outside the isolated group or layer are passed over → {count}",
|
||||
has_selection,
|
||||
|s, _| same(s, "select.same.symbolInstance", |a, b| match (&a.kind, &b.kind) {
|
||||
(NodeKind::SymbolInstance { symbol: x, .. }, NodeKind::SymbolInstance { symbol: y, .. }) => x == y,
|
||||
@@ -256,7 +256,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Color Mode",
|
||||
["File", "Document Color Mode"],
|
||||
None,
|
||||
"{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks included), symbols, graph designs, pattern tiles, graphic styles, brushes and swatches through the color settings; swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}",
|
||||
"{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks, effect colors and graphs' series and label paints included), symbols, graph designs, pattern tiles, graphic styles (their effect colors included), brushes, swatches and the paints new art takes through the color settings, together in one undo step (Undo restores their original values; Redo reapplies the conversion); swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}",
|
||||
has_doc,
|
||||
super::colormgmt::convert_mode
|
||||
),
|
||||
@@ -337,7 +337,7 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool)
|
||||
/// object inside two selected objects is given twice. The walk stops when `f` returns false.
|
||||
fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(NodeId) -> bool) -> bool {
|
||||
if !n.visible || n.locked {
|
||||
if !n.visible || n.locked || n.is_template() {
|
||||
return true;
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Text(_)) && !f(n.id) {
|
||||
|
||||
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Setup",
|
||||
[],
|
||||
None,
|
||||
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
|
||||
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
|
||||
has_doc,
|
||||
setup
|
||||
)]
|
||||
|
||||
@@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req,
|
||||
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_or_artboard_tool, has_selection_or_guides, id_param, index, ok, point_param,
|
||||
str_param,
|
||||
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok,
|
||||
point_param, str_param,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
@@ -125,8 +125,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
undo_group_end
|
||||
),
|
||||
cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{} (the Artboard tool chosen: artboard.cut)", has_selection_or_artboard_tool, cut),
|
||||
cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{} (the Artboard tool chosen: artboard.copy)", has_selection_or_artboard_tool, copy),
|
||||
cmd!(
|
||||
"edit.cut",
|
||||
"Cut",
|
||||
["Edit"],
|
||||
Some("Cmd+X"),
|
||||
"{} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
cut
|
||||
),
|
||||
cmd!(
|
||||
"edit.copy",
|
||||
"Copy",
|
||||
["Edit"],
|
||||
Some("Cmd+C"),
|
||||
"{} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
copy
|
||||
),
|
||||
cmd!(
|
||||
"edit.paste",
|
||||
"Paste",
|
||||
@@ -177,7 +193,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)",
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -487,6 +503,9 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
let paints = e.color_mode_paints.clone();
|
||||
turned.color_mode_paints = e.color_mode_paints;
|
||||
turned.recost_paints();
|
||||
st.history.redo.push(turned);
|
||||
st.history.trim();
|
||||
st.revision += 1;
|
||||
@@ -499,6 +518,9 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
leave_isolation_if_gone(st);
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((before, _)) = paints {
|
||||
s.paint = before;
|
||||
}
|
||||
Ok(json!({ "undone": label }))
|
||||
}
|
||||
|
||||
@@ -516,6 +538,9 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
let paints = e.color_mode_paints.clone();
|
||||
turned.color_mode_paints = e.color_mode_paints;
|
||||
turned.recost_paints();
|
||||
st.history.undo.push(turned);
|
||||
st.history.trim();
|
||||
st.revision += 1;
|
||||
@@ -527,6 +552,9 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
leave_isolation_if_gone(st);
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((_, after)) = paints {
|
||||
s.paint = after;
|
||||
}
|
||||
Ok(json!({ "redone": label }))
|
||||
}
|
||||
|
||||
@@ -640,9 +668,35 @@ fn copy(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if s.tool_id() == "artboard" {
|
||||
return super::panelcmds::artboard_copy(s, &json!({}), false);
|
||||
}
|
||||
let roots = selected_roots(s)?;
|
||||
s.clipboard = Clipboard::copy(s.doc()?, &roots);
|
||||
Ok(json!({ "copied": s.clipboard.nodes.len() }))
|
||||
let st = s.doc()?;
|
||||
// Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay
|
||||
// behind.
|
||||
let guides: Vec<vectorcraft_doc::Guide> = st
|
||||
.selection
|
||||
.guides
|
||||
.iter()
|
||||
.filter_map(|i| st.doc.guides.get(*i))
|
||||
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() })
|
||||
.collect();
|
||||
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? };
|
||||
let st = s.doc()?;
|
||||
let mut clip = Clipboard::copy(st, &roots);
|
||||
// Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes
|
||||
// measure from, as the objects' artboard is.
|
||||
if clip.nodes.is_empty()
|
||||
&& let Some(g) = st.selection.guides.first().and_then(|i| st.doc.guides.get(*i))
|
||||
{
|
||||
let board = g.artboard.and_then(|id| st.doc.artboards.iter().find(|a| a.id == id)).or_else(|| {
|
||||
st.doc
|
||||
.artboards
|
||||
.iter()
|
||||
.find(|a| if g.vertical { (a.rect.x0..=a.rect.x1).contains(&g.pos) } else { (a.rect.y0..=a.rect.y1).contains(&g.pos) })
|
||||
});
|
||||
clip.source_artboard = board.map(|a| a.rect);
|
||||
}
|
||||
clip.guides = guides;
|
||||
s.clipboard = clip;
|
||||
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
|
||||
}
|
||||
|
||||
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -651,9 +705,15 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Copy promotes a compound member to its compound. Cut must remove the same objects it
|
||||
// copied, while Clear on its own deletes exactly the selected members.
|
||||
// Ruler guides selected on their own: Copy takes them, Clear removes them.
|
||||
if s.doc()?.selection.is_empty() {
|
||||
copy(s, p)?;
|
||||
return clear(s, &json!({}));
|
||||
}
|
||||
let ids = selected_roots(s)?;
|
||||
copy(s, p)?;
|
||||
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids })) } else { clear(s, &json!({})) }
|
||||
// The selected ruler guides it copied go with the objects, in the same undo step (#3226).
|
||||
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) }
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -667,8 +727,9 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return super::docmenu::guide_remove(s, &json!({}));
|
||||
}
|
||||
let st = s.doc()?;
|
||||
// Guides selected with the art go with it (not when ids are given).
|
||||
let with_guides = explicit.is_none();
|
||||
// Guides selected with the art go with it (not when ids are given, unless `guides` says so:
|
||||
// Cut, which names the objects it copied).
|
||||
let with_guides = explicit.is_none() || bool_or(p, "guides", false);
|
||||
let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc));
|
||||
// Keep the selected ids themselves, without promoting compound members. Delete a selected
|
||||
// ancestor just once; its selected descendants leave with it. Layers themselves are kept.
|
||||
@@ -838,6 +899,13 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
// In place, in front, in back: onto the active artboard when the UI names it.
|
||||
_ => vec![onto_artboard(&st.doc, p, clip)],
|
||||
};
|
||||
// Guides alone don't follow a plain paste's offset or the view centre: they stay where they
|
||||
// were. With objects they move as the objects do.
|
||||
let guide_placements: Vec<Affine> = if !clip.nodes.is_empty() || !matches!(mode, PasteMode::Offset | PasteMode::Library | PasteMode::Drag) {
|
||||
placements.clone()
|
||||
} else {
|
||||
vec![Affine::IDENTITY]
|
||||
};
|
||||
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
|
||||
let imported = clip.import_into(d, choices, same_doc);
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
@@ -885,6 +953,20 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
|
||||
// paste of guides alone keeps them where they were, but onto another artboard or every
|
||||
// artboard as the in-place pastes put art); they are selected with the objects.
|
||||
let guide_layer = parent.and_then(|p| if d.node(p).is_some_and(Node::is_layer) { Some(p) } else { d.layer_containing(p) });
|
||||
for xf in &guide_placements {
|
||||
let dv = xf.translation();
|
||||
for g in &clip.guides {
|
||||
let pos = g.pos + if g.vertical { dv.x } else { dv.y };
|
||||
if pos.is_finite() {
|
||||
sel.guides.push(d.guides.len());
|
||||
d.guides.push(vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pasted type arrives without the layout bounds cache: fill it so boxes and alignment are
|
||||
// right away (opening the file later would, but paste must not depend on a reopen).
|
||||
super::typecmd::refresh_bounds_of(d, &new_ids);
|
||||
@@ -899,6 +981,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
Ok(json!({
|
||||
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"guides": clip.guides.len() * guide_placements.len(),
|
||||
"artboard": artboards.first(),
|
||||
"artboards": artboards,
|
||||
"added": imported.added,
|
||||
|
||||
@@ -108,7 +108,7 @@ mod export_names;
|
||||
mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use access::list_dir;
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::write_file_with;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::{Placed, copy_new, file_metadata};
|
||||
@@ -120,7 +120,7 @@ pub(crate) use access::{drive_share_of, share_of};
|
||||
#[cfg(test)]
|
||||
pub(crate) use access::{drive_share_path, share_path, touched};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use access::{may_read, may_write};
|
||||
pub(crate) use access::{may_read, may_write};
|
||||
pub use commands::specs;
|
||||
pub use export_names::artboard_file_names;
|
||||
pub(crate) use export_names::{default_name, merge, unique_file_names, with_black_output, write_or_return};
|
||||
|
||||
@@ -10,7 +10,7 @@ use super::{EngineError, Result, Session, Value, bad, json};
|
||||
|
||||
/// `path` checked for reading against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn may_read(path: &str) -> Result<()> {
|
||||
pub(crate) fn may_read(path: &str) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
touch(path);
|
||||
crate::file_access::check_read(path).map_err(EngineError::Other)
|
||||
@@ -44,7 +44,7 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn may_write(path: &str) -> Result<()> {
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ pub(super) fn file_list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// The entries of folder `path`, sorted by name: at most `max`, and whether there were more. A
|
||||
/// link isn't followed: its target may lie outside the automation roots.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
|
||||
pub(crate) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
|
||||
may_read(path)?;
|
||||
let dir = std::fs::read_dir(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let mut entries: Vec<(String, Value)> = vec![];
|
||||
@@ -195,7 +195,7 @@ pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec<Value>, bool)> {
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) fn list_dir(_: &str, _: usize) -> Result<(Vec<Value>, bool)> {
|
||||
pub(crate) fn list_dir(_: &str, _: usize) -> Result<(Vec<Value>, bool)> {
|
||||
Err(EngineError::Other("no file system here".into()))
|
||||
}
|
||||
|
||||
|
||||
@@ -15,12 +15,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let artboard = p.get("artboard").and_then(Value::as_u64);
|
||||
// What an error rolls back besides the documents: session-level state a step may change
|
||||
// (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group).
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
// A drag or typing still in progress is a step of its own, as before Undo: the batch's steps
|
||||
// would otherwise run inside it and take its baseline as theirs (#1697).
|
||||
if s.active().is_some() {
|
||||
if s.active().is_some() && !s.previewing {
|
||||
super::super::edit::settle_interaction(s)?;
|
||||
}
|
||||
let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone());
|
||||
// The documents as they are now, whole: what a failed step brings back. Their art, history,
|
||||
// file, format and saved state share their data with the open ones until a step changes them.
|
||||
let start = s.docs.clone();
|
||||
@@ -47,10 +47,18 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
// Each document the steps edited keeps them as one undo step.
|
||||
s.remember_pending_paint();
|
||||
for st in &mut s.docs {
|
||||
if let Some(it) = st.interaction.take() {
|
||||
st.keep_interaction(it);
|
||||
if !s.previewing {
|
||||
s.remember_pending_paint();
|
||||
for st in &mut s.docs {
|
||||
if let Some(mut it) = st.interaction.take() {
|
||||
// Redo restores the new-art colors the whole batch left, not the ones right after a
|
||||
// color-mode step.
|
||||
if let Some((_, after)) = &mut it.color_mode_paints {
|
||||
after.clone_from(&s.paint);
|
||||
s.batch_paint_docs.push(st.uid);
|
||||
}
|
||||
st.keep_interaction(it);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The batch journals itself, whichever document it ends in.
|
||||
@@ -58,7 +66,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(o) = entry.as_object_mut() {
|
||||
o.insert("commands".into(), Value::Array(cmds));
|
||||
}
|
||||
s.journal.push(("command.batch".into(), entry));
|
||||
if !s.previewing {
|
||||
s.journal.push(("command.batch".into(), entry));
|
||||
}
|
||||
Ok(json!({ "results": results }))
|
||||
}
|
||||
|
||||
@@ -104,6 +114,9 @@ fn run_steps(
|
||||
let held: Vec<(u64, Arc<Document>)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect();
|
||||
let (v, noted) =
|
||||
s.execute_step(&id, ¶ms).map_err(|e| EngineError::Other(format!("batch step {} (`{id}`) failed: {e}", results.len())))?;
|
||||
if s.previewing && s.active().map(|d| d.uid) != start {
|
||||
return Err(bad("command.batch", "a batch preview cannot switch documents"));
|
||||
}
|
||||
grouped.push(step_groups(s, start, &held));
|
||||
// The step's journal entry records what it took from the preferences or the clock (a
|
||||
// save's date, a new document's), as a command of its own would.
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
|
||||
@@ -165,18 +165,18 @@ pub fn load(name: &str, bytes: &[u8]) -> Result<Loaded> {
|
||||
/// of its art, which it carries: its layers and hidden objects as they were, and the art outside
|
||||
/// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read.
|
||||
/// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its
|
||||
/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `private`: the
|
||||
/// editor's copy ([`editing_copy`]).
|
||||
/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `layers`: the
|
||||
/// editor's copy ([`editing_copy`]), as far as it was decoded and read.
|
||||
fn through_editing_data(
|
||||
private: Option<&[u8]>,
|
||||
layers: Option<vectorcraft_eps::AiLayers>,
|
||||
opts: &LoadOptions,
|
||||
doc: Document,
|
||||
warnings: Vec<String>,
|
||||
unit: f64,
|
||||
) -> (Document, Vec<String>, bool) {
|
||||
let Some(private) = private else { return (doc, warnings, false) };
|
||||
let Some(layers) = layers else { return (doc, warnings, false) };
|
||||
let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines;
|
||||
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(private, doc, warnings, outlined, opts.trust_editing_data, unit);
|
||||
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit);
|
||||
// The layers weren't read (or couldn't be): the notes of reading the PDF part still hold.
|
||||
if !read {
|
||||
return (doc, warnings, false);
|
||||
@@ -216,6 +216,14 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool {
|
||||
opts.pages.is_none() && opts.layers && opts.editing_data
|
||||
}
|
||||
|
||||
/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part
|
||||
/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages'
|
||||
/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its
|
||||
/// type as text?
|
||||
fn reads_layers_alone(opts: &LoadOptions) -> bool {
|
||||
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
}
|
||||
|
||||
/// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`]
|
||||
/// reads it), when `opts` read it ([`reads_editing_copy`]).
|
||||
fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<Vec<u8>> {
|
||||
@@ -365,41 +373,68 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
Ok(o) => super::pdfimport::import(bytes, o, opts, format.id != "pdf"),
|
||||
Err(e) => Err(err(e)),
|
||||
};
|
||||
let read = restore_or_import(editing, || match imported() {
|
||||
Ok(r) => {
|
||||
// The editor's copy, read once the import is done with the pages.
|
||||
let private = opened.as_ref().ok().and_then(|o| editing_copy(o, opts));
|
||||
// Pages of text alone: the editing copy alone where it reads, as for a file
|
||||
// saved without its PDF part (#1387: else the page, which is the art). So too
|
||||
// pages that draw nothing at all: there is no page art to check the layers
|
||||
// against, and the empty page would lose all of it.
|
||||
// A page is empty only when nothing on it was skipped (an image that can't be
|
||||
// decoded draws nothing either): its notes are at most the page's own.
|
||||
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
|
||||
let alone = (r.only_text || empty)
|
||||
.then(|| private.as_deref().map(editing_copy_alone))
|
||||
.flatten()
|
||||
.and_then(|read| read.ok())
|
||||
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts));
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => through_editing_data(private.as_deref(), opts, r.document, r.warnings, r.user_unit),
|
||||
};
|
||||
editing_data = read;
|
||||
Ok((doc, warnings))
|
||||
let read = restore_or_import(editing, || {
|
||||
// Type all from the text document and nothing that needs the PDF part: the layers
|
||||
// alone, the PDF part not imported. Else what was read of the layers is kept for
|
||||
// reading them with the PDF part.
|
||||
let mut layers = None;
|
||||
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
|
||||
{
|
||||
let pages = o.trim_pages();
|
||||
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit) {
|
||||
Ok((mut doc, warnings)) => {
|
||||
doc.setup.bleed = pages.bleed;
|
||||
editing_data = true;
|
||||
return Ok((doc, warnings));
|
||||
}
|
||||
Err(read) => layers = Some(read),
|
||||
}
|
||||
}
|
||||
match imported() {
|
||||
Ok(r) => {
|
||||
// The editor's copy, read once the import is done with the pages, unless
|
||||
// its layers were read before it.
|
||||
let private = layers.is_none().then(|| opened.as_ref().ok().and_then(|o| editing_copy(o, opts))).flatten();
|
||||
// Pages of text alone: the editing copy alone where it reads, as for a file
|
||||
// saved without its PDF part (#1387: else the page, which is the art). So too
|
||||
// pages that draw nothing at all: there is no page art to check the layers
|
||||
// against, and the empty page would lose all of it.
|
||||
// A page is empty only when nothing on it was skipped (an image that can't be
|
||||
// decoded draws nothing either): its notes are at most the page's own.
|
||||
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
|
||||
let copy_alone = || match &private {
|
||||
Some(private) => Some(editing_copy_alone(private)),
|
||||
None if layers.is_some() => opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p)),
|
||||
None => None,
|
||||
};
|
||||
let alone = (r.only_text || empty)
|
||||
.then(copy_alone)
|
||||
.flatten()
|
||||
.and_then(|read| read.ok())
|
||||
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts));
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => {
|
||||
let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode));
|
||||
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
|
||||
}
|
||||
};
|
||||
editing_data = read;
|
||||
Ok((doc, warnings))
|
||||
}
|
||||
// Saved without its PDF part: the editing copy is all the file has (`pages` that
|
||||
// name every page read it as the whole file).
|
||||
Err(e) if is_placeholder(&e) => opened
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|o| from_editing_data_alone(o, opts))
|
||||
.unwrap_or(Err(e))
|
||||
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts))
|
||||
.inspect(|_| editing_data = true),
|
||||
// A PDF part that can't be read (a stream the import refuses): the editing copy
|
||||
// alone where it reads, else the error.
|
||||
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
|
||||
}
|
||||
// Saved without its PDF part: the editing copy is all the file has (`pages` that
|
||||
// name every page read it as the whole file).
|
||||
Err(e) if is_placeholder(&e) => opened
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|o| from_editing_data_alone(o, opts))
|
||||
.unwrap_or(Err(e))
|
||||
.map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts))
|
||||
.inspect(|_| editing_data = true),
|
||||
// A PDF part that can't be read (a stream the import refuses): the editing copy
|
||||
// alone where it reads, else the error.
|
||||
Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e),
|
||||
})?;
|
||||
// The File Info of a file read from its pages or its editing copy.
|
||||
if !read.2 {
|
||||
|
||||
@@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
|
||||
name: "editingData",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, paths, fills and strokes, colors, swatches and artboards, with type, gradients, patterns, images, symbols, clipping and live objects as plain filled and stroked paths, without transparency (written only with every artboard, as Preserve Editing is)",
|
||||
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, swatches, artboards, the transparency of objects and layers, objects' opacity masks, and clipping groups and layers clipped by a path, with type, gradients, patterns, images, symbols, other clipping objects and live objects as plain filled and stroked paths (written only with every artboard, as Preserve Editing is)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "aiVersion",
|
||||
|
||||
@@ -24,8 +24,8 @@ const TRUNCATED: &str = "the Pixar file is cut short";
|
||||
/// define.
|
||||
const DAMAGED: &str = "the Pixar file's header is damaged";
|
||||
|
||||
/// The message for encoded tile data with a packet the format doesn't define, or one that runs
|
||||
/// past the end of its scan line.
|
||||
/// The message for a tile pointer into the header or the tile pointer table, and for encoded tile
|
||||
/// data with a packet the format doesn't define, or one that runs past the end of its scan line.
|
||||
const BAD_DATA: &str = "the Pixar file's image data is damaged";
|
||||
|
||||
/// The channel bits of the picture format field (header byte 424): R, G, B and A, stored in this
|
||||
@@ -115,7 +115,9 @@ pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, S
|
||||
let layout =
|
||||
Layout { gray: format & 0b1110 == 0b1000, matted: alpha_mode == 0, alpha: format & 1 != 0, sample: if wide { 2 } else { 1 }, wide, stored };
|
||||
let (across, down) = (w.div_ceil(tile_w), h.div_ceil(tile_h));
|
||||
let table = bytes.get(HEADER..HEADER + across * down * 8).ok_or(TRUNCATED)?;
|
||||
// A table end past the largest address is past the end of the file too.
|
||||
let table_end = across.checked_mul(down).and_then(|n| n.checked_mul(8)).and_then(|n| n.checked_add(HEADER)).ok_or(TRUNCATED)?;
|
||||
let table = bytes.get(HEADER..table_end).ok_or(TRUNCATED)?;
|
||||
let empty = if layout.alpha { [0; 4] } else { [0, 0, 0, 255] };
|
||||
let mut img = image::RgbaImage::from_pixel(w as u32, h as u32, image::Rgba(empty));
|
||||
// The encoded data read in all, which a file whose tiles each hold their own data stays within.
|
||||
@@ -131,6 +133,11 @@ pub(super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, S
|
||||
if length == -1 || pointer >= bytes.len() {
|
||||
return Err(TRUNCATED.into());
|
||||
}
|
||||
// Tile data follows the tile pointer table; a pointer into the header or the table would
|
||||
// read them as pixels.
|
||||
if pointer < table_end {
|
||||
return Err(BAD_DATA.into());
|
||||
}
|
||||
let (x0, y0) = (n % across * tile_w, n / across * tile_h);
|
||||
// The part of the tile inside the picture; the pixels of border tiles past its edges are
|
||||
// stored and skipped.
|
||||
|
||||
@@ -1221,10 +1221,16 @@ fn half_outlined_line(y: f64, rest: &str, mode: u8) -> String {
|
||||
/// text document (a line starting at (14, 65)), then `more` of a story the text document doesn't
|
||||
/// have. Without `story` the file has no text document.
|
||||
fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec<u8> {
|
||||
half_outlined_ai_on(story, more, type_content, "", |page| page)
|
||||
}
|
||||
|
||||
/// [`half_outlined_ai`] with the editing data's comments `head` before its art, whose page is
|
||||
/// `page_of` the 200 × 100 pt page it draws on (other boxes, more entries).
|
||||
fn half_outlined_ai_on(story: Option<&str>, more: usize, type_content: &str, head: &str, page_of: impl FnOnce(PdfPage) -> PdfPage) -> Vec<u8> {
|
||||
let text = |story: u32| format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n;\n");
|
||||
let texts: String = std::iter::once(text(0)).chain((0..more).map(|_| text(99))).collect();
|
||||
let mut body =
|
||||
format!("%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0))));
|
||||
format!("{head}%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0))));
|
||||
if let Some(story) = story {
|
||||
// The story's one line starts at the canvas center (8191.5, the template box's center) moved
|
||||
// to (14, 65): its y runs down the page.
|
||||
@@ -1255,7 +1261,7 @@ fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec
|
||||
};
|
||||
let cmap = "begincmap\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n1 beginbfchar\n<41> <FFFD>\nendbfchar\nendcmap\n";
|
||||
pdf_with(
|
||||
&[page],
|
||||
&[page_of(page)],
|
||||
&[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())],
|
||||
None,
|
||||
)
|
||||
@@ -1287,6 +1293,12 @@ fn texts(s: &Session) -> Vec<String> {
|
||||
/// (art x 10 to 90 and 110 to 190, y 10 to 90), then a band across the first frame (y 30 to 70),
|
||||
/// made a wrap object with no offset when `wrap` is set.
|
||||
fn wrapped_thread_ai(wrap: bool) -> Vec<u8> {
|
||||
ai::ai(&wrapped_thread_data(wrap.then_some(0.0)), PLACEHOLDER)
|
||||
}
|
||||
|
||||
/// The editing data of [`wrapped_thread_ai`], compressed, with the band a wrap object of `offset`
|
||||
/// when one is given.
|
||||
fn wrapped_thread_data(offset: Option<f64>) -> Vec<u8> {
|
||||
// The template box is centred at (100, 50), the canvas centre 8191.5: y runs down the canvas.
|
||||
let canvas = |x: f64, y: f64| (x + 8091.5, 8241.5 - y);
|
||||
let rect = |x0: f64, y0: f64, x1: f64, y1: f64| {
|
||||
@@ -1306,14 +1318,47 @@ fn wrapped_thread_ai(wrap: bool) -> Vec<u8> {
|
||||
);
|
||||
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
let frame = |f: u32| format!("/AI11Text :\n0 /FreeUndo ,\n{f} /FrameIndex ,\n0 /StoryIndex ,\n;\n");
|
||||
let dict = if wrap { "%_/ArtDictionary :\n%_0 /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n" } else { "" };
|
||||
let dict = offset
|
||||
.map(|o| format!("%_/ArtDictionary :\n%_{o} /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n"))
|
||||
.unwrap_or_default();
|
||||
let art = format!("{}{}0.5 g\n{}f\n{dict}", frame(0), frame(1), ai::rect(10.0, 30.0, 90.0, 70.0));
|
||||
let body = format!(
|
||||
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
|
||||
ai::layer("Art", &art),
|
||||
lines.join("\n")
|
||||
);
|
||||
ai::ai(&compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()), PLACEHOLDER)
|
||||
compressed(ai::editing_data(200.0, 100.0, &body).as_bytes())
|
||||
}
|
||||
|
||||
/// The wrap offset of the first frame of `doc`'s threaded type, as its text resolves it.
|
||||
fn first_frame_wrap_offset(doc: &vectorcraft_doc::Document) -> f64 {
|
||||
match &doc.node(doc.text_threads[0][0]).unwrap().kind {
|
||||
NodeKind::Text(t) => t.wrap[0].wrap.offset,
|
||||
_ => panic!("area type"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A `.ai` in units of 10 points whose threaded area type flows around a wrap object of a 2 unit
|
||||
/// offset opens with the type flowing round it 20 pt off, its PDF part read or not, and when its
|
||||
/// PDF part can't be read. The default graphic styles of a file without its own aren't scaled.
|
||||
#[test]
|
||||
fn wrapped_type_in_units_of_ten_points_flows_round_the_wrap_at_its_size_in_points() {
|
||||
let private = wrapped_thread_data(Some(2.0));
|
||||
let page = "0.5 g 10 30 80 40 re f";
|
||||
let refused = ai::ai_with_entries_and_content(&private, page, "/UserUnit 10", REFUSED_CONTENT);
|
||||
// On the trim boxes the PDF part is imported, and the refused stream stops it.
|
||||
let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() };
|
||||
let files = [(ai::ai_with(&private, page, "/UserUnit 10"), LoadOptions::default()), (refused, trim)];
|
||||
for (file, opts) in &files {
|
||||
let loaded = load_with("thread.ai", file, opts).unwrap();
|
||||
assert!(loaded.editing_data, "{:?}", loaded.warnings);
|
||||
assert!((first_frame_wrap_offset(&loaded.doc) - 20.0).abs() < 0.01, "{:?}", loaded.warnings);
|
||||
}
|
||||
let loaded = load_with("thread.ai", &files[1].0, &files[1].1).unwrap();
|
||||
assert!(loaded.warnings.iter().any(|w| w.starts_with("the PDF part couldn't be read")), "{:?}", loaded.warnings);
|
||||
// The file has no graphic styles of its own: the default ones aren't scaled either way.
|
||||
let read = load_with("thread.ai", &files[0].0, &files[0].1).unwrap();
|
||||
assert_eq!(loaded.doc.graphic_styles, read.doc.graphic_styles);
|
||||
}
|
||||
|
||||
/// Threaded area type below a wrap object flows around it when the file opens: the text the wrap
|
||||
@@ -1358,6 +1403,77 @@ fn type_from_the_text_document_opens_without_the_pdf_parts_note_on_outlines() {
|
||||
assert!(!r["warnings"].as_array().unwrap().contains(&without_outlines_note(1)), "{r}");
|
||||
}
|
||||
|
||||
/// A `.ai` whose text document makes all of its type, with nothing unread, opens from its layers
|
||||
/// without its PDF part being imported: a page that draws more than the layers isn't compared with
|
||||
/// them. On its trim box it takes the pages' bleed, and pages in units of 10 points draw it ten
|
||||
/// times as large, as when its PDF part is imported. With type the text document can't make,
|
||||
/// editing data on a large canvas, its type asked for as outlines, another box or pages picked, the
|
||||
/// PDF part is imported as before.
|
||||
#[test]
|
||||
fn type_all_from_the_text_document_opens_without_importing_the_pdf_part() {
|
||||
let line = half_outlined_line(65.0, "rst draft", 0);
|
||||
// The page draws a red square the layers don't have.
|
||||
let differs = half_outlined_ai(Some("first draft"), 0, &format!("{line} 1 0 0 rg 20 20 30 30 re f"));
|
||||
let mut s = Session::new();
|
||||
let before = vectorcraft_pdf::imports_of(&differs);
|
||||
let loaded = load_with("draft.ai", &differs, &LoadOptions::default()).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&differs), before, "{:?}", loaded.warnings);
|
||||
assert!(loaded.editing_data, "{:?}", loaded.warnings);
|
||||
assert!(!loaded.warnings.iter().any(|w| w.contains("differently")), "{:?}", loaded.warnings);
|
||||
let r = open(&mut s, "draft.ai", &differs, json!({})).unwrap();
|
||||
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
|
||||
assert_eq!(texts(&s), ["first draft"], "{r}");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the square and the type, without the page's red square: {r}");
|
||||
// A 10 pt bleed round the trim box, the art drawn in the trim box.
|
||||
let bled = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage {
|
||||
media: [0.0, 0.0, 220.0, 120.0],
|
||||
bleed: Some([0.0, 0.0, 220.0, 120.0]),
|
||||
trim: Some([10.0, 10.0, 210.0, 110.0]),
|
||||
content: format!("1 0 0 1 10 10 cm {}", p.content),
|
||||
..p
|
||||
});
|
||||
let before = vectorcraft_pdf::imports_of(&bled);
|
||||
let loaded = load_with("bled.ai", &bled, &LoadOptions::default()).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&bled), before);
|
||||
assert_eq!(loaded.doc.setup.bleed, [10.0; 4]);
|
||||
// Pages of 10 pt units.
|
||||
let large = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { entries: format!("{} /UserUnit 10", p.entries), ..p });
|
||||
let before = vectorcraft_pdf::imports_of(&large);
|
||||
let loaded = load_with("large.ai", &large, &LoadOptions::default()).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::imports_of(&large), before);
|
||||
let board = loaded.doc.artboards[0].rect;
|
||||
assert!((board.width() - 2000.0).abs() < 0.01 && (board.height() - 1000.0).abs() < 0.01, "{board:?}");
|
||||
// Opened on the trim boxes with the PDF part imported and compared, as before, both files have
|
||||
// the same artboards and bleed.
|
||||
for file in [&bled, &large] {
|
||||
let alone = load_with("draft.ai", file, &LoadOptions::default()).unwrap();
|
||||
let compared = load_with("draft.ai", file, &LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }).unwrap();
|
||||
assert!(compared.editing_data, "{:?}", compared.warnings);
|
||||
let boards = |d: &vectorcraft_doc::Document| d.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
|
||||
assert_eq!(boards(&alone.doc), boards(&compared.doc));
|
||||
assert_eq!(alone.doc.setup.bleed, compared.doc.setup.bleed);
|
||||
assert_eq!(names(&alone.doc.layers), names(&compared.doc.layers));
|
||||
// The file has no graphic styles of its own: the default ones aren't scaled.
|
||||
assert_eq!(alone.doc.graphic_styles, compared.doc.graphic_styles);
|
||||
}
|
||||
// The PDF part is imported, once.
|
||||
let unmade = half_outlined_ai(Some("first draft"), 1, &line);
|
||||
// Editing data on a large canvas reads at its own scale when the file has no PDF part.
|
||||
let canvas = half_outlined_ai_on(Some("first draft"), 0, &line, "%AI24_LargeCanvasScale: 2\n", |p| p);
|
||||
let cases = [
|
||||
(&unmade, LoadOptions::default()),
|
||||
(&canvas, LoadOptions::default()),
|
||||
(&differs, LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() }),
|
||||
(&differs, LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }),
|
||||
(&differs, LoadOptions { pages: Some("1".into()), ..Default::default() }),
|
||||
];
|
||||
for (file, opts) in cases {
|
||||
let before = vectorcraft_pdf::imports_of(file);
|
||||
load_with("draft.ai", file, &opts).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::imports_of(file) - before, 1, "{opts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A text object that takes the page's type lacks the glyphs next to it that the page kept as
|
||||
/// outlines: a note counts such objects, in place of the PDF part's notes. Stroked glyphs that
|
||||
/// come in with the stroked type keep the PDF part's notes.
|
||||
|
||||
@@ -453,27 +453,173 @@ fn ai_files_carry_an_editing_copy_for_other_apps() {
|
||||
}
|
||||
|
||||
/// A `.ai` whose editing copy for other apps differs from the VectorCraft document it carries (the
|
||||
/// copy has no transparency) opens in VectorCraft from the VectorCraft document.
|
||||
/// copy leaves the live effect out) opens in VectorCraft from the VectorCraft document.
|
||||
#[test]
|
||||
fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": "ai"})).unwrap());
|
||||
let opacities = |doc: &vectorcraft_doc::Document| {
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "ai"})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("live effects"), "{r}");
|
||||
let bytes = b64(&r);
|
||||
let effects = |doc: &vectorcraft_doc::Document| {
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }) {
|
||||
out.push(n.opacity);
|
||||
out.push(n.appearance.effects.len());
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let copy = load::load_with("art.ai", &bytes, &LoadOptions { native: false, trust_editing_data: true, ..Default::default() }).unwrap();
|
||||
assert!(copy.editing_data && !copy.restored);
|
||||
assert_eq!(opacities(©.doc), [1.0]);
|
||||
assert_eq!(effects(©.doc), [0]);
|
||||
let opened = load::load_with("art.ai", &bytes, &LoadOptions::default()).unwrap();
|
||||
assert!(opened.restored);
|
||||
assert_eq!(opacities(&opened.doc), [0.5]);
|
||||
assert_eq!(effects(&opened.doc), [1]);
|
||||
}
|
||||
|
||||
/// The layers, groups, compound paths and paths of `doc` with their names, visibility, geometric
|
||||
/// bounds (rounded), transparency, clipping and opacity masks, one line each; a mask's art after
|
||||
/// its object.
|
||||
fn see_through_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
fn walk(nodes: &[std::sync::Arc<vectorcraft_doc::Node>], depth: usize, out: &mut Vec<String>) {
|
||||
for n in nodes {
|
||||
let kind = match &n.kind {
|
||||
NodeKind::Layer { clip, .. } => format!("layer clip={clip}"),
|
||||
NodeKind::Group { clip, .. } => format!("group clip={clip}"),
|
||||
NodeKind::Compound { .. } => "compound".into(),
|
||||
NodeKind::Path { clipping, .. } => format!("path clipping={clipping}"),
|
||||
_ => "other".into(),
|
||||
};
|
||||
let b = n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
|
||||
let mask = n.extras().mask.clone();
|
||||
out.push(format!(
|
||||
"{depth} {kind} {:?} {} {b:?} {} {:?} isolate={} {:?} shape={} mask={:?}",
|
||||
n.name,
|
||||
n.visible,
|
||||
(n.opacity * 100.0).round(),
|
||||
n.blend,
|
||||
n.isolate,
|
||||
n.knockout,
|
||||
n.knockout_shape,
|
||||
mask.as_ref().map(|m| (m.clip, m.invert, m.disabled, m.linked))
|
||||
));
|
||||
if let Some(m) = mask {
|
||||
walk(std::slice::from_ref(&m.art), depth + 1, out);
|
||||
}
|
||||
walk(n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(&doc.layers, 0, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// A document of two artboards (the art on the first) with a compound path at 70% in Screen, a
|
||||
/// clipping group at 50% in Multiply, a named group (isolated, knockout on, knockout shape) and a
|
||||
/// square with an opacity mask that doesn't clip on layer `Layer 1`, and layer `Cut` (40%,
|
||||
/// clipping) holding two squares.
|
||||
fn see_through_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let id = |v: serde_json::Value| v["id"].as_u64().unwrap();
|
||||
let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| {
|
||||
id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
|
||||
};
|
||||
// A compound path at 70% in Screen.
|
||||
let (a, b) = (rect(&mut s, 10.0, 10.0, 40.0, 40.0), rect(&mut s, 20.0, 20.0, 20.0, 20.0));
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 70, "blend": "Screen"})).unwrap();
|
||||
// A clipping group at 50% in Multiply.
|
||||
let (art, clip) = (rect(&mut s, 60.0, 10.0, 60.0, 40.0), rect(&mut s, 70.0, 20.0, 30.0, 20.0));
|
||||
s.execute("select.set", &json!({"ids": [art, clip]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50, "blend": "Multiply"})).unwrap();
|
||||
// A named group, isolated, knockout on, whose opacity defines the knockout shape.
|
||||
let (a, b) = (rect(&mut s, 60.0, 60.0, 30.0, 30.0), rect(&mut s, 75.0, 75.0, 30.0, 30.0));
|
||||
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
|
||||
s.execute("object.setProps", &json!({"ids": [g], "name": "Knock", "opacity": 80, "isolate": true, "knockout": "on", "knockoutShape": true}))
|
||||
.unwrap();
|
||||
// A square with an opacity mask that doesn't clip.
|
||||
let masked = rect(&mut s, 130.0, 10.0, 40.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap();
|
||||
let mask = rect(&mut s, 140.0, 20.0, 20.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [masked, mask]})).unwrap();
|
||||
s.execute("transparency.makeOpacityMask", &json!({"clip": false})).unwrap();
|
||||
// A clipping layer at 40%.
|
||||
let cut = id(s.execute("layer.new", &json!({"name": "Cut"})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
rect(&mut s, 10.0, 100.0, 80.0, 60.0);
|
||||
rect(&mut s, 30.0, 110.0, 40.0, 40.0);
|
||||
s.execute("layer.clippingMask.toggle", &json!({})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [cut], "opacity": 40})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The editing copy of `bytes` read alone, checked against its page.
|
||||
fn editing_copy(bytes: &[u8]) -> vectorcraft_doc::Document {
|
||||
let l = load::load_with("art.ai", bytes, &LoadOptions { native: false, ..Default::default() }).unwrap();
|
||||
assert!(l.editing_data && !l.restored, "{:?}", l.warnings);
|
||||
assert!(!l.warnings.iter().any(|w| w.contains("editing data")), "{:?}", l.warnings);
|
||||
l.doc
|
||||
}
|
||||
|
||||
/// `nodes` as the editing copy reads them back: an opacity mask's art that isn't a group comes
|
||||
/// back as a plain group holding it.
|
||||
fn mask_art_grouped(nodes: &mut [std::sync::Arc<vectorcraft_doc::Node>]) {
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
for n in nodes {
|
||||
let n = std::sync::Arc::make_mut(n);
|
||||
if let Some(m) = n.extras_mut().mask.as_mut()
|
||||
&& !matches!(m.art.kind, NodeKind::Group { .. })
|
||||
{
|
||||
let art = m.art.clone();
|
||||
m.art = std::sync::Arc::new(Node::new(art.id, NodeKind::Group { children: vec![art], clip: false }));
|
||||
}
|
||||
if let Some(c) = n.children_mut() {
|
||||
mask_art_grouped(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transparency, a compound path, a clipping group, an opacity mask and a clipping layer come back
|
||||
/// from the editing copy for other apps alone, its page matching it, with every save option that
|
||||
/// writes the copy; the version 7 `.ai` keeps the compound path and the clipping group.
|
||||
#[test]
|
||||
fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
|
||||
let mut s = see_through_session();
|
||||
let mut before = (*s.doc().unwrap().doc).clone();
|
||||
// The mask's art is one path; it reads back as a group holding the path.
|
||||
let mut arts = vec![];
|
||||
before.walk(|n| arts.extend(n.extras().mask.as_ref().map(|m| matches!(m.art.kind, vectorcraft_doc::NodeKind::Path { .. }))));
|
||||
assert_eq!(arts, [true]);
|
||||
mask_art_grouped(&mut before.layers);
|
||||
let want = see_through_outline(&before);
|
||||
for opts in [json!({"format": "ai"}), json!({"format": "ai", "compress": false}), json!({"format": "ai", "pdfCompatible": true})] {
|
||||
let bytes = b64(&s.execute("document.export", &opts).unwrap());
|
||||
assert_eq!(see_through_outline(&editing_copy(&bytes)), want, "{opts}");
|
||||
}
|
||||
// Each artboard in a file of its own: the first holds all the art.
|
||||
let path = tmp("see-through.ai");
|
||||
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(files.len(), 3, "{r}");
|
||||
for f in &files {
|
||||
let copy = editing_copy(&std::fs::read(f).unwrap());
|
||||
if f.ends_with("-2.ai") {
|
||||
assert!(copy.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{f} {:#?}", see_through_outline(©));
|
||||
} else {
|
||||
assert_eq!(see_through_outline(©), want, "{f}");
|
||||
}
|
||||
}
|
||||
// Version 7 has no transparency; it keeps the compound path and the clipping group.
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap();
|
||||
let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap();
|
||||
let kinds = see_through_outline(&legacy.doc);
|
||||
assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}");
|
||||
}
|
||||
@@ -361,3 +361,17 @@ fn damaged_files_are_refused_with_a_message() {
|
||||
assert!(!is_pxr(&bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_pointers_into_the_header_or_table_are_refused() {
|
||||
// Tile data follows the tile pointer table, which ends at byte 520 in a one-tile picture.
|
||||
let rgb = one(head(2, 1, RGB, 2), &[1, 2, 3, 4, 5, 6]);
|
||||
for pointer in [4u32, 511, 512, 519] {
|
||||
let mut inside = rgb.clone();
|
||||
inside[512..516].copy_from_slice(&pointer.to_le_bytes());
|
||||
let e = raster_image(&inside).err().expect("refused").to_string();
|
||||
assert_eq!(e, "the Pixar file's image data is damaged", "a pointer to byte {pointer}");
|
||||
}
|
||||
// A pointer at the table's end reads.
|
||||
assert_eq!(pixels(&rgb), [[1, 2, 3, 255], [4, 5, 6, 255]]);
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color?, keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one with spot color stops in its inks when every other stop is paper white, CMYK or gray; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white or written in CMYK or gray (a CMYK document, or an export that converts colors to a CMYK destination profile, writes RGB and Lab stops in CMYK), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Vector Halftone…",
|
||||
["Object"],
|
||||
None,
|
||||
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
has_selection,
|
||||
halftone
|
||||
)]
|
||||
|
||||
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Layer Options…",
|
||||
["Window", "Layers"],
|
||||
None,
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)",
|
||||
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)",
|
||||
has_doc,
|
||||
artboard_new
|
||||
),
|
||||
@@ -155,7 +155,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Artboard Options…",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}",
|
||||
"{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}",
|
||||
has_doc,
|
||||
artboard_set
|
||||
),
|
||||
@@ -297,7 +297,8 @@ pub(crate) fn make_layer(d: &mut Document, name: Option<&str>) -> Node {
|
||||
NewLayers::of(d).make(d, name)
|
||||
}
|
||||
|
||||
/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case).
|
||||
/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case). A hex color
|
||||
/// with an alpha part (`#rrggbbaa` or `#rgba`) is an error.
|
||||
pub(super) fn layer_color_param(v: &Value) -> std::result::Result<LayerColor, String> {
|
||||
match v {
|
||||
Value::Number(n) => match n.as_u64() {
|
||||
@@ -308,7 +309,13 @@ pub(super) fn layer_color_param(v: &Value) -> std::result::Result<LayerColor, St
|
||||
if let Some(i) = LAYER_COLORS.iter().position(|(name, _)| name.eq_ignore_ascii_case(s.trim())) {
|
||||
return Ok(LayerColor::Preset(i as u8));
|
||||
}
|
||||
let c = vectorcraft_color::Color::from_hex(s).ok_or_else(|| format!("`{s}` is not a colour (#rrggbb or a preset name)"))?;
|
||||
let refused = || format!("`{s}` is not a colour (#rrggbb or a preset name)");
|
||||
// `Color::from_hex` reads `#rrggbbaa` as `#rrggbb`, dropping the alpha.
|
||||
let digits = s.trim();
|
||||
if digits.strip_prefix('#').unwrap_or(digits).len() == 8 {
|
||||
return Err(refused());
|
||||
}
|
||||
let c = vectorcraft_color::Color::from_hex(s).ok_or_else(refused)?;
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
Ok(LayerColor::Custom([r, g, b]))
|
||||
}
|
||||
|
||||
@@ -643,7 +643,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Library",
|
||||
[],
|
||||
None,
|
||||
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
|
||||
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
|
||||
@@ -20,7 +20,7 @@ use super::edit::selected_roots;
|
||||
use super::expand::gradient_sampler;
|
||||
use super::pathops::Beside;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_value, f64_or, f64_req, finite_numbers,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_param, f64_or, f64_req, finite_numbers,
|
||||
has_doc, has_multi, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or,
|
||||
};
|
||||
|
||||
|
||||
@@ -245,7 +245,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Mesh Point Color",
|
||||
[],
|
||||
None,
|
||||
"{id, index | points: [index…] | items: [{id, index | points}…], color?, keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)",
|
||||
"{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)",
|
||||
has_doc,
|
||||
mesh_set_color
|
||||
),
|
||||
@@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Mesh Line",
|
||||
[],
|
||||
None,
|
||||
"{id, x, y, color?, keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
|
||||
"{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}",
|
||||
has_doc,
|
||||
mesh_add_line
|
||||
),
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selec
|
||||
use super::envelope::{outline_of, rows_cols};
|
||||
use super::{
|
||||
Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad,
|
||||
check_numbers, color_value, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param,
|
||||
check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param,
|
||||
};
|
||||
|
||||
// ---------- Gradient mesh ----------
|
||||
@@ -232,7 +232,7 @@ pub(super) fn mesh_set_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let items = point_items(p, C)?;
|
||||
let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let opacity = p.get("opacity").and_then(Value::as_f64);
|
||||
if color.is_none() && opacity.is_none() {
|
||||
return Err(bad(C, "missing `color` or `opacity`"));
|
||||
@@ -283,7 +283,7 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
check_numbers(p, &["tolerance"], C)?;
|
||||
let tol = f64_or(p, "tolerance", 0.0).max(0.0);
|
||||
let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c));
|
||||
let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| {
|
||||
let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?;
|
||||
if let Some(c) = color {
|
||||
|
||||
@@ -115,7 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rasterize…",
|
||||
["Object"],
|
||||
None,
|
||||
"{ppi?, background?: transparent|white|black|\"#rrggbb\", antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
|
||||
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
|
||||
has_selection,
|
||||
rasterize
|
||||
),
|
||||
@@ -347,7 +347,7 @@ fn other_layers(s: &mut Session, lock: bool) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Returns the objects [`super::select::walk_selectable`] visits that are not among the selected objects `roots` and
|
||||
/// hold none of them. A selected layer's objects count as selected. The walk goes into a plain group, but not a Shaper
|
||||
/// hold none of them. A selected layer and its objects count as selected. The walk goes into a plain group, but not a Shaper
|
||||
/// group, that holds a selected object. With `lock`, it also goes into a clip group or compound path that holds one,
|
||||
/// and includes guide paths while `guides_locked`. Without `lock`, guide paths and the objects that hold one are left
|
||||
/// out while `guides_locked`; a clip group, Shaper group, compound path and every other object that holds a selected
|
||||
@@ -360,14 +360,32 @@ fn unselected(
|
||||
guides_locked: bool,
|
||||
lock: bool,
|
||||
) -> Vec<NodeId> {
|
||||
/// Pushes the visible guide paths in `n`, `n` included, locked ones too.
|
||||
fn shown_guides(n: &vectorcraft_doc::Node, out: &mut Vec<NodeId>) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. }) {
|
||||
out.push(n.id);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
shown_guides(c, out);
|
||||
}
|
||||
}
|
||||
let mut roots: HashSet<NodeId> = roots.iter().copied().collect();
|
||||
roots.extend(selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer()).flat_map(|l| l.layer_art(true)));
|
||||
let layers = || selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer());
|
||||
roots.extend(layers().map(|l| l.id));
|
||||
roots.extend(layers().flat_map(|l| l.layer_art(true)));
|
||||
let mut kept: Vec<NodeId> = roots.iter().copied().collect();
|
||||
if guides_locked && !lock {
|
||||
super::select::walk_selectable(d, iso, |n| {
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. }) {
|
||||
kept.push(n.id);
|
||||
}
|
||||
// The walk skips locked objects, so the guide paths in them are looked for here.
|
||||
for c in n.children().into_iter().flatten().filter(|c| c.locked) {
|
||||
shown_guides(c, &mut kept);
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
|
||||
@@ -303,16 +303,30 @@ fn is_effect_color(v: &Value) -> bool {
|
||||
pub(crate) fn check_effect_color(id: &str, effect: &str, params: &Value) -> Result<()> {
|
||||
let key = "color";
|
||||
let Some(v) = params.get(key) else { return Ok(()) };
|
||||
if effect.starts_with(vectorcraft_plugins::effect::PREFIX) {
|
||||
return Ok(());
|
||||
}
|
||||
let takes_color = vectorcraft_render::effects::effect_info(effect).is_some_and(|info| info.defaults.get(key).is_some_and(Value::is_string));
|
||||
if takes_color && !is_effect_color(v) {
|
||||
if effect_takes_color(effect) && !is_effect_color(v) {
|
||||
return Err(bad(id, format!("`{key}` must be a #rrggbb color")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Does built-in effect `effect` have a `color` parameter (one whose default is a string)? Plug-in
|
||||
/// effects have none here.
|
||||
pub(crate) fn effect_takes_color(effect: &str) -> bool {
|
||||
!effect.starts_with(vectorcraft_plugins::effect::PREFIX)
|
||||
&& vectorcraft_render::effects::effect_info(effect).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string))
|
||||
}
|
||||
|
||||
/// The color that built-in effect `effect` draws with `params`: their `color`, else the effect's
|
||||
/// default color. `None` when the effect has no `color` parameter ([`effect_takes_color`]) or
|
||||
/// `params` hold a `color` it can't read ([`is_effect_color`]).
|
||||
pub(crate) fn effect_color(effect: &str, params: &Value) -> Option<vectorcraft_color::Color> {
|
||||
if !effect_takes_color(effect) || params.get("color").is_some_and(|v| !is_effect_color(v)) {
|
||||
return None;
|
||||
}
|
||||
let merged = vectorcraft_render::effects::merged_params(effect, params);
|
||||
Some(vectorcraft_render::effects::color_param(&merged, vectorcraft_color::Color::BLACK))
|
||||
}
|
||||
|
||||
/// The `channel` in `params` of Levels or Curves (`effect`), as command `id` was given it: a
|
||||
/// parameter error naming the channels unless the effect reads it
|
||||
/// ([`vectorcraft_render::effects::is_channel`]); the effect draws any other value as RGB.
|
||||
|
||||
@@ -1189,7 +1189,9 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
|
||||
let with_guides = p.get("guides").and_then(Value::as_bool).unwrap_or(false);
|
||||
let st = s.doc()?;
|
||||
let sel = st.selection.anchors.clone();
|
||||
let segments = st.selection.segments.clone();
|
||||
@@ -1197,6 +1199,10 @@ pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// also catches part of another path must still delete those whole objects.
|
||||
let whole = st.selection.whole();
|
||||
s.edit("Clear", |d, selection| {
|
||||
if with_guides {
|
||||
let gone = selection.guides.clone();
|
||||
d.retain_guides(selection, |i, _| !gone.contains(&i));
|
||||
}
|
||||
let targets: BTreeSet<NodeId> = whole.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.is_layer())).collect();
|
||||
let whole_ids: Vec<NodeId> = targets
|
||||
.iter()
|
||||
|
||||
@@ -185,7 +185,7 @@ impl FilterRun {
|
||||
if let Some(data) = out.document_data {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)));
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
@@ -432,7 +432,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [..] (default: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths are left out): it may change, delete or add objects, as one undo step; the result is selected. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [..] (default: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
|
||||
has_doc,
|
||||
run
|
||||
),
|
||||
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -255,13 +255,14 @@ enum Match {
|
||||
}
|
||||
|
||||
impl Match {
|
||||
/// A colour key, a hex (`#rrggbb`) or a colour value.
|
||||
/// A colour key, a hex (`#rrggbb`) or a colour value. `None` for a hex color with an alpha
|
||||
/// part (`#rrggbbaa` or `#rgba`).
|
||||
fn of(v: &Value) -> Option<Self> {
|
||||
if let Some(s) = v.as_str() {
|
||||
if let Some(k) = ColorKey::parse(s) {
|
||||
return Some(Match::Key(k));
|
||||
}
|
||||
return Color::from_hex(s).map(|c| Match::Hex(c.to_hex()));
|
||||
return Color::from_hex(s).filter(|_| !super::hex_with_alpha(s)).map(|c| Match::Hex(c.to_hex()));
|
||||
}
|
||||
color_value(v).map(|c| Match::Key(ColorKey::of(&c)))
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select by Color",
|
||||
[],
|
||||
None,
|
||||
"{fill?: colour, stroke?: colour (as paint.setFill's color; at least one)} select the objects whose fill (and stroke) reads as that colour in #rrggbb, as document.inspect reports colours, whatever its swatch or tint; with both, the objects that match both. No object needs to be selected first; Select > Reselect repeats it → {count}",
|
||||
"{fill?: colour, stroke?: colour (as paint.setFill's color, #rrggbbaa and #rgba refused; at least one)} select the objects whose fill (and stroke) reads as that colour in #rrggbb, as document.inspect reports colours, whatever its swatch or tint; with both, the objects that match both. No object needs to be selected first; Select > Reselect repeats it → {count}",
|
||||
has_doc,
|
||||
select_color
|
||||
),
|
||||
@@ -321,21 +321,19 @@ fn all_on_artboard(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let i = p.get("artboard").and_then(Value::as_u64).map_or(0, index);
|
||||
let r = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| bad("select.allOnArtboard", "no such artboard"))?;
|
||||
// Symbol instances are measured by their art.
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
st.doc
|
||||
.node(*id)
|
||||
.and_then(|n| n.geometric_bounds_with(&symbols))
|
||||
.is_some_and(|b| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center()))
|
||||
})
|
||||
.collect();
|
||||
let ids: Vec<NodeId> =
|
||||
selectable(&st.doc, st.isolation).into_iter().filter(|id| st.doc.node(*id).is_some_and(|n| on_artboard(n, &symbols, r))).collect();
|
||||
s.select(|_, sel| sel.set(ids.iter().copied()))?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Is `n` on the artboard at `r`, as All on Active Artboard takes it: its geometric bounds (a
|
||||
/// symbol instance's measured by its art) overlap the artboard, or its center is on it.
|
||||
pub(crate) fn on_artboard(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes, r: vectorcraft_geom::Rect) -> bool {
|
||||
n.geometric_bounds_with(symbols).is_some_and(|b| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center()))
|
||||
}
|
||||
|
||||
fn none(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.select(|_, sel| sel.clear())?;
|
||||
ok()
|
||||
@@ -819,8 +817,16 @@ fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn same_layers(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
// The layers or sublayers the selected objects are on (art in their sublayers too).
|
||||
let layers: BTreeSet<NodeId> = st.selection.objects.iter().filter_map(|id| st.doc.layer_containing(*id)).collect();
|
||||
// The layers or sublayers the selected objects are on (art in their sublayers too). A selected
|
||||
// object that `is_selectable` does not accept adds no layer.
|
||||
let locks = st.doc.locked_artboards();
|
||||
let layers: BTreeSet<NodeId> = st
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.filter(|id| is_selectable(&st.doc, st.isolation, &locks, **id))
|
||||
.filter_map(|id| st.doc.layer_containing(*id))
|
||||
.collect();
|
||||
let mut on = BTreeSet::new();
|
||||
for l in layers.iter().filter_map(|l| st.doc.node(*l)) {
|
||||
l.walk(&mut |n| {
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Slice Options…",
|
||||
["Object", "Slice"],
|
||||
None,
|
||||
"{kind?: \"image\"|\"noImage\"|\"htmlText\" (object slices of type only), name?, url?, target?, message?, alt?: (image), text?: cell text; HTML allowed (noImage), background?: \"\"|\"matte\"|\"#rrggbb\", hAlign?: \"default\"|\"left\"|\"center\"|\"right\", vAlign?: \"default\"|\"top\"|\"middle\"|\"baseline\"|\"bottom\"} set the selected slices' options as one undo step; no options: read them → the first slice's {kind, name, url, target, message, alt, text, background, hAlign, vAlign, htmlText: whether HTML Text applies}",
|
||||
"{kind?: \"image\"|\"noImage\"|\"htmlText\" (object slices of type only), name?, url?, target?, message?, alt?: (image), text?: cell text; HTML allowed (noImage), background?: \"\"|\"matte\"|\"#rrggbb\" (#rrggbbaa and #rgba are refused), hAlign?: \"default\"|\"left\"|\"center\"|\"right\", vAlign?: \"default\"|\"top\"|\"middle\"|\"baseline\"|\"bottom\"} set the selected slices' options as one undo step; no options: read them → the first slice's {kind, name, url, target, message, alt, text, background, hAlign, vAlign, htmlText: whether HTML Text applies}",
|
||||
slices_targeted,
|
||||
options
|
||||
),
|
||||
@@ -513,6 +513,7 @@ impl Edits {
|
||||
"" | "none" => Ok(String::new()),
|
||||
"matte" => Ok("matte".to_string()),
|
||||
_ => vectorcraft_color::Color::from_hex(&b)
|
||||
.filter(|_| !super::hex_with_alpha(&b))
|
||||
.map(|c| c.to_hex())
|
||||
.ok_or_else(|| bad(C, "`background` must be \"\", \"matte\" or #rrggbb")),
|
||||
})
|
||||
|
||||
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Swatch",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
has_doc,
|
||||
swatch_new
|
||||
),
|
||||
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
has_doc,
|
||||
swatch_new_group
|
||||
),
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swatch Options",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
has_doc,
|
||||
swatch_edit
|
||||
),
|
||||
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
"{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}",
|
||||
has_doc,
|
||||
swatch_edit_group
|
||||
),
|
||||
@@ -316,7 +316,8 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let colors: Vec<Color> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(color_value).map(|c| super::paint::new_color(s, p, c)).collect())
|
||||
.map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect())
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let from_art = bool_or(p, "fromArtwork", false);
|
||||
let to_global = from_art && bool_or(p, "toGlobal", true);
|
||||
|
||||
@@ -69,6 +69,23 @@ fn apply(s: &mut Session, p: &Value, stops: Vec<TabStop>, label: &str) -> Result
|
||||
let ids = text_targets(s, p, "text.tabs.set")?;
|
||||
let range = TextRange::parse(p, "text.tabs.set")?;
|
||||
let n = stops.len();
|
||||
// A typing session ends here as `s.edit` would end it, whether or not the stops then change:
|
||||
// the typing is its own undo step.
|
||||
if !s.previewing && super::typing_in_progress(s) {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
// Every targeted paragraph already holds these stops: no edit and no undo step.
|
||||
let doc = &s.doc()?.doc;
|
||||
let unchanged = ids.iter().all(|id| match doc.node(*id).map(|node| &node.kind) {
|
||||
Some(NodeKind::Text(t)) => match para_span(range, t) {
|
||||
None => t.para_styles().all(|pa| pa.tabs == stops),
|
||||
Some(mut r) => r.all(|i| t.para_at(i).tabs == stops),
|
||||
},
|
||||
_ => true,
|
||||
});
|
||||
if unchanged {
|
||||
return Ok(json!({ "stops": n }));
|
||||
}
|
||||
s.edit(label, |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
@@ -114,6 +131,60 @@ mod tests {
|
||||
assert_eq!(s.execute("text.tabs.get", &json!({})).unwrap()["stops"], json!([]));
|
||||
}
|
||||
|
||||
/// Setting the stops every targeted paragraph already holds records no undo step. When one
|
||||
/// targeted paragraph holds other stops, the command still sets them all.
|
||||
#[test]
|
||||
fn setting_the_same_stops_records_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb\nc\td"})).unwrap();
|
||||
let stops = json!({"stops": [{"position": 0}, {"position": 20, "leader": "."}]});
|
||||
s.execute("text.tabs.set", &stops).unwrap();
|
||||
let undo = |s: &Session| s.active().unwrap().history.undo.len();
|
||||
let before = undo(&s);
|
||||
s.execute("text.tabs.set", &stops).unwrap();
|
||||
s.execute("text.tabs.set", &json!({"stops": [{"position": 20, "leader": "."}, {"position": 0}]})).unwrap();
|
||||
assert_eq!(undo(&s), before);
|
||||
s.execute("text.tabs.clear", &json!({})).unwrap();
|
||||
s.execute("text.tabs.clear", &json!({})).unwrap();
|
||||
assert_eq!(undo(&s), before + 1);
|
||||
// The second paragraph (bytes 4 on) takes other stops; setting the first paragraph's stops
|
||||
// on both paragraphs changes the second.
|
||||
s.execute("text.tabs.set", &stops).unwrap();
|
||||
s.execute("text.tabs.set", &json!({"stops": [{"position": 50}], "start": 4, "end": 4})).unwrap();
|
||||
let before = undo(&s);
|
||||
s.execute("text.tabs.set", &stops).unwrap();
|
||||
assert_eq!(undo(&s), before + 1);
|
||||
assert_eq!(s.execute("text.tabs.get", &json!({"start": 4})).unwrap()["stops"][1]["position"], json!(20.0));
|
||||
}
|
||||
|
||||
/// Setting the stops the paragraphs already hold, while the Type tool is typing, still ends the
|
||||
/// typing session: the typing is its own undo step, as when the stops change.
|
||||
#[test]
|
||||
fn setting_the_same_stops_ends_the_typing() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
use crate::ViewInfo;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb"})).unwrap()["id"].as_u64().unwrap();
|
||||
let stops = json!({"stops": [{"position": 40}], "ids": [id]});
|
||||
s.execute("text.tabs.set", &stops).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("type", v).unwrap();
|
||||
let b = s.doc().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap();
|
||||
}
|
||||
s.tool_text("!", v).unwrap();
|
||||
assert!(crate::cmd::typing_in_progress(&s));
|
||||
let steps = s.active().unwrap().history.undo.len();
|
||||
s.execute("text.tabs.set", &stops).unwrap();
|
||||
assert!(!crate::cmd::typing_in_progress(&s));
|
||||
let labels: Vec<String> = s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect();
|
||||
assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing")));
|
||||
}
|
||||
|
||||
/// #1877: a leader set the way the Tabs panel sets it fills the tab's gap with its dots.
|
||||
#[test]
|
||||
fn tab_leader_fills_the_gap_with_its_characters() {
|
||||
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
has_doc,
|
||||
set_range_style
|
||||
),
|
||||
@@ -53,6 +53,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
touch_type
|
||||
),
|
||||
cmd!(
|
||||
"text.setGlyphAlternate",
|
||||
"Glyphs",
|
||||
[],
|
||||
None,
|
||||
"{id, start: byte (a character of it), gid: glyph id|null} draw that one character with another glyph of its font as one undo step, what a double-click in the Glyphs panel's Show › Alternates for Current Selection does: gid is one of the glyphs text.glyphAlternates lists for it; its own default glyph, or null, puts the default glyph back. The text keeps the character, and its other attributes do not change. The choice is saved with the character's style and names the face it was made in (PostScript name and version): set in another font or version, or after the font goes missing, the character takes its default glyph; typed characters take their default glyphs. Choosing the glyph the character already draws is not an edit. An error when the character's font is not available, the glyph is not one of its alternates, or the character's style does not draw it (All Caps, Small Caps, another numeral system) → {id, start, end (the character's bytes), gid (the glyph drawn)}",
|
||||
has_doc,
|
||||
set_glyph_alternate
|
||||
),
|
||||
cmd!(
|
||||
query "text.glyphAlternates",
|
||||
"Glyphs",
|
||||
[],
|
||||
None,
|
||||
"{id, start: byte (a character of it)} the alternate glyphs of that character in its font, what the Glyphs panel's Show › Alternates for Current Selection lists: from the font's OpenType GSUB table, the glyphs that single and alternate substitutions put in place of the character's default glyph, `aalt` first, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`, `jalt`, `nalt`, `ornm` and `titl`, each glyph once, the default glyph only when `aalt` lists it → {char, font: family, style: style, default: glyph id, chosen: glyph id (the glyph drawn now), alternates: [{gid, feature}]} (empty when the font has none for it; an error when the character's font is not available)",
|
||||
has_doc,
|
||||
glyph_alternates
|
||||
),
|
||||
cmd!(
|
||||
query "text.getRange",
|
||||
"Get Text Range",
|
||||
@@ -930,8 +948,8 @@ impl CharChange {
|
||||
|
||||
/// Type › Enable Missing Glyph Protection: after a font change, the characters of `runs` their new
|
||||
/// font has no glyph for, but their font `before` the change had, keep that font: its family,
|
||||
/// style, version and Variable Font settings.
|
||||
pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>) {
|
||||
/// style, version and Variable Font settings. Returns the byte ranges that kept their font, in order.
|
||||
pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>) -> Vec<(usize, usize)> {
|
||||
fn chars(runs: &[TextRun]) -> impl Iterator<Item = (usize, char, &CharStyle)> {
|
||||
runs.iter()
|
||||
.scan(0, |at, r| {
|
||||
@@ -963,6 +981,7 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>
|
||||
_ => keep.push((at, end, old)),
|
||||
}
|
||||
}
|
||||
let kept = keep.iter().map(|(a, b, _)| (*a, *b)).collect();
|
||||
for (a, b, old) in keep {
|
||||
edit::style_range(runs, a, b, |st| {
|
||||
st.font_family.clone_from(&old.font_family);
|
||||
@@ -971,6 +990,30 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec<TextRun>
|
||||
st.font_axes.clone_from(&old.font_axes);
|
||||
});
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// The runs of `runs` from byte `a` to `b`, leaving out the ranges `kept` (in order) that Missing
|
||||
/// Glyph Protection gave their earlier font: the characters a font command set its font on.
|
||||
pub(crate) fn unprotected_runs(runs: &[TextRun], a: usize, b: usize, kept: &[(usize, usize)]) -> Vec<TextRun> {
|
||||
let mut out = vec![];
|
||||
let mut at = a;
|
||||
for &(k0, k1) in kept {
|
||||
if k1 <= at {
|
||||
continue;
|
||||
}
|
||||
if k0 >= b {
|
||||
break;
|
||||
}
|
||||
if k0 > at {
|
||||
out.extend(edit::slice_runs(runs, at, k0));
|
||||
}
|
||||
at = k1;
|
||||
}
|
||||
if at < b {
|
||||
out.extend(edit::slice_runs(runs, at, b));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1021,12 +1064,10 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let before = protect.then(|| t.runs.clone());
|
||||
edit::style_range(&mut t.runs, a, b, |st| change.apply(st));
|
||||
if let Some(before) = before {
|
||||
protect_missing_glyphs(&before, &mut t.runs);
|
||||
}
|
||||
let kept = before.map(|before| protect_missing_glyphs(&before, &mut t.runs)).unwrap_or_default();
|
||||
if sets_font {
|
||||
// Empty text has one run, which the empty range styles.
|
||||
let styled = if a == b { t.runs.clone() } else { edit::slice_runs(&t.runs, a, b) };
|
||||
// Empty text has one run, which the empty range styles. Characters that kept their font aren't the command's.
|
||||
let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) };
|
||||
set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style)));
|
||||
}
|
||||
refresh_bounds(t);
|
||||
@@ -1085,6 +1126,144 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve
|
||||
if em > 0.0 { drawn_gap(original).zip(drawn_gap(&base)).map_or(0.0, |(a, b)| (a - b) * 1000.0 / em) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error
|
||||
/// when there is no character there, it is an inline graphic, or its font is not available.
|
||||
fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range<usize>, std::sync::Arc<vectorcraft_text::FontFace>)> {
|
||||
check_numbers(p, &["start"], c)?;
|
||||
let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?;
|
||||
let mut at = 0;
|
||||
for run in &t.runs {
|
||||
let end = at + run.text.len();
|
||||
if (at..end).contains(&start) {
|
||||
let ch = run.text.get(start - at..).and_then(|s| s.chars().next()).ok_or_else(|| bad(c, format!("no character at byte {start}")))?;
|
||||
if run.inline.is_some() {
|
||||
return Err(bad(c, "an inline graphic has no glyphs"));
|
||||
}
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let face = db.style_face(&run.style).filter(|_| db.has_family(&run.style.font_family));
|
||||
let face = face.ok_or_else(|| bad(c, format!("the font {} is not available", run.style.font_family)))?;
|
||||
return Ok((ch, start..start + ch.len_utf8(), face));
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
Err(bad(c, format!("no character at byte {start}")))
|
||||
}
|
||||
|
||||
fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.setGlyphAlternate";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let gid = match p.get("gid") {
|
||||
None => return Err(bad(C, "missing `gid` (a glyph id, or null for the default glyph)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => Some(v.as_u64().and_then(|g| u32::try_from(g).ok()).ok_or_else(|| bad(C, format!("`gid` must be a glyph id, not {v}")))?),
|
||||
};
|
||||
let t = text_ref(s, id)?;
|
||||
let (ch, bytes, face) = glyph_target(&t, p, C)?;
|
||||
let default = face.glyph_for(ch);
|
||||
let holder = t
|
||||
.runs
|
||||
.iter()
|
||||
.scan(0, |at, r| {
|
||||
let start = *at;
|
||||
*at += r.text.len();
|
||||
Some((start..*at, r))
|
||||
})
|
||||
.find(|(bytes_of_run, _)| bytes_of_run.contains(&bytes.start));
|
||||
let styled =
|
||||
holder.as_ref().is_some_and(|(_, r)| r.style.all_caps || (r.style.small_caps.is_some() && ch.is_lowercase()) || r.style.digits.map(ch) != ch);
|
||||
// The glyph the character is drawn with when it holds no choice, drawn alone in its face: a
|
||||
// feature of its style (`salt`, a stylistic set) can draw another glyph than the default one.
|
||||
// The default glyph is then kept as a choice, so that it is drawn. A character that is not laid
|
||||
// out (overflowing text) is shaped alone in its style and writing direction. A character that starts a longer
|
||||
// grapheme (a letter and its combining marks) is drawn in the grapheme's cluster, and is shaped
|
||||
// with the grapheme. Of a cluster of several glyphs (a mark, a vowel sign drawn before the
|
||||
// letter), the character's glyph is its default glyph or one of its alternates.
|
||||
let plain = t.plain_text();
|
||||
let grapheme = plain.get(bytes.start..edit::next_cluster(&plain, bytes.start).max(bytes.end)).map_or_else(|| ch.to_string(), str::to_owned);
|
||||
let listed = face.alternates(ch);
|
||||
let own_glyph = |lay: &vectorcraft_text::TextLayout, at: usize| {
|
||||
let cluster: Vec<u32> = lay
|
||||
.glyphs
|
||||
.iter()
|
||||
.filter(|g| g.byte == at && [bytes.len(), grapheme.len()].contains(&g.len) && g.font_id == face.id())
|
||||
.map(|g| g.gid)
|
||||
.collect();
|
||||
match cluster[..] {
|
||||
[one] => Some(one),
|
||||
_ => cluster.into_iter().find(|&g| g == default || listed.iter().any(|a| a.gid == g)),
|
||||
}
|
||||
};
|
||||
let alone_in_face = |lay: &vectorcraft_text::TextLayout| {
|
||||
let found = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len));
|
||||
found.map(|_| own_glyph(lay, bytes.start))
|
||||
};
|
||||
let unchosen = match holder.as_ref().filter(|_| !styled) {
|
||||
None => None,
|
||||
Some((_, run)) => {
|
||||
let mut probe = t.clone();
|
||||
edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = None);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
alone_in_face(&vectorcraft_text::layout(db, &probe)).unwrap_or_else(|| {
|
||||
let st = CharStyle { glyph_alternate: None, ..run.style.clone() };
|
||||
let mut single = TextObject::point(Point::ZERO, &grapheme, st);
|
||||
single.vertical = t.vertical;
|
||||
own_glyph(&vectorcraft_text::layout(db, &single), 0)
|
||||
})
|
||||
}
|
||||
};
|
||||
let substituted = unchosen.is_some_and(|g| g != default);
|
||||
let choice = match gid.filter(|g| *g != default || substituted) {
|
||||
None => None,
|
||||
Some(g) if g == default || face.alternates(ch).iter().any(|a| a.gid == g) => Some(face.choice(ch, g)),
|
||||
Some(g) => return Err(bad(C, format!("glyph {g} is not an alternate of {ch} in {} {}", face.family, face.style))),
|
||||
};
|
||||
let drawn = choice.as_ref().map_or(unchosen.unwrap_or(default), |c| c.gid);
|
||||
// The run holding the character. The request changes nothing when the choice is the one the
|
||||
// character's run holds and that run holds the character alone; otherwise the edit splits the
|
||||
// run, so that the following text does not take the character into a ligature.
|
||||
let held = holder.as_ref().filter(|(bytes_of_run, _)| bytes_of_run.start == bytes.start).and_then(|(_, r)| r.style.glyph_alternate.clone());
|
||||
let alone = holder.as_ref().is_some_and(|(bytes_of_run, _)| *bytes_of_run == bytes);
|
||||
// A choice that the character's style keeps from being drawn (All Caps, Small Caps, another
|
||||
// numeral system) is an error, not an edit that leaves the page as it was. The style decides
|
||||
// for a character outside its frame too; one that is laid out is checked in the layout.
|
||||
if let Some(c) = &choice {
|
||||
let shown = || {
|
||||
let mut probe = t.clone();
|
||||
edit::style_range(&mut probe.runs, bytes.start, bytes.end, |st| st.glyph_alternate = Some(c.clone()));
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe);
|
||||
lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)).map(|g| g.gid)
|
||||
};
|
||||
if styled || shown().is_some_and(|g| g != c.gid) {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("glyph {} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system)", c.gid),
|
||||
));
|
||||
}
|
||||
}
|
||||
if held == choice && (choice.is_none() || alone) {
|
||||
return Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn}));
|
||||
}
|
||||
s.edit("Glyphs", |d, _| {
|
||||
let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?;
|
||||
edit::style_range(&mut t.runs, bytes.start, bytes.end, |st| st.glyph_alternate = choice.clone());
|
||||
refresh_bounds(t);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"id": id.0, "start": bytes.start, "end": bytes.end, "gid": drawn}))
|
||||
}
|
||||
|
||||
fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.glyphAlternates";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let t = text_ref(s, id)?;
|
||||
let (ch, bytes, face) = glyph_target(&t, p, C)?;
|
||||
let default = face.glyph_for(ch);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
let chosen = lay.glyphs.iter().find(|g| g.byte <= bytes.start && bytes.start < g.byte.saturating_add(g.len)).map_or(default, |g| g.gid);
|
||||
let alternates: Vec<Value> = face.alternates(ch).iter().map(|a| json!({"gid": a.gid, "feature": String::from_utf8_lossy(&a.feature)})).collect();
|
||||
Ok(json!({"char": ch.to_string(), "font": face.family, "style": face.style, "default": default, "chosen": chosen, "alternates": alternates}))
|
||||
}
|
||||
|
||||
fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.touchType";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
@@ -1330,6 +1509,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
check_numbers(p, &["size"], C)?;
|
||||
check_switches(p, &["vertical", "placeholder"], C)?;
|
||||
super::color_param(p, "color", C)?;
|
||||
let style = super::create::new_type_style(s, p);
|
||||
let text = str_param(p, "text").unwrap_or("").to_string();
|
||||
let start = match point_param(p, "at") {
|
||||
|
||||
@@ -51,14 +51,14 @@ const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static st
|
||||
}
|
||||
|
||||
macro_rules! style_cmds {
|
||||
($kind:expr, $p:literal, $menu:literal, $what:literal) => {
|
||||
($kind:expr, $p:literal, $menu:literal, $what:literal, $bounds:literal) => {
|
||||
vec![
|
||||
spec(concat!($p, ".list"), concat!($what, " Styles"), &[], "{} → {styles: [{name, attrs, uses}]}", |s, _| list(s, $kind), false),
|
||||
spec(
|
||||
concat!($p, ".new"),
|
||||
concat!("New ", $what, " Style"),
|
||||
&["Window", "Type", $menu],
|
||||
"{name? (trimmed, as rename trims `to`), attrs?: {…} (default: selected text), id?, start?: byte, end?: byte} → {name}; a nonempty character range samples its first selected character; start alone keeps insertion affinity; paragraph styles sample start",
|
||||
concat!("{name? (trimmed, as rename trims `to`), attrs?: {…} (default: selected text), id?, start?: byte, end?: byte} → {name}; a nonempty character range samples its first selected character; start alone keeps insertion affinity; paragraph styles sample start", $bounds),
|
||||
|s, p| new(s, p, $kind),
|
||||
true,
|
||||
),
|
||||
@@ -82,7 +82,7 @@ macro_rules! style_cmds {
|
||||
concat!($p, ".setAttrs"),
|
||||
concat!($what, " Style Options"),
|
||||
&[],
|
||||
"{name, attrs: {…}} replace the style's attributes; users keep their overrides",
|
||||
concat!("{name, attrs: {…}} replace the style's attributes; users keep their overrides", $bounds),
|
||||
|s, p| set_attrs(s, p, $kind),
|
||||
true,
|
||||
),
|
||||
@@ -116,16 +116,22 @@ macro_rules! style_cmds {
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = style_cmds!(Kind::Char, "charStyle", "Character Styles", "Character");
|
||||
let mut v = style_cmds!(
|
||||
Kind::Char,
|
||||
"charStyle",
|
||||
"Character Styles",
|
||||
"Character",
|
||||
"; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt"
|
||||
);
|
||||
v.push(spec(
|
||||
"charStyle.edit",
|
||||
"Edit Character Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides",
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt",
|
||||
|s, p| edit_style(s, p, Kind::Char),
|
||||
true,
|
||||
));
|
||||
v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph"));
|
||||
v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph", ""));
|
||||
v
|
||||
}
|
||||
|
||||
@@ -155,6 +161,8 @@ fn to_attrs<T: Serialize>(v: &T) -> Map<String, Value> {
|
||||
/// from a style instead leaves the text's own value alone.
|
||||
pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
|
||||
let mut m = to_attrs(v);
|
||||
// A chosen glyph belongs to one character, not to a reusable character style.
|
||||
m.remove("glyphAlternate");
|
||||
for (k, x) in [
|
||||
("font_version", json!(v.font_version)),
|
||||
("fontAxes", json!(v.font_axes)),
|
||||
@@ -270,11 +278,9 @@ fn restyle<T: Serialize + DeserializeOwned + Clone>(
|
||||
new: &Map<String, Value>,
|
||||
base: &Map<String, Value>,
|
||||
) -> T {
|
||||
let Some(full) = to_map(cur) else { return cur.clone() };
|
||||
let mut m = attrs(cur);
|
||||
if let Some(name) = full.get("style_name") {
|
||||
m.insert("style_name".into(), name.clone());
|
||||
}
|
||||
// Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept.
|
||||
let Some(mut m) = to_map(cur) else { return cur.clone() };
|
||||
m.extend(attrs(cur));
|
||||
for (k, v) in new {
|
||||
if old.get(k).is_none_or(|o| m.get(k) == Some(o)) {
|
||||
m.insert(k.clone(), v.clone());
|
||||
@@ -492,8 +498,27 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
let c = kind.cmd(verb);
|
||||
let full = match kind {
|
||||
Kind::Char => {
|
||||
if m.contains_key("glyphAlternate") {
|
||||
return Err(bad(&c, "`glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it)"));
|
||||
}
|
||||
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
|
||||
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
|
||||
for (key, value, lo, hi) in
|
||||
[("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)]
|
||||
{
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) {
|
||||
return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto"));
|
||||
}
|
||||
let shift_max = 1296.0;
|
||||
for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] {
|
||||
if changed(key) && !(-shift_max..=shift_max).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max)));
|
||||
}
|
||||
}
|
||||
// A language of the list, stored as its tag (as text.setFormat takes it).
|
||||
if let Some(l) = &st.language
|
||||
&& kept.and_then(|k| k.get("language")) != m.get("language")
|
||||
|
||||
@@ -1,5 +1,42 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn captured_character_style_excludes_a_one_character_glyph_choice() {
|
||||
let style = CharStyle {
|
||||
glyph_alternate: Some(vectorcraft_doc::GlyphChoice { ch: 'a', gid: 42, font: "Test-Regular".into(), version: "1".into() }),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!char_attrs(&style).contains_key("glyphAlternate"));
|
||||
assert!(style.glyph_alternate.is_some(), "the selected text keeps its direct glyph choice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_style_edit_keeps_a_linked_runs_glyph_choice() {
|
||||
let (mut s, id) = session_with_text("Styled");
|
||||
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap();
|
||||
s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap();
|
||||
let choice = vectorcraft_doc::GlyphChoice { ch: 'S', gid: 42, font: "Test-Regular".into(), version: "1".into() };
|
||||
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(NodeId(id)).map(|n| &mut n.kind) {
|
||||
t.runs[0].style.glyph_alternate = Some(choice.clone());
|
||||
}
|
||||
s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"size": 18}})).unwrap();
|
||||
let run = &runs(&s, id)[0];
|
||||
assert_eq!((run.style.style_name.as_deref(), run.style.size), (Some("Body"), 18.0));
|
||||
assert_eq!(run.style.glyph_alternate, Some(choice), "the style edit keeps the run's own glyph choice");
|
||||
}
|
||||
|
||||
/// A glyph choice given to a character style is an error, not a value the style drops.
|
||||
#[test]
|
||||
fn character_style_attributes_refuse_a_glyph_choice() {
|
||||
let (mut s, _) = session_with_text("Styled");
|
||||
let choice = json!({"ch": "S", "gid": 42, "font": "Test-Regular", "version": "1"});
|
||||
let err = s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24, "glyphAlternate": choice}})).unwrap_err();
|
||||
assert!(err.to_string().contains("glyphAlternate"), "{err}");
|
||||
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24}})).unwrap();
|
||||
let err = s.execute("charStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": {"glyphAlternate": choice}})).unwrap_err();
|
||||
assert!(err.to_string().contains("glyphAlternate"), "{err}");
|
||||
}
|
||||
|
||||
fn session_with_text(text: &str) -> (Session, u64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
@@ -335,6 +372,54 @@ fn character_style_color_and_features_are_checked() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for attrs in [
|
||||
json!({"size": 0.0}),
|
||||
json!({"size": 1296.1}),
|
||||
json!({"leading": 0.0}),
|
||||
json!({"leading": 5000.1}),
|
||||
json!({"h_scale": 0.0}),
|
||||
json!({"h_scale": 0.9}),
|
||||
json!({"h_scale": 10000.1}),
|
||||
json!({"v_scale": 0.0}),
|
||||
json!({"v_scale": 0.9}),
|
||||
json!({"v_scale": 10000.1}),
|
||||
json!({"baseline_shift": -1296.1}),
|
||||
json!({"baseline_shift": 1296.1}),
|
||||
json!({"tcyUpDown": 1296.1}),
|
||||
json!({"tcyLeftRight": -1296.1}),
|
||||
] {
|
||||
let key = attrs.as_object().unwrap().keys().next().unwrap();
|
||||
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
|
||||
let params = match cmd {
|
||||
"charStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}),
|
||||
"charStyle.new" => json!({"name": "Other", "attrs": attrs}),
|
||||
_ => json!({"name": "Body", "attrs": attrs}),
|
||||
};
|
||||
let error = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("`{key}`")), "{cmd} {attrs}: {error}");
|
||||
}
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
|
||||
s.execute(
|
||||
"charStyle.setAttrs",
|
||||
&json!({"name": "Body", "attrs": {
|
||||
"size": 1296.0, "leading": 5000.0,
|
||||
"h_scale": 1.0, "v_scale": 10000.0,
|
||||
"baseline_shift": -1296.0,
|
||||
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_style_rejects_doubly_signed_feature_tags() {
|
||||
let (mut s, id) = session_with_text("Text");
|
||||
@@ -776,7 +861,8 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() {
|
||||
}
|
||||
|
||||
/// The same for character styles: Auto kerning and the Roman baseline alignment, which the
|
||||
/// run's JSON leaves out, are captured and reach the style's users.
|
||||
/// run's JSON leaves out, are captured and reach the style's users. A glyph choice belongs to
|
||||
/// one character, so it is not a reusable style attribute.
|
||||
#[test]
|
||||
fn char_style_redefined_to_the_defaults_updates_its_text() {
|
||||
use vectorcraft_doc::CharAlign;
|
||||
@@ -794,9 +880,11 @@ fn char_style_redefined_to_the_defaults_updates_its_text() {
|
||||
s.execute("text.setFormat", &json!({"ids": [source], "kerning": "auto", "charAlign": "romanBaseline"})).unwrap();
|
||||
s.execute("charStyle.redefine", &json!({"name": "Body", "id": source})).unwrap();
|
||||
assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3]));
|
||||
assert_eq!(defined(&s, 0), settable::<CharStyle>(), "Redefine captures every attribute");
|
||||
let mut reusable = settable::<CharStyle>();
|
||||
reusable.remove("glyphAlternate");
|
||||
assert_eq!(defined(&s, 0), reusable, "Redefine captures every reusable attribute");
|
||||
s.execute("charStyle.new", &json!({"name": "Copy", "id": local})).unwrap();
|
||||
assert_eq!(defined(&s, 1), settable::<CharStyle>(), "New captures every attribute");
|
||||
assert_eq!(defined(&s, 1), reusable, "New captures every reusable attribute");
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"kerning": 10, "charAlign": "emBoxTop"}})).unwrap();
|
||||
assert_eq!((kerning(&s), aligns(&s)), ([Some(10.0), Some(10.0), Some(60.0)], [CharAlign::EmBoxTop; 3]));
|
||||
s.execute("charStyle.setAttrs", &json!({"name": "Body", "attrs": {"charAlign": "romanBaseline"}})).unwrap();
|
||||
|
||||
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
@@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
has_doc,
|
||||
set_style
|
||||
),
|
||||
@@ -874,16 +874,16 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.features = super::textedit::change_features(&st.features, c);
|
||||
}
|
||||
});
|
||||
if let Some(before) = before {
|
||||
super::textedit::protect_missing_glyphs(&before, &mut t.runs);
|
||||
}
|
||||
let kept = before.map(|before| super::textedit::protect_missing_glyphs(&before, &mut t.runs)).unwrap_or_default();
|
||||
if font.is_some() || style.is_some() {
|
||||
// All the text: every run, the one run of empty text included.
|
||||
// All the text: every run, the one run of empty text included. Characters that kept their font aren't the
|
||||
// command's.
|
||||
let styled = match range {
|
||||
None => t.runs.clone(),
|
||||
None if kept.is_empty() => t.runs.clone(),
|
||||
None => super::textedit::unprotected_runs(&t.runs, 0, vectorcraft_text::edit::runs_len(&t.runs), &kept),
|
||||
Some(r) => {
|
||||
let (a, b) = r.bytes(t);
|
||||
vectorcraft_text::edit::slice_runs(&t.runs, a, b)
|
||||
super::textedit::unprotected_runs(&t.runs, a, b, &kept)
|
||||
}
|
||||
};
|
||||
set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style)));
|
||||
@@ -1080,46 +1080,74 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let t = area_text(s.doc()?.doc.node(first)).ok_or_else(|| bad(C, "select area type (text in a frame)"))?;
|
||||
area_options_json(t)
|
||||
};
|
||||
// Checked once up front (its errors don't depend on the frame); each frame resolves `fit`
|
||||
// against its own setting below.
|
||||
let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default();
|
||||
let fit = fit_param(p, cur.fit, C)?;
|
||||
let mut v = serde_json::to_value(&cur).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
fit_param(p, cur.fit, C)?;
|
||||
let fit_given = p.get("fit").is_some_and(|v| !v.is_null()) || p.get("fitMinPercent").is_some_and(|v| !v.is_null());
|
||||
let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0));
|
||||
let (w, mut h) = (size("width"), size("height"));
|
||||
let mut changed = w.is_some() || h.is_some() || fit.is_some();
|
||||
if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) {
|
||||
for (k, val) in src.iter().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())) {
|
||||
o.insert(k.clone(), val.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
let (w, h) = (size("width"), size("height"));
|
||||
let given: Vec<(&String, &Value)> = p.as_object().into_iter().flatten().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())).collect();
|
||||
if w.is_none() && h.is_none() && !fit_given && given.is_empty() {
|
||||
return options(s);
|
||||
}
|
||||
let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?;
|
||||
opts.rows = opts.rows.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS);
|
||||
opts.columns = opts.columns.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS);
|
||||
let finite = |x: f64| if x.is_finite() { x } else { 0.0 };
|
||||
opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0);
|
||||
// A gutter given alone is the rows' and the columns'.
|
||||
if p.get("gutter").is_some() && p.get("rowGutter").is_none() {
|
||||
opts.row_gutter = None;
|
||||
}
|
||||
opts.row_gutter = opts.row_gutter.map(|g| finite(g).clamp(0.0, 10_000.0)).filter(|g| *g != opts.gutter);
|
||||
opts.inset = finite(opts.inset).clamp(0.0, 10_000.0);
|
||||
opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0);
|
||||
opts.fit = fit.unwrap_or(cur.fit);
|
||||
if opts.fit == AreaFit::AutoHeight {
|
||||
// Each area type takes the options given over its own (#3759): setting one option on several
|
||||
// frames leaves their other options as they were.
|
||||
let merged = |own: &vectorcraft_doc::AreaOptions| -> Result<vectorcraft_doc::AreaOptions> {
|
||||
let mut v = serde_json::to_value(own).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
for (k, val) in &given {
|
||||
o.insert((*k).clone(), (*val).clone());
|
||||
}
|
||||
}
|
||||
let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?;
|
||||
opts.rows = opts.rows.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS);
|
||||
opts.columns = opts.columns.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS);
|
||||
let finite = |x: f64| if x.is_finite() { x } else { 0.0 };
|
||||
opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0);
|
||||
// A gutter given alone is the rows' and the columns'.
|
||||
if p.get("gutter").is_some() && p.get("rowGutter").is_none() {
|
||||
opts.row_gutter = None;
|
||||
}
|
||||
opts.row_gutter = opts.row_gutter.map(|g| finite(g).clamp(0.0, 10_000.0)).filter(|g| *g != opts.gutter);
|
||||
opts.inset = finite(opts.inset).clamp(0.0, 10_000.0);
|
||||
opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0);
|
||||
// Each frame's fit from its own (`fitMinPercent` alone changes only Shrink Text frames).
|
||||
opts.fit = fit_param(p, own.fit, C)?.unwrap_or(own.fit);
|
||||
Ok(opts)
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let planned: Vec<(NodeId, vectorcraft_doc::AreaOptions)> = ids
|
||||
.iter()
|
||||
.filter_map(|id| area_text(d.node(*id)).map(|t| (*id, &t.area)))
|
||||
.map(|(id, own)| merged(own).map(|o| (id, o)))
|
||||
.collect::<Result<_>>()?;
|
||||
let apply = |t: &mut TextObject, opts: &vectorcraft_doc::AreaOptions| {
|
||||
t.area = opts.clone();
|
||||
// Auto Size sets the height (Illustrator's dialog turns the Height field off).
|
||||
h = None;
|
||||
let h = if opts.fit == AreaFit::AutoHeight { None } else { h };
|
||||
// A resized frame has laid its text out again; otherwise the new options do here.
|
||||
if !size_area(t, w, h) {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
};
|
||||
// Options that change nothing (the vertical alignment already set, `fitMinPercent` on frames
|
||||
// without Shrink Text) add no undo step and keep redo, frame sizes and Auto Size included.
|
||||
let unchanged = planned.iter().all(|(id, opts)| match d.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => {
|
||||
let mut after = t.clone();
|
||||
apply(&mut after, opts);
|
||||
after == *t
|
||||
}
|
||||
_ => true,
|
||||
});
|
||||
if unchanged {
|
||||
return options(s);
|
||||
}
|
||||
s.edit("Area Type Options", |d, _| {
|
||||
for id in &ids {
|
||||
for (id, opts) in &planned {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
t.area = opts.clone();
|
||||
// A resized frame has laid its text out again; otherwise the new options do here.
|
||||
if !size_area(t, w, h) {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
apply(t, opts);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -1762,3 +1762,46 @@ fn area_options_set_a_gutter_between_rows_of_its_own() {
|
||||
s.execute("text.areaOptions", &json!({"rowGutter": null})).unwrap();
|
||||
assert_eq!(area(&s).row_gutter, None);
|
||||
}
|
||||
|
||||
/// #3759: an option given for several area types goes onto each one's own options: the others
|
||||
/// stay as each had them, not copied from the first.
|
||||
#[test]
|
||||
fn area_options_for_several_frames_change_only_what_is_given() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let make = |s: &mut Session, x: f64| {
|
||||
s.execute("text.create", &json!({"x": x, "y": 10, "text": "A", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let (a, b) = (make(&mut s, 10.0), make(&mut s, 200.0));
|
||||
s.execute("text.areaOptions", &json!({"ids": [a], "columns": 3, "gutter": 6})).unwrap();
|
||||
s.execute("text.areaOptions", &json!({"ids": [b], "inset": 4})).unwrap();
|
||||
s.execute("text.areaOptions", &json!({"ids": [a, b], "verticalAlign": "bottom"})).unwrap();
|
||||
let area = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.area.clone(),
|
||||
k => panic!("{k:?}"),
|
||||
};
|
||||
let (oa, ob) = (area(&s, a), area(&s, b));
|
||||
assert_eq!((oa.vertical_align, ob.vertical_align), (vectorcraft_doc::VerticalAlign::Bottom, vectorcraft_doc::VerticalAlign::Bottom));
|
||||
assert_eq!((oa.columns, oa.gutter, oa.inset), (3, 6.0, 0.0));
|
||||
assert_eq!((ob.columns, ob.inset), (1, 4.0), "b keeps its own options");
|
||||
}
|
||||
|
||||
/// `fitMinPercent` alone changes only the frames that shrink text to fit, each from its own
|
||||
/// setting (#3759).
|
||||
#[test]
|
||||
fn fit_min_percent_for_several_frames_keeps_each_frames_fit() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let make = |s: &mut Session, x: f64| {
|
||||
s.execute("text.create", &json!({"x": x, "y": 10, "text": "A", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let (plain, shrink) = (make(&mut s, 10.0), make(&mut s, 200.0));
|
||||
s.execute("text.areaOptions", &json!({"ids": [shrink], "fit": "shrinkText"})).unwrap();
|
||||
s.execute("text.areaOptions", &json!({"ids": [plain, shrink], "fitMinPercent": 30})).unwrap();
|
||||
let fit = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.area.fit,
|
||||
k => panic!("{k:?}"),
|
||||
};
|
||||
assert_eq!(fit(&s, plain), vectorcraft_doc::AreaFit::None, "the plain frame doesn't start shrinking");
|
||||
assert_eq!(fit(&s, shrink), vectorcraft_doc::AreaFit::ShrinkText { min_percent: 30.0 });
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -329,6 +329,7 @@ impl ColorTable {
|
||||
list.iter()
|
||||
.map(|h| {
|
||||
vectorcraft_color::Color::from_hex(h)
|
||||
.filter(|_| !super::hex_with_alpha(h))
|
||||
.map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Sample Color",
|
||||
[],
|
||||
None,
|
||||
"{color, stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
|
||||
"{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it",
|
||||
has_doc,
|
||||
sample_color
|
||||
),
|
||||
|
||||
@@ -318,6 +318,16 @@ impl DocState {
|
||||
_ => it.selection,
|
||||
};
|
||||
self.push_undo(it.label, it.doc, selection);
|
||||
if let Some(paints) = it.color_mode_paints
|
||||
&& let Some(e) = self.history.undo.last_mut()
|
||||
{
|
||||
match &mut e.color_mode_paints {
|
||||
Some((_, after)) => *after = paints.1,
|
||||
slot => *slot = Some(paints),
|
||||
}
|
||||
e.recost_paints();
|
||||
self.history.trim();
|
||||
}
|
||||
self.revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ pub struct HistoryEntry {
|
||||
pub doc: Arc<Document>,
|
||||
/// The selection as it was, shared with the neighbouring steps that have the same one.
|
||||
pub selection: Arc<Selection>,
|
||||
/// Roughly the memory this step keeps of its own: what of `doc` the step after it (or the
|
||||
/// document now) doesn't share ([`Document::retained_bytes`]).
|
||||
/// Roughly the memory this step keeps of its own: the unshared document data
|
||||
/// ([`Document::retained_bytes`]) plus owned color-mode paint snapshots.
|
||||
pub bytes: usize,
|
||||
/// The same the other way round: what that next state keeps that `doc` doesn't share. Undoing
|
||||
/// (redoing) this step makes a step that keeps the next state: this is its `bytes`.
|
||||
@@ -19,6 +19,10 @@ pub struct HistoryEntry {
|
||||
next: usize,
|
||||
/// The template and name `label` was made from ([`Session::edit_named`]).
|
||||
pub(crate) named: Option<NamedStep>,
|
||||
/// Original and converted new-art colors, only for steps that change document color mode.
|
||||
pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>,
|
||||
/// Owned new-art snapshots included in both directional estimates.
|
||||
color_mode_bytes: usize,
|
||||
}
|
||||
|
||||
/// A step name made by filling the `{name}` placeholder of a template with a name
|
||||
@@ -45,7 +49,17 @@ impl HistoryEntry {
|
||||
pub(crate) fn kept(label: String, doc: Arc<Document>, selection: Arc<Selection>, next: &Document) -> Self {
|
||||
doc.drop_lookup_cache();
|
||||
let (bytes, next_bytes) = doc.retained_bytes_each(next);
|
||||
HistoryEntry { label, doc, selection, bytes, next_bytes, next: std::ptr::from_ref(next) as usize, named: None }
|
||||
HistoryEntry {
|
||||
label,
|
||||
doc,
|
||||
selection,
|
||||
bytes,
|
||||
next_bytes,
|
||||
next: std::ptr::from_ref(next) as usize,
|
||||
named: None,
|
||||
color_mode_paints: None,
|
||||
color_mode_bytes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The template and name the step's label was made from, while the label is still the one
|
||||
@@ -66,12 +80,42 @@ impl HistoryEntry {
|
||||
return Self::kept(label, doc, selection, now);
|
||||
}
|
||||
doc.drop_lookup_cache();
|
||||
HistoryEntry { label, doc, selection, bytes: costs.next_bytes, next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None }
|
||||
HistoryEntry {
|
||||
label,
|
||||
doc,
|
||||
selection,
|
||||
bytes: costs.next_bytes,
|
||||
next_bytes: costs.bytes,
|
||||
next: Arc::as_ptr(now) as usize,
|
||||
named: None,
|
||||
color_mode_paints: None,
|
||||
color_mode_bytes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The figures [`HistoryEntry::turned`] reuses.
|
||||
/// Recount the separately owned paints after a color-mode step or group changes them.
|
||||
pub(crate) fn recost_paints(&mut self) {
|
||||
let owned = |p: &vectorcraft_tools::PaintDefaults| {
|
||||
std::mem::size_of::<vectorcraft_tools::PaintDefaults>()
|
||||
+ vectorcraft_doc::paint_heap_bytes(&p.fill)
|
||||
+ vectorcraft_doc::paint_heap_bytes(&p.stroke)
|
||||
+ p.appearance.as_ref().map_or(0, vectorcraft_doc::appearance_heap_bytes)
|
||||
+ p.style.as_ref().map_or(0, String::capacity)
|
||||
};
|
||||
let bytes = self.color_mode_paints.as_ref().map_or(0, |(before, after)| owned(before).saturating_add(owned(after)));
|
||||
self.bytes = self.bytes.saturating_sub(self.color_mode_bytes).saturating_add(bytes);
|
||||
self.next_bytes = self.next_bytes.saturating_sub(self.color_mode_bytes).saturating_add(bytes);
|
||||
self.color_mode_bytes = bytes;
|
||||
}
|
||||
|
||||
/// The document-only figures [`HistoryEntry::turned`] reuses. Its paint snapshots are
|
||||
/// attached and counted separately, so swapping direction never doubles their cost.
|
||||
pub(crate) fn costs(&self) -> StepCosts {
|
||||
StepCosts { bytes: self.bytes, next_bytes: self.next_bytes, next: self.next }
|
||||
StepCosts {
|
||||
bytes: self.bytes.saturating_sub(self.color_mode_bytes),
|
||||
next_bytes: self.next_bytes.saturating_sub(self.color_mode_bytes),
|
||||
next: self.next,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,7 +184,9 @@ impl History {
|
||||
/// merged into it, or an undo group extended it).
|
||||
pub(crate) fn recost_last(&mut self, now: &Document) {
|
||||
if let Some(e) = self.undo.last_mut() {
|
||||
(e.bytes, e.next_bytes) = e.doc.retained_bytes_each(now);
|
||||
let (before, after) = e.doc.retained_bytes_each(now);
|
||||
e.bytes = before.saturating_add(e.color_mode_bytes);
|
||||
e.next_bytes = after.saturating_add(e.color_mode_bytes);
|
||||
e.next = std::ptr::from_ref(now) as usize;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,13 @@ pub struct Interaction {
|
||||
/// The selection the previews start from (shared, so a preview frame copies nothing).
|
||||
pub selection: Arc<Selection>,
|
||||
pub preview: Option<(String, Value)>,
|
||||
/// A replaced or canceled preview restores these new-art paints from before the interaction.
|
||||
pub(crate) paint: vectorcraft_tools::PaintDefaults,
|
||||
/// An accepted batch preview uses these final paints after changing the document color mode.
|
||||
pub(crate) preview_paint: Option<vectorcraft_tools::PaintDefaults>,
|
||||
/// Conversion of new-art paints waits until a color-mode preview is accepted.
|
||||
pub(crate) deferred_color_mode: Option<crate::cmd::colormgmt::DeferredColorMode>,
|
||||
pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>,
|
||||
/// Per-document state restored on cancel (current layer, highlighted Layers panel rows,
|
||||
/// isolation).
|
||||
pub active_layer: Option<NodeId>,
|
||||
@@ -53,6 +60,8 @@ pub(crate) struct PreviewCopies {
|
||||
/// An open undo group ([`Session::begin_undo_group`]): the edits made in it are one undo step.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UndoGroup {
|
||||
/// The new-art paints from before the group's first command.
|
||||
pub(crate) paint: vectorcraft_tools::PaintDefaults,
|
||||
/// The document before the group's first edit, as the undo step that edit recorded keeps it.
|
||||
pub(crate) first: Option<Arc<Document>>,
|
||||
/// The numbers of the journal entries made in the group's document while it was open: a canceled
|
||||
@@ -83,4 +92,8 @@ pub struct UndoScope {
|
||||
/// that the group's undo step keeps, as they were when the scope began; `None` when the scope
|
||||
/// opened the group.
|
||||
pub(crate) joined: Option<(Arc<Document>, Selection, Option<Arc<Document>>)>,
|
||||
/// The new-art colors and the group's color-mode history metadata at the scope's start.
|
||||
/// Only used when cancelling a joined scope that converted those colors.
|
||||
pub(crate) paint: vectorcraft_tools::PaintDefaults,
|
||||
pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>,
|
||||
}
|
||||
@@ -157,6 +157,10 @@ pub struct Session {
|
||||
/// groups: for each step, the documents ([`DocState::uid`]) whose undo groups it belongs to, and
|
||||
/// the index of the document it left active when it changed the active document.
|
||||
pub(crate) batch_steps: Option<Vec<(Vec<u64>, Option<usize>)>>,
|
||||
/// After `command.batch` kept a color-mode step's new-art colors, until the top-level command
|
||||
/// has inherited the selection's appearance: the documents ([`DocState::uid`]) whose newest
|
||||
/// history step takes the colors the batch finally left.
|
||||
pub(crate) batch_paint_docs: Vec<u64>,
|
||||
/// While [`Session::place_read`] runs `file.place`: the file read for it, which the command
|
||||
/// places instead of reading the file; `None` otherwise.
|
||||
pub(crate) place_hand_off: Option<cmd::place::PlaceRead>,
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
//! update, or answering No, leaves the link modified until the file changes again.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -27,8 +28,21 @@ use crate::{Result, Session};
|
||||
pub type Stamp = (u64, u128);
|
||||
|
||||
/// Stamps of a document's linked files taken on a worker thread: (document uid, [(file,
|
||||
/// object ids, stamp)]).
|
||||
pub type LinkScan = Arc<Mutex<Option<(u64, Vec<(String, Vec<u64>, Option<Stamp>)>)>>>;
|
||||
/// object ids, stamp)]), the condition the worker signals when it ends, and whether it has.
|
||||
pub type LinkScan = Arc<(Mutex<Option<(u64, Vec<(String, Vec<u64>, Option<Stamp>)>)>>, Condvar, AtomicBool)>;
|
||||
|
||||
/// Held by a look's worker: marks the look as ended and wakes [`Session::wait_link_scan`] when
|
||||
/// dropped, whether the worker returned or unwound.
|
||||
struct Ended(LinkScan);
|
||||
|
||||
impl Drop for Ended {
|
||||
fn drop(&mut self) {
|
||||
let (done, finished, ended) = &*self.0;
|
||||
let _held = done.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
ended.store(true, Ordering::SeqCst);
|
||||
finished.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// The stamp of the linked file stored as `path` in the document saved at `doc_path`; `None` when
|
||||
/// there is no file, its path isn't followed ([`crate::cmd::fileio::document_path`]) or
|
||||
@@ -79,12 +93,14 @@ impl Session {
|
||||
let out = slot.clone();
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || {
|
||||
// Marks the look as ended when the worker returns or unwinds.
|
||||
let _ended = Ended(out.clone());
|
||||
let stamps = scope.run(|| {
|
||||
crate::file_access::confine(crate::file_access::current().or(opened_by).as_ref(), || {
|
||||
files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect()
|
||||
})
|
||||
});
|
||||
*out.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps));
|
||||
*out.0.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps));
|
||||
});
|
||||
if spawned.is_ok() {
|
||||
self.link_scan = Some(slot);
|
||||
@@ -94,11 +110,21 @@ impl Session {
|
||||
/// Apply a finished look (`None` while there is none, or it is still running): see
|
||||
/// [`Session::apply_link_stamps`].
|
||||
pub fn poll_link_scan(&mut self) -> Option<Result<Value>> {
|
||||
let (uid, stamps) = self.link_scan.as_ref()?.lock().unwrap_or_else(PoisonError::into_inner).take()?;
|
||||
let (uid, stamps) = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?;
|
||||
self.link_scan = None;
|
||||
Some(self.apply_link_stamps(uid, stamps, false))
|
||||
}
|
||||
|
||||
/// Block until the look in flight has ended (at once when none is running), so that the next
|
||||
/// [`Session::poll_link_scan`] applies its stamps. A look whose worker stopped without stamps
|
||||
/// ends too, and the poll then returns `None`. For tests that drive the look step by step.
|
||||
pub fn wait_link_scan(&self) {
|
||||
let Some(scan) = &self.link_scan else { return };
|
||||
let (done, finished, ended) = &**scan;
|
||||
let guard = done.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
drop(finished.wait_while(guard, |stamps| stamps.is_none() && !ended.load(Ordering::SeqCst)).unwrap_or_else(PoisonError::into_inner));
|
||||
}
|
||||
|
||||
/// Compare the stamps of document `uid`'s linked files with the ones last seen and act on
|
||||
/// the changed ones as Update Links says (`update`: read them again regardless). Returns
|
||||
/// `{updated: [ids], ask: [ids], modified: [ids]}`: read again, to offer (Ask When Modified),
|
||||
|
||||
@@ -77,6 +77,7 @@ impl Session {
|
||||
explicit_undo_group: None,
|
||||
batch_stash: None,
|
||||
batch_steps: None,
|
||||
batch_paint_docs: Vec::new(),
|
||||
place_hand_off: None,
|
||||
queue_hand_off: None,
|
||||
place_queue_roots: None,
|
||||
|
||||
@@ -225,6 +225,7 @@ impl Session {
|
||||
cmd::settle_interaction(self)?;
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
let paint = self.paint.clone();
|
||||
let st = self.doc_mut()?;
|
||||
if st.interaction.is_some() {
|
||||
return Ok(());
|
||||
@@ -234,6 +235,10 @@ impl Session {
|
||||
doc: st.doc.clone(),
|
||||
selection: Arc::new(st.selection.clone()),
|
||||
preview: None,
|
||||
paint,
|
||||
preview_paint: None,
|
||||
color_mode_paints: None,
|
||||
deferred_color_mode: None,
|
||||
active_layer: st.active_layer,
|
||||
layer_rows: st.layer_rows.clone(),
|
||||
variables_highlight: st.variables_highlight.clone(),
|
||||
@@ -246,10 +251,10 @@ impl Session {
|
||||
|
||||
/// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview).
|
||||
pub fn preview(&mut self, cmd: &str, params: &Value) -> Result<Value> {
|
||||
{
|
||||
let (paint, restore_paint) = {
|
||||
let menu = self.menu.clone();
|
||||
let st = self.doc_mut()?;
|
||||
let Some(it) = &st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) };
|
||||
let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) };
|
||||
// Undoing the previous preview counts as a change, so views redraw even when the command
|
||||
// below returns without an edit.
|
||||
let selection_changed = st.selection != *it.selection;
|
||||
@@ -257,6 +262,11 @@ impl Session {
|
||||
st.revision += 1;
|
||||
}
|
||||
st.doc = it.doc.clone();
|
||||
let restore_paint = cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch");
|
||||
let paint = it.paint.clone();
|
||||
it.preview_paint = None;
|
||||
it.color_mode_paints = None;
|
||||
it.deferred_color_mode = None;
|
||||
if selection_changed {
|
||||
st.selection.clone_from(&it.selection);
|
||||
}
|
||||
@@ -264,30 +274,54 @@ impl Session {
|
||||
// even when the preview fails.
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
cmd::globaledit::follow_history(st);
|
||||
(paint, restore_paint)
|
||||
};
|
||||
if restore_paint {
|
||||
self.paint = paint.clone();
|
||||
}
|
||||
// The previous preview's paint is undone with it.
|
||||
self.pending_paint = None;
|
||||
let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params));
|
||||
let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p));
|
||||
// A selected object's converted appearance must not replace the current paints while
|
||||
// this tentative color-mode preview is still cancellable.
|
||||
let color_mode_paint = matches!(cmd, "file.documentColorMode" | "object.convertDocumentColorMode").then(|| self.paint.clone());
|
||||
let outer = std::mem::replace(&mut self.previewing, true);
|
||||
let r = self.execute(cmd, params);
|
||||
self.previewing = outer;
|
||||
if let Some(paint) = color_mode_paint {
|
||||
self.paint = paint;
|
||||
}
|
||||
let params = self.noted(params);
|
||||
let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone());
|
||||
let st = self.doc_mut()?;
|
||||
if let Some(it) = &mut st.interaction {
|
||||
// A failed preview leaves the document at the snapshot, so nothing is left to commit
|
||||
// (not even an earlier successful preview, which the reset above already undid).
|
||||
it.preview = r.is_ok().then(|| (cmd.to_string(), params));
|
||||
if it.color_mode_paints.is_some() {
|
||||
it.preview_paint = batch_paint.clone();
|
||||
}
|
||||
}
|
||||
if batch_paint.is_some() && self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.preview_paint.is_some()) {
|
||||
self.paint = paint;
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
pub fn commit_interaction(&mut self) -> Result<()> {
|
||||
self.clear_deferred_overlay_cache();
|
||||
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
|
||||
self.paint = paint;
|
||||
}
|
||||
self.remember_pending_paint();
|
||||
cmd::colormgmt::commit_new_art_colors(self)?;
|
||||
let paint = self.paint.clone();
|
||||
let st = self.doc_mut()?;
|
||||
let Some(mut it) = st.interaction.take() else { return Ok(()) };
|
||||
let Some(preview) = it.preview.take() else { return Ok(()) };
|
||||
if let Some((_, after)) = &mut it.color_mode_paints {
|
||||
after.clone_from(&paint);
|
||||
}
|
||||
let perspective_again = it.perspective_again.take();
|
||||
let copy = preview.0 == "object.transform" && preview.1.get("copy").and_then(Value::as_bool).unwrap_or(false);
|
||||
// Alt pressed or released during a move drag turns it into a copy or back: name it for
|
||||
@@ -353,6 +387,14 @@ impl Session {
|
||||
pub fn cancel_interaction(&mut self) -> Result<()> {
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.pending_paint = None;
|
||||
if let Some(paint) = self
|
||||
.active()
|
||||
.and_then(|st| st.interaction.as_ref())
|
||||
.filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch"))
|
||||
.map(|it| it.paint.clone())
|
||||
{
|
||||
self.paint = paint;
|
||||
}
|
||||
let menu = self.menu.clone();
|
||||
let st = self.doc_mut()?;
|
||||
st.undo_interaction();
|
||||
|
||||
@@ -107,9 +107,31 @@ impl Session {
|
||||
let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs());
|
||||
let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::<Vec<_>>());
|
||||
let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) };
|
||||
if r.is_err() && self.depth == 0 {
|
||||
self.batch_paint_docs.clear();
|
||||
}
|
||||
let r = r?;
|
||||
if self.depth == 0 {
|
||||
self.inherit_new_art();
|
||||
// A color-mode history step restores exact new-art colors; selection inheritance
|
||||
// must not immediately replace that restoration.
|
||||
let restored = self.active().is_some_and(|d| match id {
|
||||
"edit.undo" => d.history.redo.last().is_some_and(|e| e.color_mode_paints.is_some()),
|
||||
"edit.redo" => d.history.undo.last().is_some_and(|e| e.color_mode_paints.is_some()),
|
||||
_ => false,
|
||||
});
|
||||
if !restored {
|
||||
self.inherit_new_art();
|
||||
}
|
||||
for uid in std::mem::take(&mut self.batch_paint_docs) {
|
||||
if let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid)
|
||||
&& let Some(e) = st.history.undo.last_mut()
|
||||
&& let Some((_, after)) = &mut e.color_mode_paints
|
||||
{
|
||||
after.clone_from(&self.paint);
|
||||
e.recost_paints();
|
||||
st.history.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(open) = open {
|
||||
self.open_undo_groups_in_new_documents(&open);
|
||||
|
||||
@@ -13,10 +13,11 @@ impl Session {
|
||||
|
||||
/// [`Session::begin_undo_group`] with the undo step named `label` (else after its first edit).
|
||||
pub fn begin_named_undo_group(&mut self, label: Option<String>) {
|
||||
let paint = self.paint.clone();
|
||||
if let Some(st) = self.active_mut()
|
||||
&& st.undo_group.is_none()
|
||||
{
|
||||
st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label });
|
||||
st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,9 +28,10 @@ impl Session {
|
||||
/// entry that made the document stays.
|
||||
pub(super) fn open_undo_groups_in_new_documents(&mut self, open: &[u64]) {
|
||||
let Some(label) = &self.explicit_undo_group else { return };
|
||||
let paint = self.paint.clone();
|
||||
for st in &mut self.docs {
|
||||
if !open.contains(&st.uid) && st.undo_group.is_none() {
|
||||
st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone() });
|
||||
st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,12 +93,26 @@ impl Session {
|
||||
continue;
|
||||
}
|
||||
let Some(g) = st.undo_group.take() else { continue };
|
||||
// Redo of a group that changed document color mode restores the new-art colors the
|
||||
// whole group left, not the ones right after the conversion.
|
||||
if !cancel
|
||||
&& let Some(first) = &g.first
|
||||
&& let Some(e) = st.history.undo.last_mut().filter(|e| Arc::ptr_eq(&e.doc, first))
|
||||
&& let Some((_, after)) = &mut e.color_mode_paints
|
||||
{
|
||||
after.clone_from(&self.paint);
|
||||
e.recost_paints();
|
||||
st.history.trim();
|
||||
}
|
||||
// Only while the group's step is still the newest one.
|
||||
if cancel
|
||||
&& let Some(first) = g.first
|
||||
&& st.history.undo.last().is_some_and(|e| Arc::ptr_eq(&e.doc, &first))
|
||||
&& let Some(e) = st.history.undo.pop()
|
||||
{
|
||||
if let Some((before, _)) = e.color_mode_paints {
|
||||
self.paint = before;
|
||||
}
|
||||
st.doc = e.doc;
|
||||
st.selection = Arc::unwrap_or_clone(e.selection);
|
||||
deselect_hidden(&self.menu, &st.doc, &mut st.selection);
|
||||
@@ -194,11 +210,17 @@ impl Session {
|
||||
let journal = self.journal.len();
|
||||
let st = self.active()?;
|
||||
let uid = st.uid;
|
||||
let color_mode_paints = st
|
||||
.undo_group
|
||||
.as_ref()
|
||||
.and_then(|g| g.first.as_ref())
|
||||
.and_then(|first| st.history.undo.last().filter(|e| Arc::ptr_eq(&e.doc, first)).and_then(|e| e.color_mode_paints.clone()));
|
||||
let paint = self.paint.clone();
|
||||
let joined = st.undo_group.as_ref().map(|g| (st.doc.clone(), st.selection.clone(), g.first.clone()));
|
||||
if joined.is_none() {
|
||||
self.begin_undo_group();
|
||||
}
|
||||
Some(UndoScope { uid, journal, joined })
|
||||
Some(UndoScope { uid, journal, joined, paint, color_mode_paints })
|
||||
}
|
||||
|
||||
/// End `scope` in its own document, whichever document is active now; undo groups open in other
|
||||
@@ -219,13 +241,19 @@ impl Session {
|
||||
if !cancel || !newest {
|
||||
return;
|
||||
}
|
||||
let colors_changed = st.history.undo.last().and_then(|e| e.color_mode_paints.as_ref()) != scope.color_mode_paints.as_ref();
|
||||
match &first {
|
||||
// The scope's first edit recorded the group's step.
|
||||
None => {
|
||||
st.history.undo.pop();
|
||||
g.first = None;
|
||||
}
|
||||
Some(f) if g.first.as_ref().is_some_and(|now| Arc::ptr_eq(now, f)) => {}
|
||||
Some(f) if g.first.as_ref().is_some_and(|now| Arc::ptr_eq(now, f)) => {
|
||||
if let Some(e) = st.history.undo.last_mut() {
|
||||
e.color_mode_paints = scope.color_mode_paints;
|
||||
e.recost_paints();
|
||||
}
|
||||
}
|
||||
Some(_) => return,
|
||||
}
|
||||
st.doc = doc;
|
||||
@@ -235,6 +263,9 @@ impl Session {
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
st.history.recost_last(&st.doc);
|
||||
st.revision += 1;
|
||||
if colors_changed {
|
||||
self.paint = scope.paint;
|
||||
}
|
||||
self.journal.truncate(scope.journal);
|
||||
// The next commands take the cut entries' numbers, so no open undo group keeps them.
|
||||
for g in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) {
|
||||
|
||||
@@ -67,6 +67,7 @@ mod gradient;
|
||||
mod gradpanel;
|
||||
mod gradpresets;
|
||||
mod gradspan;
|
||||
mod guide_clipboard;
|
||||
mod halftone;
|
||||
mod history_mem;
|
||||
mod ids_without_selection;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Node};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, Node};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -288,8 +288,8 @@ fn add_fill_and_stroke_copy_the_top_ones() {
|
||||
assert_eq!(node(&s, id).appearance.items.len(), 3);
|
||||
}
|
||||
|
||||
/// With a fill row active, Add New Fill puts a copy of that row right above it and makes the copy
|
||||
/// the active row; the rows above it stay where they are.
|
||||
/// With a fill row active, Add New Fill puts a fill with that row's paint right above it and makes
|
||||
/// the new fill the active row; the rows above it stay where they are.
|
||||
#[test]
|
||||
fn add_fill_copies_the_active_fill_row_right_above_it() {
|
||||
let mut s = session();
|
||||
@@ -323,8 +323,60 @@ fn add_fill_copies_the_active_fill_row_right_above_it() {
|
||||
assert_eq!(s.appearance_item(), Some(0));
|
||||
}
|
||||
|
||||
/// With a fill row active, Add New Fill given `id` alone also puts a copy of the top fill on top,
|
||||
/// and the active row stays.
|
||||
#[test]
|
||||
fn add_fill_with_id_leaves_the_active_fill_row_alone() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0);
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "appearance.setItem", json!({"index": 2, "color": "#0000ff"})); // [red, Stroke, blue]
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "appearance.addFill", json!({"id": id.0}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "stroke", "fill", "fill"]);
|
||||
assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
|
||||
assert_eq!(fill_paint(&n, 3).color().unwrap().to_hex(), "#0000ff");
|
||||
assert_eq!(s.appearance_item(), Some(0));
|
||||
}
|
||||
|
||||
/// Add New Stroke copies the top stroke's weight but makes the new stroke at least 1 pt.
|
||||
#[test]
|
||||
fn add_stroke_is_at_least_one_point() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0);
|
||||
run(&mut s, "stroke.set", json!({"weight": 0.5}));
|
||||
run(&mut s, "appearance.addStroke", json!({})); // [Fill, Stroke, Stroke]
|
||||
let n = node(&s, id);
|
||||
assert_eq!(stroke(&n, 1).width, 0.5);
|
||||
assert_eq!(stroke(&n, 2).width, 1.0);
|
||||
}
|
||||
|
||||
/// The new fill above the active fill row takes only the row's paint: the row's opacity, blend
|
||||
/// mode, visibility, overprint and effects are not copied (Duplicate Item copies those).
|
||||
#[test]
|
||||
fn add_fill_takes_only_the_active_fill_rows_paint() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0);
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "appearance.setItem", json!({"index": 0, "opacity": 40, "blend": "multiply", "visible": false}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.roughen", "item": 0}));
|
||||
run(&mut s, "object.setOverprint", json!({"fill": true, "item": 0}));
|
||||
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "fill", "stroke"]);
|
||||
let (AppearanceItem::Fill(row), AppearanceItem::Fill(copy)) = (&n.appearance.items[0], &n.appearance.items[1]) else {
|
||||
panic!("the first two rows are not fills")
|
||||
};
|
||||
assert_eq!((row.opacity, row.blend, row.visible, row.overprint), (0.4, BlendMode::Multiply, false, true));
|
||||
assert_eq!(row.effects.len(), 1);
|
||||
assert_eq!(copy, &FillLayer::new(row.paint.clone()));
|
||||
}
|
||||
|
||||
/// In a mixed selection the active fill row goes above itself in the first object; an object that
|
||||
/// doesn't share that row gets a copy of its top fill on top, as without an active row.
|
||||
/// doesn't share that row gets a fill with its top fill's paint on top, as without an active row.
|
||||
#[test]
|
||||
fn add_fill_above_an_unshared_active_row_tops_the_other_objects() {
|
||||
let mut s = session();
|
||||
@@ -463,6 +515,45 @@ fn reduce_to_basic_keeps_the_active_row_of_the_first_selected_object() {
|
||||
assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#0000ff");
|
||||
}
|
||||
|
||||
/// Three objects with equal stacks, the third's lower fill changed; the lower, green fill row of
|
||||
/// the first is active, selected a, b, c.
|
||||
fn three_with_one_changed(s: &mut Session) -> [NodeId; 3] {
|
||||
let ids = [rect(s, 50.0), rect(s, 200.0), rect(s, 300.0)];
|
||||
run(s, "select.set", json!({"ids": ids.map(|id| id.0)}));
|
||||
run(s, "appearance.addFill", json!({}));
|
||||
run(s, "appearance.setItem", json!({"index": 0, "color": "#00ff00"}));
|
||||
run(s, "appearance.setItem", json!({"index": 2, "color": "#ff0000"})); // [Fill green, Stroke, Fill red]
|
||||
run(s, "appearance.setItem", json!({"index": 0, "color": "#0000ff", "ids": [ids[2].0]}));
|
||||
run(s, "appearance.setActiveItem", json!({"index": 0}));
|
||||
ids
|
||||
}
|
||||
|
||||
/// The active row is matched in each other object on its own: one object without an equal row
|
||||
/// does not stop another that has one from keeping it.
|
||||
#[test]
|
||||
fn reduce_to_basic_keeps_the_active_row_in_each_object_that_has_it() {
|
||||
let mut s = session();
|
||||
let [a, b, c] = three_with_one_changed(&mut s);
|
||||
run(&mut s, "appearance.reduceToBasic", json!({}));
|
||||
assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#00ff00");
|
||||
assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00");
|
||||
assert_eq!(fill_paint(&node(&s, c), 0).color().unwrap().to_hex(), "#ff0000");
|
||||
}
|
||||
|
||||
/// Add New Fill puts its copy of the active row right above that row in each object that has an
|
||||
/// equal row, even when another selected object has none.
|
||||
#[test]
|
||||
fn add_fill_copies_the_active_row_in_each_object_that_has_it() {
|
||||
let mut s = session();
|
||||
let [a, b, _] = three_with_one_changed(&mut s);
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
for id in [a, b] {
|
||||
let n = node(&s, id);
|
||||
assert_eq!(fill_paint(&n, 1).color().unwrap().to_hex(), "#00ff00", "{:?}", n.appearance);
|
||||
assert_eq!(fill_paint(&n, 3).color().unwrap().to_hex(), "#ff0000", "{:?}", n.appearance);
|
||||
}
|
||||
}
|
||||
|
||||
/// b `[Fill red, Fill white, Stroke]` above a `[Fill white, Stroke]`, selected b first: b's rows 1
|
||||
/// and 2 equal a's rows 0 and 1.
|
||||
fn reversed_pair(s: &mut Session) -> (NodeId, NodeId) {
|
||||
|
||||
@@ -77,7 +77,7 @@ fn area_options_set_and_report_the_fit() {
|
||||
let n = undo_len(&s);
|
||||
let again = s.execute("text.areaOptions", &q).unwrap();
|
||||
assert_eq!(again, q);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(undo_len(&s), n, "options that change nothing add no undo step");
|
||||
// Undo back to no fit.
|
||||
while text(&s, id).area.fit != AreaFit::None {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
@@ -1405,6 +1405,26 @@ fn symbolism_adjustments() {
|
||||
assert!(s.execute("symbol.adjust", &json!({"tool": "nope", "points": at})).is_err());
|
||||
}
|
||||
|
||||
/// The Symbol Stainer's `color` with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes
|
||||
/// nothing, rather than staining with the current fill; `#rrggbb` still stains with it.
|
||||
#[test]
|
||||
fn a_stain_color_with_an_alpha_part_is_refused() {
|
||||
let mut s = session();
|
||||
let (inst, _, b) = make_symbol(&mut s);
|
||||
let c = b.center();
|
||||
let at = json!([[c.x, c.y]]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for bad in ["#ff000080", "ff000080", "#f008"] {
|
||||
assert!(s.execute("symbol.adjust", &json!({"tool": "stain", "points": at, "color": bad, "intensity": 10})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(*s.doc().unwrap().doc, *before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
s.execute("symbol.adjust", &json!({"tool": "stain", "points": at, "color": "#ff0000", "intensity": 10})).unwrap();
|
||||
let f = node(&s, inst).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(f.paint.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
|
||||
}
|
||||
|
||||
/// In a CMYK document the Symbol Stainer's RGB `color` separates through the color settings, as
|
||||
/// `paint.setFill` stores it.
|
||||
#[test]
|
||||
|
||||
@@ -2244,6 +2244,25 @@ fn live_paint_gap_detection_stops_paint_at_a_gap() {
|
||||
assert!(node(&s, g).extras().live_paint_gaps.is_none());
|
||||
}
|
||||
|
||||
/// A Gap Preview Color with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes nothing;
|
||||
/// `#rrggbb` and a layer color's name still set it.
|
||||
#[test]
|
||||
fn a_gap_color_with_an_alpha_part_is_refused() {
|
||||
let mut s = session();
|
||||
let g = live_square_with_a_gap(&mut s);
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
for bad in ["#00ff0080", "00ff0080", "#0f08"] {
|
||||
let err = s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": bad})).unwrap_err().to_string();
|
||||
assert!(err.contains(&format!("`{bad}` is not a colour (#rrggbb or a preset name)")), "{bad}: {err}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
|
||||
assert_eq!(gap_options(&s, g).color, [0xff, 0x4f, 0x4f]);
|
||||
s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": "#00ff00"})).unwrap();
|
||||
assert_eq!(gap_options(&s, g).color, [0, 0xff, 0]);
|
||||
s.execute("livePaint.gapOptions", &json!({"id": g.0, "color": "Green"})).unwrap();
|
||||
assert_eq!(gap_options(&s, g).color, [0x4f, 0xff, 0x4f]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medium_and_large_gaps_stop_paint_at_wider_gaps() {
|
||||
// Squares whose ends stop 5 pt and 9 pt short of their starts: each size closes the gaps up
|
||||
|
||||
@@ -114,6 +114,149 @@ fn swatch_links_survive_mode_conversion() {
|
||||
assert_eq!(color, sw, "object and swatch converted identically");
|
||||
}
|
||||
|
||||
/// The process color the active color settings give `c` in CMYK (the default intent).
|
||||
fn to_cmyk(c: Color) -> Color {
|
||||
let cms = cms::active();
|
||||
cms.convert(&c, cms::Model::Cmyk, cms.settings().intent)
|
||||
}
|
||||
|
||||
/// A document with colors that no 8-bit hex value holds: a plain fill, a three-stop gradient, a
|
||||
/// pattern fill, a global swatch on one object's fill and at a 50% tint on another's stroke, and a
|
||||
/// spot swatch on a third object → (session, plain, gradient, patterned, the swatch's two users,
|
||||
/// the spot user).
|
||||
fn reusable_paints_document() -> (Session, [NodeId; 6]) {
|
||||
let mut s = session();
|
||||
let plain = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(Color::rgb(0.123_457, 0.765_432, 0.333_333)));
|
||||
let grad = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!("#000000"));
|
||||
let stops = json!([
|
||||
{"offset": 0, "color": Color::rgb(0.912_345, 0.1, 0.2)},
|
||||
{"offset": 0.37, "color": Color::rgb(0.2, 0.876_543, 0.3)},
|
||||
{"offset": 1, "color": Color::rgb(0.3, 0.4, 0.654_321)},
|
||||
]);
|
||||
s.execute("paint.setFill", &json!({"ids": [grad.0], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
|
||||
let tile = rect(&mut s, 40.0, 0.0, 10.0, 10.0, json!(Color::rgb(0.6, 0.111_111, 0.9)));
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile.0], "name": "Odd Tile", "edit": false})).unwrap();
|
||||
let patterned = rect(&mut s, 60.0, 0.0, 10.0, 10.0, json!("#000000"));
|
||||
s.execute("paint.setFill", &json!({"ids": [patterned.0], "swatch": "Odd Tile"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Shared", "color": Color::rgb(0.271_937, 0.314_773, 0.583_119), "global": true})).unwrap();
|
||||
let filled = rect(&mut s, 0.0, 20.0, 10.0, 10.0, json!("#000000"));
|
||||
s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Shared"})).unwrap();
|
||||
let stroked = rect(&mut s, 20.0, 20.0, 10.0, 10.0, json!("#000000"));
|
||||
s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Shared", "tint": 50})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Spot Lab", "color": Color::Lab { l: 61.5, a: 42.25, b: -17.75 }, "global": true})).unwrap();
|
||||
s.execute("swatch.setSpot", &json!({"name": "Spot Lab"})).unwrap();
|
||||
let spot = rect(&mut s, 40.0, 20.0, 10.0, 10.0, json!("#000000"));
|
||||
s.execute("paint.setFill", &json!({"ids": [spot.0], "swatch": "Spot Lab"})).unwrap();
|
||||
(s, [plain, grad, patterned, filled, stroked, spot])
|
||||
}
|
||||
|
||||
/// RGB → CMYK → Undo gives back the document bit for bit (no conversion back through the
|
||||
/// profile), and Redo gives back the converted one.
|
||||
#[test]
|
||||
fn rgb_cmyk_undo_restores_every_color_exactly() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (mut s, _) = reusable_paints_document();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let converted = s.doc().unwrap().doc.clone();
|
||||
assert_ne!(*converted, *before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one Undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *converted);
|
||||
}
|
||||
|
||||
/// Each stop of a gradient converts on its own and keeps its offset.
|
||||
#[test]
|
||||
fn rgb_cmyk_converts_each_gradient_stop() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (mut s, [_, grad, ..]) = reusable_paints_document();
|
||||
let Paint::Gradient(old) = fill_of(&s, grad) else { panic!("not a gradient") };
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let Paint::Gradient(new) = fill_of(&s, grad) else { panic!("not a gradient") };
|
||||
assert_eq!(new.gradient.stops.len(), 3);
|
||||
for (o, n) in old.gradient.stops.iter().zip(&new.gradient.stops) {
|
||||
assert_eq!(n.offset, o.offset);
|
||||
assert!(matches!(n.color, Color::Cmyk { .. }), "{:?}", n.color);
|
||||
assert_eq!(n.color, to_cmyk(o.color));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern's tile art converts, and the art filled with the pattern keeps it.
|
||||
#[test]
|
||||
fn rgb_cmyk_converts_a_pattern_tile() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (mut s, [_, _, patterned, ..]) = reusable_paints_document();
|
||||
let tile = |s: &Session| s.doc().unwrap().doc.pattern("Odd Tile").unwrap().art[0].appearance.fill_paint().color().unwrap();
|
||||
let old = tile(&s);
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
assert!(matches!(tile(&s), Color::Cmyk { .. }), "{:?}", tile(&s));
|
||||
assert_eq!(tile(&s), to_cmyk(old));
|
||||
assert!(matches!(fill_of(&s, patterned), Paint::Pattern { ref pattern, .. } if pattern == "Odd Tile"), "{:?}", fill_of(&s, patterned));
|
||||
}
|
||||
|
||||
/// A global swatch used in two places converts once: both uses keep the link and take the
|
||||
/// converted swatch color (the 50% tint at that tint), not a conversion of their own.
|
||||
#[test]
|
||||
fn rgb_cmyk_converts_a_shared_swatch_once() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (mut s, [.., filled, stroked, _]) = reusable_paints_document();
|
||||
let shared = |s: &Session| s.doc().unwrap().doc.swatch("Shared").unwrap().paint.color().unwrap();
|
||||
let old = shared(&s);
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let new = shared(&s);
|
||||
assert_eq!(new, to_cmyk(old));
|
||||
assert_eq!(fill_of(&s, filled), Paint::Solid { color: new, swatch: Some("Shared".into()), tint: 1.0 });
|
||||
let stroke = s.doc().unwrap().doc.node(stroked).unwrap().appearance.stroke_paint();
|
||||
assert_eq!(stroke, Paint::Solid { color: new.tinted(0.5), swatch: Some("Shared".into()), tint: 0.5 });
|
||||
}
|
||||
|
||||
/// A spot color defined in Lab stays a spot color: its Lab definition, its link and its own
|
||||
/// plate are kept.
|
||||
#[test]
|
||||
fn rgb_cmyk_keeps_a_spot_color() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (mut s, [.., spot]) = reusable_paints_document();
|
||||
let swatch = |s: &Session| s.doc().unwrap().doc.swatch("Spot Lab").unwrap().clone();
|
||||
let (old_swatch, old_fill) = (swatch(&s), fill_of(&s, spot));
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
assert_eq!(swatch(&s), old_swatch);
|
||||
assert!(swatch(&s).spot);
|
||||
assert_eq!(fill_of(&s, spot), old_fill);
|
||||
let plates = s.execute("color.plates", &json!({})).unwrap();
|
||||
assert!(plates["plates"].as_array().unwrap().iter().any(|p| p["name"] == "Spot Lab"), "{plates}");
|
||||
}
|
||||
|
||||
/// A spot color defined in RGB stays a spot color with its own plate, and its definition
|
||||
/// converts like any other swatch: the fill that uses it and a 40% tint stroke both take the
|
||||
/// converted definition.
|
||||
#[test]
|
||||
fn rgb_cmyk_converts_an_rgb_spot_definition() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Spot RGB", "color": Color::rgb(0.812_345, 0.234_567, 0.456_789), "global": true})).unwrap();
|
||||
s.execute("swatch.setSpot", &json!({"name": "Spot RGB"})).unwrap();
|
||||
let filled = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!("#000000"));
|
||||
s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Spot RGB"})).unwrap();
|
||||
let stroked = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!("#000000"));
|
||||
s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Spot RGB", "tint": 40})).unwrap();
|
||||
let swatch = |s: &Session| s.doc().unwrap().doc.swatch("Spot RGB").unwrap().clone();
|
||||
let old = swatch(&s).paint.color().unwrap();
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let sw = swatch(&s);
|
||||
assert!(sw.spot);
|
||||
let new = sw.paint.color().unwrap();
|
||||
assert!(matches!(new, Color::Cmyk { .. }), "{new:?}");
|
||||
assert_eq!(new, to_cmyk(old));
|
||||
assert_eq!(fill_of(&s, filled), Paint::Solid { color: new, swatch: Some("Spot RGB".into()), tint: 1.0 });
|
||||
let stroke = s.doc().unwrap().doc.node(stroked).unwrap().appearance.stroke_paint();
|
||||
assert_eq!(stroke, Paint::Solid { color: new.tinted(0.4), swatch: Some("Spot RGB".into()), tint: 0.4 });
|
||||
let plates = s.execute("color.plates", &json!({})).unwrap();
|
||||
assert!(plates["plates"].as_array().unwrap().iter().any(|p| p["name"] == "Spot RGB" && p["spot"] == true), "{plates}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gamut_check_flags_unprintable_colours() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -128,6 +271,10 @@ fn gamut_check_flags_unprintable_colours() {
|
||||
let r = s.execute("color.gamutCheck", &json!({"colors": ["#00ff00", {"c": 100, "m": 0, "y": 0, "k": 0}]})).unwrap();
|
||||
assert_eq!(r["checked"], 2);
|
||||
assert_eq!(r["outOfGamut"].as_array().unwrap().len(), 1);
|
||||
// A color it can't read, a hex color with an alpha part included, is an error, not skipped.
|
||||
for bad in ["#0000ff80", "nope"] {
|
||||
assert!(s.execute("color.gamutCheck", &json!({"colors": ["#00ff00", bad]})).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Copying and pasting ruler guides (#3226): selected guides go on the clipboard with the objects
|
||||
//! or alone, and paste into another document or onto another artboard.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// The active document's guides: (vertical, pos, layer).
|
||||
fn guides(s: &Session) -> Vec<(bool, f64, Option<NodeId>)> {
|
||||
s.doc().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos, g.layer)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruler_guides_copy_and_paste_into_another_document() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
run(&mut s, "guide.add", json!({"vertical": true, "pos": 120}));
|
||||
run(&mut s, "guide.add", json!({"vertical": false, "pos": 80}));
|
||||
run(&mut s, "guide.select", json!({"indexes": [0, 1]}));
|
||||
let r = run(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!(r["guides"], 2);
|
||||
// Into another document: the same places, on its current layer, selected, one undo step.
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = run(&mut s, "edit.paste", json!({}));
|
||||
assert_eq!(r["guides"], 2);
|
||||
assert_eq!(guides(&s), [(true, 120.0, Some(layer)), (false, 80.0, Some(layer))], "where they were, not offset");
|
||||
assert_eq!(s.doc().unwrap().selection.guides, [0, 1]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(guides(&s).is_empty());
|
||||
// With an object, they move as it does (Paste offsets it by the Paste Offset preference).
|
||||
run(&mut s, "document.activate", json!({"index": 0}));
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [rect]}));
|
||||
run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "document.activate", json!({"index": 1}));
|
||||
run(&mut s, "edit.paste", json!({"dx": 5, "dy": 7}));
|
||||
assert_eq!(guides(&s).iter().map(|g| (g.0, g.1)).collect::<Vec<_>>(), [(true, 125.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_paste_in_place_onto_another_artboard_and_cut_removes_them() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100, "artboards": 2}));
|
||||
let [a, b] = [0, 1].map(|i| s.doc().unwrap().doc.artboards[i].rect);
|
||||
run(&mut s, "guide.add", json!({"vertical": true, "pos": a.x0 + 30.0}));
|
||||
run(&mut s, "guide.select", json!({"indexes": [0]}));
|
||||
// Cut takes the guide away and keeps it on the clipboard.
|
||||
run(&mut s, "edit.cut", json!({}));
|
||||
assert!(guides(&s).is_empty());
|
||||
// Paste in Place onto the second artboard: 30 pt into it.
|
||||
run(&mut s, "edit.pasteInPlace", json!({"artboard": 1}));
|
||||
assert_eq!(guides(&s).iter().map(|g| g.1).collect::<Vec<_>>(), [b.x0 + 30.0]);
|
||||
// Paste on All Artboards: one on each.
|
||||
run(&mut s, "edit.pasteOnAllArtboards", json!({}));
|
||||
let mut at: Vec<f64> = guides(&s).iter().map(|g| g.1).collect();
|
||||
at.sort_by(f64::total_cmp);
|
||||
assert_eq!(at, [a.x0 + 30.0, b.x0 + 30.0, b.x0 + 30.0]);
|
||||
// Cut with an object and a guide selected takes both away, in one undo step.
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap();
|
||||
let before = guides(&s).len();
|
||||
run(&mut s, "select.set", json!({"ids": [rect]}));
|
||||
run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
run(&mut s, "edit.cut", json!({}));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none());
|
||||
assert_eq!(guides(&s).len(), before - 1, "the selected guide goes too");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
// Cut with direct-selected anchors and a guide: the anchors and the guide go, one undo step.
|
||||
let path = run(&mut s, "shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "guide.add", json!({"vertical": false, "pos": 90}));
|
||||
let n = guides(&s).len();
|
||||
run(&mut s, "select.anchors", json!({"id": path, "anchors": [[0, 0]], "mode": "set"}));
|
||||
run(&mut s, "guide.select", json!({"indexes": [n - 1], "toggle": true}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
run(&mut s, "edit.cut", json!({}));
|
||||
assert_eq!(guides(&s).len(), n - 1, "the guide goes with the anchors");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
// Nothing selected: Copy is off.
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(s.execute("edit.copy", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// #3226 review: each paste adds guides of its own (a guide is its place and layer; there is no
|
||||
/// id to share), on the layer new art goes to, so they take that layer's colour, visibility and
|
||||
/// lock; and the SVG put on the system clipboard carries no guides.
|
||||
#[test]
|
||||
fn two_pastes_add_their_own_guides_on_the_current_layer_and_svg_has_none() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 300}));
|
||||
run(&mut s, "guide.add", json!({"vertical": true, "pos": 120}));
|
||||
run(&mut s, "guide.select", json!({"indexes": [0]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
// Guides alone: no art for the system clipboard's SVG.
|
||||
assert!(s.clipboard_svg().is_none(), "guides alone put no SVG on the system clipboard");
|
||||
assert!(s.clipboard.flavour_types(true, true).is_empty(), "nor any other format (the app empties the system clipboard)");
|
||||
let layer = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
assert_eq!(s.doc().unwrap().selection.guides, [1], "the first paste selects its own guide");
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
assert_eq!(s.doc().unwrap().selection.guides, [2], "the second paste selects its own guide");
|
||||
let g = guides(&s);
|
||||
assert_eq!(g.len(), 3, "two pastes, two more guides: {g:?}");
|
||||
assert_eq!((g[1].2, g[2].2), (Some(layer), Some(layer)), "on the layer new art goes to");
|
||||
// Moving the second pasted guide leaves the first where it is.
|
||||
run(&mut s, "guide.move", json!({"index": 2, "pos": 200}));
|
||||
assert_eq!(guides(&s).iter().map(|g| g.1).collect::<Vec<_>>(), [120.0, 120.0, 200.0]);
|
||||
// Hiding that layer hides the guides pasted on it: they follow its visibility (and lock).
|
||||
run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": false}));
|
||||
let st = s.doc().unwrap();
|
||||
let shown: Vec<bool> = st.doc.guides.iter().map(|g| st.doc.guide_shown(g)).collect();
|
||||
assert_eq!(shown, [true, false, false]);
|
||||
// With an object, the SVG holds the object and no guide.
|
||||
run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": true}));
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [rect]}));
|
||||
run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true}));
|
||||
let r = run(&mut s, "edit.copy", json!({}));
|
||||
assert_eq!(r["guides"], 1);
|
||||
let svg = s.clipboard_svg().unwrap();
|
||||
assert!(svg.contains("<rect") || svg.contains("<path"), "the object is there");
|
||||
assert!(!svg.to_lowercase().contains("guide"), "no guide in the SVG: {svg}");
|
||||
}
|
||||
@@ -179,3 +179,42 @@ fn redo_during_an_interaction_keeps_the_history_and_the_document_in_step() {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(first_x(&s), start);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_mode_paint_snapshots_count_toward_the_history_budget() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":100,"height":100})).unwrap();
|
||||
let mut appearance = s.new_art();
|
||||
appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "stylize.dropShadow".into(),
|
||||
visible: true,
|
||||
params: json!({"color":"#ab6739", "retainedTemplateData":"x".repeat(128*1024)}),
|
||||
});
|
||||
s.paint.appearance = Some(appearance);
|
||||
let original = s.paint.clone();
|
||||
s.active_mut().unwrap().history.byte_budget = 64 * 1024;
|
||||
for i in 0..12 {
|
||||
s.execute("file.documentColorMode", &json!({"mode": if i%2 == 0 {"cmyk"} else {"rgb"}})).unwrap();
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.history.undo.len(), History::MIN_STEPS);
|
||||
assert!(st.history.undo.iter().all(|e| e.bytes > 256 * 1024), "both large templates count even without artwork");
|
||||
assert!(st.doc.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())));
|
||||
let retained = st.history.bytes();
|
||||
let after = s.paint.clone();
|
||||
for _ in 0..History::MIN_STEPS {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.redo.len(), History::MIN_STEPS);
|
||||
assert!(s.doc().unwrap().history.redo.iter().all(|e| e.bytes > 256 * 1024));
|
||||
assert!(s.doc().unwrap().history.bytes().abs_diff(retained) < 64 * 1024, "turning entries must not double-count paint snapshots");
|
||||
for _ in 0..History::MIN_STEPS {
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(s.paint, after);
|
||||
assert!(s.doc().unwrap().history.bytes().abs_diff(retained) < 64 * 1024);
|
||||
assert_eq!(
|
||||
s.paint.appearance.as_ref().unwrap().effects[0].params["retainedTemplateData"],
|
||||
original.appearance.unwrap().effects[0].params["retainedTemplateData"]
|
||||
);
|
||||
}
|
||||
Loaded 100 of 292 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user