Merge main into fix/ru-message-rows

This commit is contained in:
dotCooCoo
2026-11-13 20:17:13 -08:00
169 changed files with 19232 additions and 1874 deletions
Generated
+98 -28
View File
@@ -978,11 +978,33 @@ dependencies = [
"ruzstd",
]
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"craft-codepage",
"encoding_rs",
"kurbo 0.13.1",
"log",
"thiserror 2.0.21",
]
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -1057,6 +1079,21 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"craft-xml",
"flate2",
"kurbo 0.13.1",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"usvg 0.48.1",
"vectorcraft-geom 0.18.0",
"vectorcraft-pathops 0.18.0",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1146,6 +1183,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -6386,13 +6432,14 @@ dependencies = [
"serde_json",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
]
[[package]]
name = "vectorcraft-cad"
version = "0.24.1"
dependencies = [
"craft-dxf",
"image",
"kurbo 0.13.1",
"serde_json",
@@ -6400,8 +6447,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-text",
]
@@ -6418,7 +6465,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-mcp",
"vectorcraft-render",
"vectorcraft-svg",
@@ -6455,7 +6502,7 @@ dependencies = [
"thiserror 2.0.21",
"tiff",
"vectorcraft-color",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"zune-jpeg 0.5.15",
]
@@ -6470,8 +6517,8 @@ dependencies = [
"svgtypes 0.16.1",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
@@ -6515,10 +6562,10 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-js",
"vectorcraft-metafile",
"vectorcraft-pathops",
"vectorcraft-pathops 0.24.1",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
@@ -6537,6 +6584,7 @@ dependencies = [
name = "vectorcraft-eps"
version = "0.24.1"
dependencies = [
"craft-eps",
"craft-pdf",
"encoding_rs",
"fax",
@@ -6552,9 +6600,9 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-metafile",
"vectorcraft-pathops",
"vectorcraft-pathops 0.24.1",
"vectorcraft-pdf",
"vectorcraft-render",
"vectorcraft-testkit",
@@ -6573,10 +6621,20 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
]
[[package]]
name = "vectorcraft-geom"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo 0.13.1",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "vectorcraft-geom"
version = "0.24.1"
@@ -6611,7 +6669,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-render",
"vectorcraft-svg",
"vectorcraft-testkit",
@@ -6628,10 +6686,21 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-text",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
"thiserror 2.0.21",
"vectorcraft-geom 0.18.0",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.24.1"
@@ -6640,7 +6709,7 @@ dependencies = [
"linesweeper",
"proptest",
"thiserror 2.0.21",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
]
@@ -6673,7 +6742,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
"weezl 0.2.1",
@@ -6692,7 +6761,7 @@ dependencies = [
"thiserror 2.0.21",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"wasmi",
"wat",
"web-time",
@@ -6717,7 +6786,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-plugins",
"vectorcraft-testkit",
"vectorcraft-text",
@@ -6741,6 +6810,7 @@ name = "vectorcraft-svg"
version = "0.24.1"
dependencies = [
"craft-docpath",
"craft-svg",
"flate2",
"image",
"kurbo 0.13.1",
@@ -6757,8 +6827,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
]
@@ -6776,7 +6846,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-render",
"vectorcraft-svg",
]
@@ -6796,7 +6866,7 @@ dependencies = [
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vello_cpu",
"windows-registry",
"write-fonts",
@@ -6806,8 +6876,8 @@ dependencies = [
name = "vectorcraft-three-d"
version = "0.24.1"
dependencies = [
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
]
[[package]]
@@ -6822,8 +6892,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-text",
]
@@ -6836,7 +6906,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
]
[[package]]
@@ -6865,7 +6935,7 @@ dependencies = [
"vectorcraft-engine",
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
+6
View File
@@ -25,6 +25,12 @@ craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", re
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
+3 -2
View File
@@ -107,7 +107,7 @@ use titlebar::opted_into_system_title_bar;
#[cfg(windows)]
use titlebar::set_taskbar_icon;
#[cfg(all(test, feature = "wgpu"))]
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{app_draws_frame, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
@@ -367,7 +367,7 @@ fn main() -> std::process::ExitCode {
};
#[cfg(feature = "wgpu")]
let crash = left_out.crash.clone();
let custom_titlebar = custom_titlebar(saved.as_ref());
let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref());
let options = native_options(custom_titlebar);
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
@@ -593,6 +593,7 @@ fn main() -> std::process::ExitCode {
}
app.titlebar_from_env = titlebar_from_env();
app.custom_titlebar = custom_titlebar;
app.caption_layout = caption_layout;
app.desktop_frame = !custom_titlebar;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
+33 -6
View File
@@ -220,8 +220,10 @@ fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
}
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
/// with the default window buttons, an app frame the desktop left to the app keeps its own buttons,
/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the
/// default buttons, and the desktop frame stays
/// where the app frame is not drawn. System Title Bar takes precedence over the preference.
#[test]
fn the_start_frame_applies_the_app_title_bar_preference() {
use craft_window::{Button, Frame, Layout};
@@ -233,9 +235,10 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, true), Frame::App(Layout::default())),
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())),
];
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
@@ -246,6 +249,30 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// The app bar's caption buttons follow the window-button layout of the app frame on Linux and the
/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame,
/// macOS and Windows keep all three at the right.
#[test]
fn the_caption_buttons_follow_the_frame_layout() {
use craft_window::{Button, Frame, Layout};
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let close_only = Layout::parse("appmenu:close");
let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] };
let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] };
let probed = [
(close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }),
(at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }),
(split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }),
];
for (layout, expected) in probed {
let shown = super::caption_layout_from(&Frame::App(layout.clone()));
let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected };
assert_eq!(shown, expected, "{layout:?}");
}
assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default());
assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]);
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
@@ -303,7 +330,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let custom = super::custom_titlebar(saved);
let (custom, _) = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
@@ -312,7 +339,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None),
_ => super::custom_titlebar(None).0,
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
+37 -9
View File
@@ -31,7 +31,7 @@ pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type)
}
/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// Windows: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// macOS keeps its traffic lights over the integrated title strip.
///
/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the
@@ -68,18 +68,45 @@ pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced
}
/// The frame this start uses, before the System Title Bar preference is applied
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
/// layout, since `custom_titlebar_from` reads only which frame it is.
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. An app frame
/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps
/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft
/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can
/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons.
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
let probed_app = matches!(probed, craft_window::Frame::App(_));
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
(true, frame @ craft_window::Frame::App(_)) => frame,
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
(true, frame @ craft_window::Frame::App(_)) if overridden.is_none() && !forced_to_x11 => frame,
(true, _) => craft_window::Frame::App(craft_window::Layout::default()),
(false, _) => craft_window::Frame::Desktop,
}
}
/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button
/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of
/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the
/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let caption = |b: &craft_window::Button| match b {
craft_window::Button::Minimize => Caption::Minimize,
craft_window::Button::Maximize => Caption::Maximize,
craft_window::Button::Close => Caption::Close,
};
match frame.layout() {
Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() },
None => CaptionLayout::default(),
}
}
/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see
/// [`custom_titlebar_from`]).
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
vectorcraft_ui_egui::titlebar::CaptionLayout::default()
}
/// The `craft-window` probe's answer for this process (its override variable is
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
fn probed_choice() -> &'static craft_window::Choice {
@@ -131,7 +158,8 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
CUSTOM_TITLEBAR && !opted_into_system
}
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// Whether this start draws its own title bar, and where its caption buttons go
/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
@@ -142,7 +170,7 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> (bool, vectorcraft_ui_egui::titlebar::CaptionLayout) {
let choice = probed_choice();
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
@@ -160,7 +188,7 @@ pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> b
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
custom_titlebar_from(&frame, opted_into_system)
(custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame))
}
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
+5 -1
View File
@@ -78,7 +78,11 @@ fn samples(t: &Track, step: Option<f64>) -> Vec<(Point, Vec2, f64)> {
let pieces = (seg / step).ceil().clamp(1.0, MAX_STEPS) as usize;
for k in 1..pieces {
let u = k as f64 / pieces as f64;
out.push((p.lerp(t.verts[i + 1], u), t.dirs[i], (t.cum[i] + seg * u) / len));
let s = t.cum[i] + seg * u;
// On a chord of a flattened curve the samples follow the smooth frame through the
// vertices.
let (q, tg) = if t.curved.get(i).copied().unwrap_or(false) { t.frame_in(i, u) } else { (p.lerp(t.verts[i + 1], u), t.dirs[i]) };
out.push((q, tg, s / len));
}
}
}
+49
View File
@@ -1037,6 +1037,26 @@ fn pressed(points: Vec<(f64, f64)>) -> StrokeLayer {
StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }
}
/// A nib that follows the pen is sampled between the vertices of the flattened path too. Along a
/// curve those samples sit on the curve, and the outline keeps its distance from it.
#[test]
fn pen_driven_nib_outline_follows_the_curve_between_vertices() {
// The top half of a circle of radius 50; a round nib 20 pt across, the same at any pressure.
let (r, half) = (50.0, 10.0);
let c = Point::new(r, r);
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(20.0, 0.0), &half_circle, &pressed(vec![(0.0, 0.5), (1.0, 0.5)]));
let mut pts = vec![];
for n in &out {
all_points(n, &mut pts);
}
// Away from the round caps at the two ends, every outline point is `half` from the curve.
let middle = pts.iter().filter(|p| ((p.y - c.y).atan2(p.x - c.x).abs() - std::f64::consts::FRAC_PI_2).abs() <= 1.2);
let worst = middle.map(|p| ((p.distance(c) - (r + half)).abs()).min((p.distance(c) - (r - half)).abs())).fold(0.0, f64::max);
assert!(worst < 0.05, "an outline point strays {worst:.4} pt from the nib's reach");
}
/// #852: with Size on Pressure the nib goes from size − variation at the lightest pressure to
/// size + variation at the heaviest, along the stroke where the pen pressed.
#[test]
@@ -1686,6 +1706,35 @@ fn an_ordinary_stroke_is_unaffected_by_the_budget() {
assert!(anchors(&out) < 2_000_000);
}
/// A straight-sided art brush on a smooth curve draws smooth edges: they do not turn at the smooth
/// anchors the fit puts along them.
#[test]
fn art_brush_edges_stay_smooth_along_a_curve() {
for &(r, w, h, sw) in &[(100.0, 100.0, 10.0, 1.0), (300.0, 100.0, 10.0, 2.0), (30.0, 100.0, 10.0, 1.0), (2000.0, 100.0, 10.0, 1.0)] {
// The top half of a circle, as one open path of two curves.
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(w, h), ArtScale::Stretch), &half_circle, &stroke(sw));
let NodeKind::Path { path, .. } = &out[0].kind else { panic!("an art brush on a path draws a path") };
// The turn at each smooth anchor of the edges: the angle between the incoming and the
// outgoing direction. Real corners (the ends of the art) turn by far more than 60°.
let mut kink = 0.0f64;
for sp in &path.subpaths {
for (k, a) in sp.anchors.iter().enumerate().skip(1).take(sp.anchors.len().saturating_sub(2)) {
let h_in = if a.h_in != a.p { a.h_in } else { sp.anchors[k - 1].p };
let h_out = if a.h_out != a.p { a.h_out } else { sp.anchors[k + 1].p };
let (u, v) = (a.p - h_in, h_out - a.p);
if u.hypot() < 1e-9 || v.hypot() < 1e-9 || u.dot(v) < 0.5 * u.hypot() * v.hypot() {
continue;
}
kink = kink.max(u.cross(v).atan2(u.dot(v)).abs().to_degrees());
}
}
assert!(kink < 0.5, "r={r} art={w}x{h} weight {sw}: an edge turns by {kink:.3}° at a smooth anchor");
}
}
/// Anchors under `n`, and how many of them keep a handle (so the segment is a curve).
fn anchors_and_curved(n: &Node) -> (usize, usize) {
let NodeKind::Path { path, .. } = &n.kind else { return (0, 0) };
+346 -35
View File
@@ -1,8 +1,9 @@
//! Arc-length parameterised polylines ("tracks") that brushes lay art along.
//!
//! A track is one flattened subpath. `frame(s)` gives the point and unit tangent at arc length
//! `s`; tangents are blended across the gentle vertices of flattened curves (so warped art bends
//! smoothly) but stay discontinuous at real corners (so art folds there, like Illustrator).
//! `s`. Along a flattened curve the frame runs on a smooth curve through the vertices, so warped
//! art bends smoothly; along a line of the path it stays on the line. At real corners the tangent
//! stays discontinuous, so art folds there.
use vectorcraft_geom::{BezPath, PathEl, Point, Vec2};
@@ -22,6 +23,11 @@ pub struct Track {
pub tangents: Vec<Vec2>,
/// Is the vertex a corner (turn > [`CORNER_DEG`])? Open ends are never corners.
pub corner: Vec<bool>,
/// Does the segment come from flattening a curve (rather than from a line of the path)?
pub curved: Vec<bool>,
/// How far (radians) a curved segment's end tangents may turn from its direction for `frame`
/// to follow a curve through them; 0 for a line.
turn: Vec<f64>,
}
fn unit(v: Vec2) -> Vec2 {
@@ -35,16 +41,53 @@ fn aligned(a: Vec2, b: Vec2) -> bool {
a.dot(b) > 1.0 - 1e-12
}
/// How far a vertex tangent may turn from a chord of a flattened curve, as a multiple of the
/// flattening tolerance over the chord's length. A circular arc needs 4; the rest is slack for
/// flattening that lands a little inside its tolerance.
const TURN_PER_TOL: f64 = 6.0;
/// `t` turned by the smallest angle that brings it within `limit` radians of each `dir`. When no
/// angle satisfies every limit, `t` turns to the middle of the gap between them.
fn held_within(t: Vec2, limits: [Option<(Vec2, f64)>; 2]) -> Vec2 {
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
for (d, limit) in limits.into_iter().flatten() {
let to = t.cross(d).atan2(t.dot(d));
lo = lo.max(to - limit);
hi = hi.min(to + limit);
}
let turn = if lo <= hi { 0f64.max(lo).min(hi) } else { (lo + hi) / 2.0 };
if turn == 0.0 || !turn.is_finite() {
return t;
}
let (sin, cos) = turn.sin_cos();
Vec2::new(t.x * cos - t.y * sin, t.x * sin + t.y * cos)
}
/// Left-hand normal in y-down document space (for a path running +x it points +y).
pub fn normal(t: Vec2) -> Vec2 {
Vec2::new(-t.y, t.x)
}
impl Track {
fn new(mut pts: Vec<Point>, closed: bool) -> Option<Track> {
pts.dedup_by(|a, b| a.distance(*b) < 1e-9);
/// `raw` pairs each vertex with the tolerance the segment ending at it was flattened with
/// when it comes from a curve, and `None` when it is a line of the path.
fn new(raw: Vec<(Point, Option<f64>)>, closed: bool) -> Option<Track> {
let mut pts: Vec<Point> = Vec::with_capacity(raw.len());
// `ends_curve[k]`: the flattening tolerance of the segment ending at vertex `k`, when it
// comes from a curve.
let mut ends_curve: Vec<Option<f64>> = Vec::with_capacity(raw.len());
for (p, c) in raw {
// A duplicate vertex adds no segment, so it is dropped with its tolerance.
if pts.last().is_some_and(|q| q.distance(p) < 1e-9) {
continue;
}
pts.push(p);
ends_curve.push(c);
}
let mut closing_curve = None;
if closed && pts.len() > 2 && pts[0].distance(pts[pts.len() - 1]) < 1e-9 {
pts.pop();
closing_curve = ends_curve.pop().flatten();
}
if pts.len() < 2 {
return None;
@@ -52,8 +95,11 @@ impl Track {
let closed = closed && pts.len() > 2;
if closed {
pts.push(pts[0]);
ends_curve.push(closing_curve);
}
let nseg = pts.len() - 1;
let curve_tol: Vec<Option<f64>> = (0..nseg).map(|i| ends_curve.get(i + 1).copied().flatten()).collect();
let curved: Vec<bool> = curve_tol.iter().map(Option::is_some).collect();
let dirs: Vec<Vec2> = (0..nseg).map(|i| unit(pts[i + 1] - pts[i])).collect();
let mut cum = vec![0.0];
for i in 0..nseg {
@@ -62,34 +108,78 @@ impl Track {
let mut tangents = Vec::with_capacity(nseg + 1);
let mut corner = Vec::with_capacity(nseg + 1);
let cos_limit = CORNER_DEG.to_radians().cos();
let seg = |i: usize| (dirs[i], cum[i + 1] - cum[i], curved[i]);
for i in 0..=nseg {
let incoming = if i > 0 {
Some(dirs[i - 1])
Some(seg(i - 1))
} else if closed {
Some(dirs[nseg - 1])
Some(seg(nseg - 1))
} else {
None
};
let outgoing = if i < nseg {
Some(dirs[i])
Some(seg(i))
} else if closed {
Some(dirs[0])
Some(seg(0))
} else {
None
};
match (incoming, outgoing) {
(Some(a), Some(b)) => {
(Some((a, la, ca)), Some((b, lb, cb))) => {
corner.push(a.dot(b) < cos_limit);
tangents.push(unit(a + b));
tangents.push(match (ca, cb) {
// Between two chords of a flattened curve: each direction weighted by the
// length of the other chord, which is the tangent of the circle through
// the vertex and its two neighbors.
(true, true) => unit(a * lb + b * la),
// Where a line of the path meets a curve, the line's direction.
(false, true) => a,
(true, false) => b,
(false, false) => unit(a + b),
});
}
(a, b) => {
// An end of an open track (both `None` only for a track without segments).
corner.push(false);
tangents.push(a.or(b).unwrap_or(Vec2::new(1.0, 0.0)));
tangents.push(a.or(b).map_or(Vec2::new(1.0, 0.0), |(d, _, _)| d));
}
}
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner })
// An open track's end on a curve continues the bend of its last chord: the tangent there
// is the neighboring vertex's tangent mirrored about the chord, as on the circle through
// the last three vertices.
if !closed && nseg >= 2 {
for (end, inner, d) in [(0, 1, dirs[0]), (nseg, nseg - 1, dirs[nseg - 1])] {
let (s_end, s_inner) = if end == 0 { (0, 1) } else { (nseg - 1, nseg - 2) };
if !corner[inner] && curved[s_end] && curved[s_inner] {
let t = tangents[inner];
tangents[end] = unit(d * (2.0 * d.dot(t)) - t);
}
}
}
// A curve lies within its flattening tolerance `tol` of each of its chords, so its tangent
// at a vertex turns only a little from a chord: at most about `4 * tol / len` on a
// circular arc. Next to a long chord the estimates above can turn much further (a
// straight curve element beside a tight bend), and `frame` would then bow off the chord.
// Between curved chords, each vertex tangent is held within `TURN_PER_TOL * tol / len` of
// both chords. Where a line meets a curve the tangent stays the line's direction, and a
// curved chord whose end tangents turn further than that from it keeps to the chord.
let turn: Vec<f64> = (0..nseg)
.map(|j| match curve_tol.get(j) {
Some(Some(tol)) => (TURN_PER_TOL * tol / (cum[j + 1] - cum[j]).max(1e-12)).min(1.0).asin(),
_ => 0.0,
})
.collect();
for (i, t) in tangents.iter_mut().enumerate() {
let incoming = if i > 0 { Some(i - 1) } else { closed.then_some(nseg - 1) };
let outgoing = if i < nseg { Some(i) } else { closed.then_some(0) };
let sides = [incoming, outgoing];
if corner[i] || sides.iter().flatten().any(|&j| !curved[j]) {
continue;
}
*t = held_within(*t, sides.map(|j| j.map(|j| (dirs[j], turn[j]))));
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner, curved, turn })
}
pub fn len(&self) -> f64 {
@@ -135,11 +225,11 @@ impl Track {
let n = self.segments();
let s = if self.closed && l > 0.0 { s.rem_euclid(l) } else { s };
if s <= 0.0 && !self.closed {
let t = self.dirs[0];
let t = self.tangents[0];
return (self.verts[0] + t * s, t);
}
if s >= l && !self.closed {
let t = self.dirs[n - 1];
let t = self.tangents[n];
return (self.verts[n] + t * (s - l), t);
}
// Binary search the segment.
@@ -149,10 +239,44 @@ impl Track {
};
let seg = self.cum[i + 1] - self.cum[i];
let u = if seg > 1e-12 { ((s - self.cum[i]) / seg).clamp(0.0, 1.0) } else { 0.0 };
let p = self.verts[i].lerp(self.verts[i + 1], u);
let t0 = if self.corner[i] { self.dirs[i] } else { self.tangents[i] };
let t1 = if self.corner[i + 1] { self.dirs[i] } else { self.tangents[i + 1] };
(p, unit(t0 + (t1 - t0) * u))
self.frame_in(i, u)
}
/// Segment `i`'s direction and the tangents [`Self::frame`] uses at its two ends: the vertex
/// tangents, or the segment's direction at a corner.
fn end_tangents(&self, i: usize) -> Option<(Vec2, Vec2, Vec2)> {
let (&d, &c0, &c1, &t0, &t1) =
(self.dirs.get(i)?, self.corner.get(i)?, self.corner.get(i + 1)?, self.tangents.get(i)?, self.tangents.get(i + 1)?);
Some((d, if c0 { d } else { t0 }, if c1 { d } else { t1 }))
}
/// Point and unit tangent at the fraction `u` (0 to 1) of segment `i`, as [`Self::frame`]
/// gives them. `i` must be below [`Self::segments`].
pub fn frame_in(&self, i: usize, u: f64) -> (Point, Vec2) {
let (Some(&p0), Some(&p1), Some((d, t0, t1))) = (self.verts.get(i), self.verts.get(i + 1), self.end_tangents(i)) else {
return (self.verts.last().copied().unwrap_or(Point::ZERO), Vec2::new(1.0, 0.0));
};
let seg = self.cum.get(i + 1).zip(self.cum.get(i)).map_or(0.0, |(b, a)| b - a);
if aligned(t0, d) && aligned(t1, d) {
return (p0.lerp(p1, u), d);
}
// The tangents may turn this far from a curved chord, a little beyond it for rounding.
let within = self.turn.get(i).map_or(-1.0, |a| a.sin() + 1e-9);
let bends = |t: Vec2| t.dot(d) <= 0.0 || t.cross(d).abs() > within;
if !self.curved.get(i).copied().unwrap_or(false) || bends(t0) || bends(t1) {
// A line of the path, or a curved chord at a sharper turn than the curve can make
// there: the point stays on it, and the tangent turns across it toward the vertex
// tangents.
return (p0.lerp(p1, u), unit(t0 + (t1 - t0) * u));
}
// On a chord of a flattened curve the frame follows the cubic through both vertices with
// their tangents, at the chord's length per unit of `u`. Its position and tangent then
// meet those of the next segment at each vertex.
let (u2, u3) = (u * u, u * u * u);
let (m0, m1) = (t0 * seg, t1 * seg);
let p = p0 + (p1 - p0) * (3.0 * u2 - 2.0 * u3) + m0 * (u3 - 2.0 * u2 + u) + m1 * (u3 - u2);
let dp = (p1 - p0) * (6.0 * u - 6.0 * u2) + m0 * (3.0 * u2 - 4.0 * u + 1.0) + m1 * (3.0 * u2 - 2.0 * u);
(p, unit(dp))
}
/// The point at arc length `s`, offset `d` along the left normal.
@@ -183,8 +307,8 @@ impl Track {
if self.closed && (lo < -1e-9 || hi > l + 1e-9) {
return false;
}
// Past an open track's ends `frame` extrapolates along the end segment's direction, so
// those segments are part of the span too.
// Past an open track's ends `frame` extrapolates along the end tangent, which is checked
// against the end segment's direction below, so those segments are part of the span too.
let ends = [(!self.closed && lo < 0.0).then_some(0), (!self.closed && hi > l).then(|| n - 1)];
let touched = (0..n).filter(|&i| {
let (a, b) = (self.cum.get(i), self.cum.get(i + 1));
@@ -193,9 +317,7 @@ impl Track {
let mut dir: Option<Vec2> = None;
let mut any = false;
for i in touched.chain(ends.into_iter().flatten()) {
let (Some(&d), Some(&t0), Some(&t1), Some(&c0), Some(&c1)) =
(self.dirs.get(i), self.tangents.get(i), self.tangents.get(i + 1), self.corner.get(i), self.corner.get(i + 1))
else {
let Some((d, t0, t1)) = self.end_tangents(i) else {
return false;
};
if dir.is_some_and(|first: Vec2| !aligned(first, d)) {
@@ -203,11 +325,11 @@ impl Track {
}
dir = Some(d);
any = true;
// `frame` blends the two vertex tangents across the segment unless the vertex is a
// corner, where it uses the segment's own direction. So a neighbour outside the span
// can still bend the tangent inside it, and checking the directions alone would miss
// that: segments d, d, e leave vertex 2's tangent at unit(d + e).
if !(c0 || aligned(t0, d)) || !(c1 || aligned(t1, d)) {
// `frame` blends the two end tangents across a line, and follows a curve through them
// on a curved chord. So a neighbour outside the span can still bend the tangent
// inside it, and checking the directions alone would miss that: segments d, d, e
// leave vertex 2's tangent at unit(d + e).
if !aligned(t0, d) || !aligned(t1, d) {
return false;
}
}
@@ -220,9 +342,10 @@ const MAX_FLATTENED: usize = 4_000_000;
/// Flatten `bp` into tracks (one per subpath) with `tol` accuracy.
pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
let tol = tol.max(1e-4);
let mut out = vec![];
let mut cur: Vec<Point> = vec![];
let flush = |cur: &mut Vec<Point>, closed: bool, out: &mut Vec<Track>| {
let mut cur: Vec<(Point, Option<f64>)> = vec![];
let flush = |cur: &mut Vec<(Point, Option<f64>)>, closed: bool, out: &mut Vec<Track>| {
if let Some(t) = Track::new(std::mem::take(cur), closed) {
out.push(t);
}
@@ -236,19 +359,40 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
return out;
}
let mut els = vec![];
// When the element being flattened is a curve, the tolerance `flatten` uses for it: `flatten`
// pulls each element before it reports that element's lines, and raises the tolerance of a
// long curve as `vectorcraft_geom::flatten` describes.
let in_curve = std::cell::Cell::new(None);
let (last, start) = (std::cell::Cell::new(Point::ZERO), std::cell::Cell::new(Point::ZERO));
let source = bp.iter().inspect(|el| {
let from = last.get();
let (curve, to) = match *el {
PathEl::MoveTo(p) => {
start.set(p);
(None, p)
}
PathEl::LineTo(p) => (None, p),
PathEl::QuadTo(a, p) => (Some(from.distance(a) + a.distance(p)), p),
PathEl::CurveTo(a, b, p) => (Some(from.distance(a) + a.distance(b) + b.distance(p)), p),
PathEl::ClosePath => (None, start.get()),
};
last.set(to);
let per = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
in_curve.set(curve.map(|length| if length.is_finite() { tol.max(length / per) } else { f64::INFINITY }));
});
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
vectorcraft_geom::flatten(source, tol, |el| {
if els.len() < MAX_FLATTENED {
els.push(el);
els.push((el, in_curve.get()));
}
});
for el in els {
for (el, from_curve) in els {
match el {
PathEl::MoveTo(p) => {
flush(&mut cur, false, &mut out);
cur.push(p);
cur.push((p, None));
}
PathEl::LineTo(p) => cur.push(p),
PathEl::LineTo(p) => cur.push((p, from_curve)),
PathEl::ClosePath => flush(&mut cur, true, &mut out),
_ => {}
}
@@ -368,6 +512,173 @@ mod tests {
assert_eq!(t.map(110.0, 0.0), Point::new(110.0, 0.0));
}
/// Between two lines that meet at a gentle turn, the frame stays on the lines: only the chords
/// of a flattened curve are smoothed. Where a line meets a curve at a gentle turn, the frame
/// stays on the line with the line's direction, and its tangent does not jump at the join.
#[test]
fn a_polylines_frame_stays_on_its_lines() {
// A line, then a line or a nearly straight curve at a 20° turn, below the corner angle, so
// the vertex is not a corner.
let turn = 20f64.to_radians();
let (c, s) = (100.0 * turn.cos(), 100.0 * turn.sin());
for curve in [false, true] {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 0.0));
if curve {
bp.curve_to((100.0 + c / 3.0, s / 3.0 + 0.5), (100.0 + 2.0 * c / 3.0, 2.0 * s / 3.0 + 0.5), (100.0 + c, s));
} else {
bp.line_to((100.0 + c, s));
}
let t = &tracks(&bp, 0.05)[0];
for at in [10.0, 30.0, 50.0, 70.0, 90.0] {
let (p, tg) = t.frame(at);
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "curve {curve}: at {at} the frame left the first line: {p:?}");
if curve {
assert!(tg.y.abs() < 1e-12, "at {at} the line's tangent turned toward the curve: {tg:?}");
}
}
if curve {
// The curve's first chord keeps to the chord rather than bending toward the line.
let (a, b) = (t.cum[1], t.cum[2]);
let (p, q) = (t.verts[1], t.verts[2]);
let mid = t.frame((a + b) / 2.0).0;
assert!((mid - p.midpoint(q)).hypot() < 1e-9, "the first curve chord bows: {mid:?}");
}
let (before, after) = (t.frame(100.0 - 1e-7).1, t.frame(100.0 + 1e-7).1);
assert!(before.dot(after) > 1.0 - 1e-9, "curve {curve}: the tangent jumps at the join: {before:?} {after:?}");
}
}
/// A curve of no length between two lines leaves them lines.
#[test]
fn a_curve_of_no_length_leaves_a_line_a_line() {
let turn = 20f64.to_radians();
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 0.0));
bp.curve_to((100.0, 0.0), (100.0, 0.0), (100.0, 0.0));
bp.line_to((100.0 + 100.0 * turn.cos(), 100.0 * turn.sin()));
let t = &tracks(&bp, 0.05)[0];
assert!(t.curved.iter().all(|c| !c), "no segment is a curve: {:?}", t.curved);
for at in [10.0, 50.0, 90.0] {
let (p, _) = t.frame(at);
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "at {at} the frame left the first line: {p:?}");
}
}
/// Where a line joins a curve smoothly, the line keeps its direction up to the join.
#[test]
fn a_line_into_a_smooth_curve_keeps_its_direction() {
// A line along y = 0 into a quarter circle of radius 50 that starts along +x.
let r = 50.0;
let mut bp = BezPath::new();
bp.move_to((-100.0, 0.0));
bp.line_to((0.0, 0.0));
bp.curve_to((r * K, 0.0), (r, r - r * K), (r, r));
let t = &tracks(&bp, 0.05)[0];
for s in [10.0, 50.0, 90.0, 99.0] {
let (p, tg) = t.frame(s);
assert!(p.y.abs() < 1e-9 && tg.y.abs() < 1e-9, "at {s} the line's frame turned: {p:?} {tg:?}");
}
}
/// The handle length of a cubic quarter circle.
const K: f64 = 0.552_284_749_8;
/// A curve element whose handles lie on its chord is a line drawn as a curve. Next to a tight
/// bend, at either end of a track, the frame along it stays within the flattening tolerance
/// of the line.
#[test]
fn a_straight_curve_element_beside_a_tight_bend_stays_on_its_line() {
let tol = 0.05;
for bend_first in [false, true] {
// A 200 pt line along y = 0 drawn as a cubic, joined smoothly to a quarter circle of
// radius 5 that turns toward +y.
let mut bp = BezPath::new();
if bend_first {
bp.move_to((-5.0, -5.0));
bp.curve_to((-5.0, -5.0 + 5.0 * K), (-5.0 * K, 0.0), (0.0, 0.0));
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
} else {
bp.move_to((0.0, 0.0));
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
bp.curve_to((200.0 + 5.0 * K, 0.0), (205.0, 5.0 - 5.0 * K), (205.0, 5.0));
}
let t = &tracks(&bp, tol)[0];
// The bend lies outside 0 <= x <= 200, so every frame point in that range is on the
// line's stretch of the track.
let on_line: Vec<(Point, Vec2)> =
(0..=2000).map(|k| t.frame(t.len() * k as f64 / 2000.0)).filter(|(p, _)| (0.0..=200.0).contains(&p.x)).collect();
let worst = on_line.iter().map(|(p, _)| p.y.abs()).fold(0.0, f64::max);
assert!(worst <= 2.0 * tol, "bend first {bend_first}: the frame strays {worst:.4} pt off the line");
// Along the line the tangent turns by no more than the line's flattening allows.
let lean = on_line.iter().map(|(_, tg)| tg.y.abs()).fold(0.0, f64::max);
assert!(lean <= 0.01, "bend first {bend_first}: the tangent turns {lean:.4} off the line");
}
}
/// A curve long enough that flattening raises its tolerance still has its frame follow the
/// curve between the vertices, not the chords.
#[test]
fn a_long_curve_flattened_coarser_is_still_followed() {
// A line along y = 0 into a cubic quarter circle of radius 5,000,000 that starts along +x.
let r = 5.0e6;
let curve = kurbo::CubicBez::new((0.0, 0.0), (r * K, 0.0), (r, r - r * K), (r, r));
let mut bp = BezPath::new();
bp.move_to((-100.0, 0.0));
bp.line_to((0.0, 0.0));
bp.curve_to(curve.p1, curve.p2, curve.p3);
let t = &tracks(&bp, 0.05)[0];
let worst = (1..400)
.map(|k| t.frame(100.0 + (t.len() - 100.0) * k as f64 / 400.0).0)
.map(|p| kurbo::ParamCurveNearest::nearest(&curve, p, 1e-9).distance_sq.sqrt())
.fold(0.0, f64::max);
assert!(worst < 0.05, "the frame strays {worst:.4} pt from the curve");
}
/// A closed curve is smooth across its seam: the frame stays on the circle and at right angles
/// to its radius all the way round, the start included.
#[test]
fn a_closed_curves_frame_is_smooth_across_its_seam() {
let (r, tol) = (50.0, 0.05);
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
bp.curve_to((-r, -r * K), (-r * K, -r), (0.0, -r));
bp.curve_to((r * K, -r), (r, -r * K), (r, 0.0));
bp.close_path();
let t = &tracks(&bp, tol)[0];
assert!(t.closed && t.curved.iter().all(|c| *c), "every chord of the circle is a chord of a curve");
for k in -20..=20 {
let (p, tg) = t.frame(k as f64 * 0.37);
let radial = p.to_vec2() / p.to_vec2().hypot();
assert!((p.to_vec2().hypot() - r).abs() <= tol, "at {k} the frame is off the circle: {p:?}");
assert!(tg.dot(radial).abs() < 0.5f64.to_radians().sin(), "at {k} the tangent leans off the circle: {tg:?}");
}
}
/// A closed path whose last side is the implicit line back to the start keeps that line
/// straight.
#[test]
fn an_implicit_closing_line_is_not_a_curve() {
let r = 50.0;
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
bp.close_path();
let t = &tracks(&bp, 0.05)[0];
assert!(t.closed);
assert_eq!(t.curved.last(), Some(&false), "the closing line is a line");
let n = t.segments();
for u in [0.1, 0.5, 0.9] {
let (p, _) = t.frame(t.cum[n - 1] + (t.cum[n] - t.cum[n - 1]) * u);
assert!(p.y.abs() < 1e-9, "the frame leaves the closing line: {p:?}");
}
}
#[test]
fn closed_square_has_four_corners() {
let mut bp = BezPath::new();
+1
View File
@@ -9,6 +9,7 @@ description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12
workspace = true
[dependencies]
craft-dxf = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
+4 -67
View File
@@ -1,50 +1,11 @@
//! The 256-colour index palette CAD apps share, generated rather than tabulated: indices 1–9 are
//! the standard colours, 10–249 run through 24 hues at five brightnesses each in a full and a
//! half-saturated tone, and 250–255 are greys.
//! The colour index palette is `craft_dxf::model::aci`; here are the indices each colour depth
//! of the writer may use.
use crate::ColorDepth;
/// The nine standard colours (index 7 shows white on a dark background and black on paper).
const STANDARD: [[u8; 3]; 9] =
[[255, 0, 0], [255, 255, 0], [0, 255, 0], [0, 255, 255], [0, 0, 255], [255, 0, 255], [255, 255, 255], [128, 128, 128], [192, 192, 192]];
/// The brightness of the five shades of each hue.
const SHADES: [f64; 5] = [1.0, 0.65, 0.5, 0.3, 0.15];
/// The RGB of colour index `i` (1–255; anything else is index 7's white).
pub fn aci_rgb(i: u8) -> [u8; 3] {
match i {
1..=9 => STANDARD[usize::from(i - 1)],
10..=249 => {
let hue = f64::from(i / 10 - 1) * 15.0;
let k = i % 10;
let v = SHADES[usize::from(k / 2)];
let pastel = k % 2 == 1;
hue_rgb(hue).map(|f| {
let f = if pastel { f + (1.0 - f) / 2.0 } else { f };
(255.0 * v * f).floor() as u8
})
}
250..=255 => {
let g = (51.0 + 204.0 * f64::from(i - 250) / 5.0).floor() as u8;
[g; 3]
}
_ => STANDARD[6],
}
}
/// The fully saturated, full-brightness colour of `hue` degrees as 0–1 channels.
fn hue_rgb(hue: f64) -> [f64; 3] {
let h = hue.rem_euclid(360.0) / 60.0;
let x = 1.0 - (h % 2.0 - 1.0).abs();
match h as u8 {
0 => [1.0, x, 0.0],
1 => [x, 1.0, 0.0],
2 => [0.0, 1.0, x],
3 => [0.0, x, 1.0],
4 => [x, 0.0, 1.0],
_ => [1.0, 0.0, x],
}
craft_dxf::model::aci::rgb(i)
}
/// The indices a colour depth may use (true colour: all of them, for the fallback index).
@@ -59,37 +20,13 @@ fn candidates(depth: ColorDepth) -> Box<dyn Iterator<Item = u8>> {
/// The index of `depth` nearest to `rgb` (squared RGB distance; ties go to the lower index).
/// Index 7 stands for both white and black, as CAD apps draw it in the background's contrast.
pub fn nearest_aci(rgb: [u8; 3], depth: ColorDepth) -> u8 {
let dist = |c: [u8; 3]| rgb.iter().zip(c).map(|(a, b)| (i32::from(*a) - i32::from(b)).pow(2)).sum::<i32>();
candidates(depth).min_by_key(|i| if *i == 7 { dist([255; 3]).min(dist([0; 3])) } else { dist(aci_rgb(*i)) }).unwrap_or(7)
craft_dxf::model::aci::nearest(rgb, candidates(depth))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_palette_matches_its_known_entries() {
let known: [(u8, [u8; 3]); 14] = [
(1, [255, 0, 0]),
(10, [255, 0, 0]),
(11, [255, 127, 127]),
(12, [165, 0, 0]),
(13, [165, 82, 82]),
(17, [76, 38, 38]),
(19, [38, 19, 19]),
(20, [255, 63, 0]),
(21, [255, 159, 127]),
(30, [255, 127, 0]),
(140, [0, 191, 255]),
(250, [51, 51, 51]),
(252, [132, 132, 132]),
(255, [255, 255, 255]),
];
for (i, rgb) in known {
assert_eq!(aci_rgb(i), rgb, "index {i}");
}
}
#[test]
fn nearest_index_by_depth() {
assert_eq!(nearest_aci([255, 0, 0], ColorDepth::Aci8), 1);
+20 -19
View File
@@ -1,4 +1,4 @@
//! DXF import: an ASCII DXF drawing of any version as a document.
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document.
//!
//! The drawing's model space (or a paper layout) comes in at a ratio (1 unit of the art = N
//! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred
@@ -10,7 +10,8 @@
//! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve
//! them. What can't come in is listed in the warnings.
//!
//! - `reader`: the file's text, group codes, sections, tables, blocks and layouts.
//! - `reader`: what the import uses of the drawing `craft_dxf::model` reads: header, tables,
//! blocks and layouts.
//! - `entity`: entities to items (geometry and properties).
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
//! - `text`: text values to plain text.
@@ -31,9 +32,6 @@ use crate::{DxfVersion, INSUNITS, SCALE_RANGE};
/// Letter, the box Fit to Artboard fills unless told otherwise (points).
pub const FIT_TO: (f64, f64) = (612.0, 792.0);
/// Why a binary DXF can't be opened.
pub const BINARY: &str = "this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that";
/// How a drawing comes in.
#[derive(Clone, Debug, PartialEq)]
pub struct ImportOptions {
@@ -104,15 +102,20 @@ pub fn is_dxf(bytes: &[u8]) -> bool {
false
}
/// The pairs of a DXF file and where it is damaged (binary and DWG files are refused).
fn text(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>, String> {
if bytes.starts_with(reader::BINARY_SENTINEL) {
return Err(BINARY.into());
}
/// The tags of a DXF file and where it is damaged (DWG files are refused).
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Option<String>), String> {
if bytes.starts_with(b"AC10") || bytes.starts_with(b"AC1.") {
return Err("this is a DWG drawing, which can't be read: save it from the CAD app as an ASCII DXF and open that".into());
return Err("this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that".into());
}
Ok(reader::decode(bytes))
let (tags, damaged) = craft_dxf::parse_recovering(bytes).map_err(|e| match e {
craft_dxf::DxfError::TooLarge { .. } => "the drawing is too large to open".to_string(),
_ if bytes.starts_with(reader::BINARY_SENTINEL) => "this binary DXF file is damaged or cut short".to_string(),
_ => "not a DXF drawing".to_string(),
})?;
if tags.is_empty() {
return Err("not a DXF drawing".into());
}
Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out"))))
}
/// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it.
@@ -161,9 +164,8 @@ fn units_name(code: i64) -> &'static str {
/// Read what `bytes` holds: its version, units, layouts and layers.
pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
let text = text(bytes)?;
let (pairs, _) = reader::pairs(&text)?;
let d = reader::Drawing::read(&pairs);
let (tags, _) = tags(bytes)?;
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
if d.sections == 0 {
return Err("not a DXF drawing".into());
}
@@ -180,7 +182,7 @@ pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
})
}
/// Import an ASCII DXF drawing with `o`.
/// Import a DXF drawing with `o`.
pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
let (w, h) = o.fit_to;
if !(w > 0.0 && h > 0.0 && w.max(h) <= build::MAX_EXTENT) {
@@ -191,9 +193,8 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
{
return Err(format!("scale must be a number from {} to {}, not {s}", SCALE_RANGE.start(), SCALE_RANGE.end()));
}
let text = text(bytes)?;
let (pairs, damaged) = reader::pairs(&text)?;
let d = reader::Drawing::read(&pairs);
let (tags, damaged) = tags(bytes)?;
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
if d.sections == 0 {
return Err("not a DXF drawing".into());
}
+180 -302
View File
@@ -7,9 +7,10 @@ use kurbo::{BezPath, PathEl};
use vectorcraft_doc::Justify;
use vectorcraft_geom::{Affine, Point, Vec2};
use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
use super::curve::{self, Vertex};
use super::reader::{Groups, Pair, Record, groups, number};
use crate::aci::aci_rgb;
use super::reader::{aci_paper, point};
/// How far below the baseline the lowest descender reaches, as a fraction of the cap height.
const DESCENT: f64 = 0.3;
@@ -25,21 +26,6 @@ const MAX_COORD: f64 = 1e12;
/// factor 1, the 1 to 10,000% horizontal scale the Character panel allows.
const SPAN_SCALE: (f64, f64) = (0.01, 100.0);
/// The colour of index `i` on paper: index 7 (white on a CAD screen) is black.
pub(crate) fn aci_paper(i: u64) -> [u8; 3] {
match u8::try_from(i) {
Ok(7) | Err(_) => [0; 3],
Ok(i) => aci_rgb(i),
}
}
/// The true colour (group 420, `0xRRGGBB`) of an entity or layer.
pub(crate) fn true_color(g: &[Pair<'_>]) -> Option<[u8; 3]> {
let v = g.int(420)?;
let [_, r, gr, b] = u32::try_from(v & 0xFF_FFFF).ok()?.to_be_bytes();
Some([r, gr, b])
}
/// An entity's colour.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Col {
@@ -79,30 +65,30 @@ pub(crate) struct Props {
}
impl Props {
fn read(g: &[Pair<'_>]) -> Self {
let color = match (true_color(g), g.int(62)) {
(Some(rgb), _) => Col::Rgb(rgb),
(None, Some(0)) => Col::ByBlock,
(None, None | Some(256..)) => Col::ByLayer,
(None, Some(i)) => Col::Rgb(aci_paper(i.unsigned_abs())),
fn read(c: &model::Common) -> Self {
let color = match c.color {
model::Color::Rgb(rgb) => Col::Rgb(rgb),
model::Color::ByBlock => Col::ByBlock,
model::Color::ByLayer => Col::ByLayer,
model::Color::Index(i) => Col::Rgb(aci_paper(i)),
};
let lineweight = match g.int(370) {
Some(-2) => Lw::ByBlock,
Some(-3) => Lw::Default,
Some(v @ 0..=211) => Lw::Hundredths(v as i32),
let lineweight = match c.lineweight {
model::Lineweight::ByBlock => Lw::ByBlock,
model::Lineweight::Default => Lw::Default,
model::Lineweight::Hundredths(v @ 0..=211) => Lw::Hundredths(i32::from(v)),
_ => Lw::ByLayer,
};
let alpha = match g.int(440) {
Some(v) if v & 0x0200_0000 != 0 => Alpha::Opacity((v & 0xFF) as f32 / 255.0),
Some(v) if v & 0x0100_0000 != 0 => Alpha::ByBlock,
_ => Alpha::ByLayer,
let alpha = match c.transparency {
model::Transparency::Alpha(a) => Alpha::Opacity(f32::from(a) / 255.0),
model::Transparency::ByBlock => Alpha::ByBlock,
model::Transparency::ByLayer => Alpha::ByLayer,
};
Self {
layer: g.name(8).unwrap_or("0").to_string(),
layer: c.layer.clone(),
color,
lineweight,
linetype: g.name(6).unwrap_or("BYLAYER").to_uppercase(),
ltscale: g.num(48).filter(|v| *v > 0.0).unwrap_or(1.0),
linetype: c.linetype.as_deref().unwrap_or("BYLAYER").to_uppercase(),
ltscale: c.ltscale,
alpha,
}
}
@@ -209,90 +195,87 @@ impl Converter {
}
/// The items of `records` (an entity section or a block), in drawing order.
pub fn items(&mut self, records: &[Record<'_>]) -> Vec<Item> {
pub fn items(&mut self, records: &[EntityRecord<'_>]) -> Vec<Item> {
let mut out = Vec::new();
for group in groups(records) {
let Some(head) = group.first() else { continue };
for e in records {
let m = model::Entity::read(e);
// Invisible entities.
if head.g.int(60) == Some(1) {
if !m.common.visible {
continue;
}
match self.geom(head, group) {
match self.geom(e, &m) {
Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY),
Some(geom) => out.push(Item { props: Props::read(head.g), geom }),
None if is_known(head.kind) => {}
None => self.skip(head.kind),
Some(geom) => out.push(Item { props: Props::read(&m.common), geom }),
None if is_known(e.kind) => {}
None => self.skip(e.kind),
}
}
out
}
fn geom(&mut self, head: &Record<'_>, group: &[Record<'_>]) -> Option<Geom> {
let g = head.g;
fn geom(&mut self, e: &EntityRecord<'_>, m: &model::Entity) -> Option<Geom> {
let g = e.groups();
let path = |bp: BezPath| Some(Geom::Path { bp, fill: false, width: 0.0 });
match head.kind {
"LINE" => {
let ocs = ocs(m.common.extrusion);
match &m.kind {
model::EntityKind::Line { start, end } => {
let mut bp = BezPath::new();
bp.move_to(g.point(10));
bp.line_to(g.point(11));
bp.move_to(point(*start));
bp.line_to(point(*end));
path(bp)
}
"CIRCLE" => path(transformed(curve::arc(g.point(10), g.num(40)?, 0.0, std::f64::consts::TAU)?, ocs(g))),
"ARC" => {
let (start, end) = (g.num_or(50, 0.0), g.num_or(51, 360.0));
let sweep = ccw_sweep(start, end);
path(transformed(curve::arc(g.point(10), g.num(40)?, start.to_radians(), sweep.to_radians())?, ocs(g)))
model::EntityKind::Circle { center, radius } => path(transformed(curve::arc(point(*center), *radius, 0.0, std::f64::consts::TAU)?, ocs)),
model::EntityKind::Arc { center, radius, start_angle, end_angle } => {
let sweep = ccw_sweep(*start_angle, *end_angle);
path(transformed(curve::arc(point(*center), *radius, start_angle.to_radians(), sweep.to_radians())?, ocs))
}
"ELLIPSE" => path(ellipse(g)?),
"LWPOLYLINE" => lwpolyline(g),
"POLYLINE" => self.polyline(g, group.get(1..).unwrap_or(&[])),
"SPLINE" => path(spline(g)?),
"SOLID" | "TRACE" => {
let [a, b, c, d] = [g.point(10), g.point(11), g.point(12), g.point_opt(13).unwrap_or(g.point(12))];
model::EntityKind::Ellipse { center, major, ratio, start, end } => {
path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?)
}
model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs),
model::EntityKind::Polyline(p) => self.polyline(p, ocs),
model::EntityKind::Spline(s) => path(spline(s)?),
model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => {
let [a, b, c, d] = corners.map(point);
// The corners zigzag: the outline runs 1, 2, 4, 3.
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs(g)), fill: true, width: 0.0 })
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 })
}
"3DFACE" => {
let [a, b, c, d] = [g.point(10), g.point(11), g.point(12), g.point_opt(13).unwrap_or(g.point(12))];
path(polygon(&[a, b, c, d]))
}
"HATCH" => self.hatch(g),
"TEXT" | "ATTRIB" => text(g, head.kind == "ATTRIB").map(Geom::Text),
"MTEXT" => mtext(g).map(Geom::Text),
"INSERT" => self.insert(g, group.get(1..).unwrap_or(&[])),
model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))),
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs),
// A dimension draws the anonymous block of its lines, arrows and text.
"DIMENSION" => Some(Geom::Insert(InsertItem { block: g.name(2)?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] })),
model::EntityKind::Dimension(d) => {
Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] }))
}
_ => None,
}
}
fn polyline(&mut self, g: &[Pair<'_>], rest: &[Record<'_>]) -> Option<Geom> {
let flags = g.int_or(70, 0);
if flags & (16 | 64) != 0 {
fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option<Geom> {
if p.is_mesh() || p.is_polyface() {
self.warn(MESHES);
return None;
}
// Spline frame control points and polyface faces aren't on the line.
let verts: Vec<Vertex> = rest
.iter()
.filter(|r| r.kind == "VERTEX" && r.g.int_or(70, 0) & (16 | 128) == 0)
.map(|r| Vertex { p: r.g.point(10), bulge: r.g.num_or(42, 0.0) })
.collect();
let bp = curve::polyline(&verts, flags & 1 != 0)?;
let verts: Vec<Vertex> =
p.vertices.iter().filter(|v| v.flags & (16 | 128) == 0).map(|v| Vertex { p: point(v.location), bulge: v.bulge }).collect();
let bp = curve::polyline(&verts, p.closed())?;
// 3D polylines are in world coordinates; 2D ones in their plane's.
let bp = if flags & 8 != 0 { bp } else { transformed(bp, ocs(g)) };
Some(Geom::Path { bp, fill: false, width: g.num_or(40, 0.0).max(0.0) })
let bp = if p.is_3d() { bp } else { transformed(bp, ocs) };
Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) })
}
fn insert(&mut self, g: &[Pair<'_>], rest: &[Record<'_>]) -> Option<Geom> {
let block = g.name(2)?.to_uppercase();
let (sx, sy) = (g.num_or(41, 1.0), g.num_or(42, 1.0));
fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option<Geom> {
let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase();
let [sx, sy, _] = ins.scale;
if sx.abs() < 1e-12 || sy.abs() < 1e-12 {
return None;
}
let place = ocs(g) * Affine::translate(g.point(10).to_vec2()) * Affine::rotate(g.num_or(50, 0.0).to_radians());
let (cols, rows) = (g.int_or(70, 1).max(1), g.int_or(71, 1).max(1));
let (cs, rs) = (g.num_or(44, 0.0), g.num_or(45, 0.0));
let place = ocs * Affine::translate(point(ins.insert).to_vec2()) * Affine::rotate(ins.rotation.to_radians());
let (cols, rows) = (ins.columns, ins.rows);
let (cs, rs) = (ins.column_spacing, ins.row_spacing);
let (cols, rows) = if cols.saturating_mul(rows) > MAX_CELLS {
self.warn(BIG_ARRAY);
(cols.min(MAX_CELLS), (MAX_CELLS / cols.min(MAX_CELLS)).max(1).min(rows))
@@ -312,27 +295,41 @@ impl Converter {
.flat_map(|r| (0..cols).map(move |c| (r, c)))
.map(|(r, c)| place * Affine::translate((c as f64 * cs, r as f64 * rs)) * Affine::scale_non_uniform(sx, sy))
.collect();
let attribs = self.items(rest);
let attribs = self.attribs(followers);
Some(Geom::Insert(InsertItem { block, cells, attribs }))
}
fn hatch(&mut self, g: &[Pair<'_>]) -> Option<Geom> {
let start = g.iter().position(|p| p.code == 91)?;
let count = g.get(start).and_then(|p| number(p.value)).filter(|n| *n >= 0.0)? as usize;
let mut c = Cursor { g, i: start + 1 };
/// An insert's attributes as text.
fn attribs(&mut self, followers: &[model::Record<'_>]) -> Vec<Item> {
let mut out = Vec::new();
for r in followers {
let c = model::Common::read(r.tags);
if !c.visible {
continue;
}
let a = model::Attrib::read("ATTRIB", r.tags);
match text(&a.text, &r.groups(), true, ocs(c.extrusion)) {
Some(t) if !in_range(&Geom::Text(t.clone())) => self.warn(FAR_AWAY),
Some(t) => out.push(Item { props: Props::read(&c), geom: Geom::Text(t) }),
None => {}
}
}
out
}
fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option<Geom> {
let mut bp = BezPath::new();
for _ in 0..count {
let Some(path) = boundary(&mut c) else { break };
for l in &h.loops {
let Some(path) = boundary(&l.path) else { break };
bp.extend(path);
}
if bp.elements().is_empty() {
return None;
}
let bp = transformed(bp, ocs(g));
let solid = g.int_or(70, 0) == 1;
if g.int_or(450, 0) == 1 {
let bp = transformed(bp, ocs);
if h.gradient.is_some() {
self.warn(GRADIENT_HATCH);
} else if !solid {
} else if !h.solid {
self.warn(PATTERN_HATCH);
return Some(Geom::Path { bp, fill: false, width: 0.0 });
}
@@ -401,217 +398,104 @@ fn polygon(pts: &[Point]) -> BezPath {
bp
}
/// The extrusion direction (210, 220, 230) of a planar entity, normalised.
fn extrusion(g: &[Pair<'_>]) -> [f64; 3] {
let n = [g.num_or(210, 0.0), g.num_or(220, 0.0), g.num_or(230, 1.0)];
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if len > 1e-12 && len.is_finite() { n.map(|v| v / len) } else { [0.0, 0.0, 1.0] }
}
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn unit(v: [f64; 3]) -> [f64; 3] {
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
if len > 1e-12 { v.map(|x| x / len) } else { v }
}
/// A planar entity's coordinate system seen from above: its x and y axes in world space by the
/// arbitrary axis algorithm (identity for drawings in the world's plane; extruded along −z it
/// mirrors x).
fn ocs(g: &[Pair<'_>]) -> Affine {
let n = extrusion(g);
if n[2] > 1.0 - 1e-12 {
fn ocs(extrusion: model::Point) -> Affine {
let [ax, ay, _] = model::ocs_axes(extrusion);
if ax == [1.0, 0.0, 0.0] && ay == [0.0, 1.0, 0.0] {
return Affine::IDENTITY;
}
let ax = unit(if n[0].abs() < 1.0 / 64.0 && n[1].abs() < 1.0 / 64.0 { cross([0.0, 1.0, 0.0], n) } else { cross([0.0, 0.0, 1.0], n) });
let ay = unit(cross(n, ax));
Affine::new([ax[0], ax[1], ay[0], ay[1], 0.0, 0.0])
}
fn ellipse(g: &[Pair<'_>]) -> Option<BezPath> {
let centre = g.point(10);
let major = g.point(11).to_vec2();
let ratio = g.num_or(40, 1.0);
fn ellipse(extrusion: model::Point, centre: model::Point, major: model::Point, ratio: f64, start: f64, end: f64) -> Option<BezPath> {
let centre = point(centre);
let major = point(major).to_vec2();
if ratio <= 0.0 || major.hypot() < 1e-12 {
return None;
}
// The minor axis is the major one turned a quarter about the extrusion direction.
let n = extrusion(g);
let n = model::ocs_axes(extrusion)[2];
let m = cross(n, [major.x, major.y, 0.0]);
let minor = Vec2::new(m[0], m[1]) * ratio;
let (start, end) = (g.num_or(41, 0.0), g.num_or(42, std::f64::consts::TAU));
let sweep = ccw_sweep(start.to_degrees(), end.to_degrees()).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start, sweep)
}
fn lwpolyline(g: &[Pair<'_>]) -> Option<Geom> {
let mut verts: Vec<Vertex> = Vec::new();
let (mut widths, mut uniform) = (None, true);
for p in g {
match p.code {
10 => verts.push(Vertex { p: Point::new(number(p.value)?, 0.0), bulge: 0.0 }),
20 => verts.last_mut()?.p.y = number(p.value)?,
42 => verts.last_mut()?.bulge = number(p.value).unwrap_or(0.0),
40 | 41 => {
let w = number(p.value).unwrap_or(0.0);
uniform &= widths.is_none_or(|x: f64| (x - w).abs() < 1e-12);
widths = Some(w);
}
_ => {}
}
}
let bp = transformed(curve::polyline(&verts, g.int_or(70, 0) & 1 != 0)?, ocs(g));
let width = g.num(43).filter(|w| *w > 0.0).or(widths.filter(|_| uniform)).unwrap_or(0.0).max(0.0);
fn lwpolyline(p: &model::LwPolyline, ocs: Affine) -> Option<Geom> {
let verts: Vec<Vertex> = p.vertices.iter().map(|v| Vertex { p: Point::new(v.x, v.y), bulge: v.bulge }).collect();
let bp = transformed(curve::polyline(&verts, p.closed)?, ocs);
// One width for every vertex is the line's width.
let widths: Vec<f64> = p.vertices.iter().flat_map(|v| [v.start_width, v.end_width]).collect();
let uniform = widths.first().filter(|w| widths.iter().all(|x| (x - *w).abs() < 1e-12)).copied();
let width = Some(p.const_width).filter(|w| *w > 0.0).or(uniform).unwrap_or(0.0).max(0.0);
Some(Geom::Path { bp, fill: false, width })
}
/// The points at `code` (x) and `code + 10` (y), in order.
fn points(g: &[Pair<'_>], code: i32) -> Option<Vec<Point>> {
let mut out: Vec<Point> = Vec::new();
for p in g {
if p.code == code {
out.push(Point::new(number(p.value)?, 0.0));
} else if p.code == code + 10 {
out.last_mut()?.y = number(p.value)?;
}
}
Some(out)
}
fn spline(g: &[Pair<'_>]) -> Option<BezPath> {
let flags = g.int_or(70, 0);
let ctrl = points(g, 10)?;
let degree = usize::try_from(g.int_or(71, 3)).ok()?;
let knots: Vec<f64> = g.iter().filter(|p| p.code == 40).map(|p| number(p.value)).collect::<Option<_>>()?;
let weights: Vec<f64> = g.iter().filter(|p| p.code == 41).filter_map(|p| number(p.value)).collect();
let weights = (flags & 4 != 0 && weights.len() == ctrl.len()).then_some(weights.as_slice());
curve::nurbs(degree, &knots, &ctrl, weights)
fn spline(s: &model::Spline) -> Option<BezPath> {
let ctrl: Vec<Point> = s.control.iter().map(|p| point(*p)).collect();
let degree = usize::try_from(s.degree).ok()?;
let weights = (s.flags & 4 != 0 && s.weights.len() == ctrl.len()).then_some(s.weights.as_slice());
curve::nurbs(degree, &s.knots, &ctrl, weights)
.map(|mut path| {
if flags & 1 != 0 {
if s.flags & 1 != 0 {
path.close_path();
}
path
})
.or_else(|| curve::through(&points(g, 11)?, flags & 1 != 0))
}
/// Reads a hatch's boundary groups in order.
struct Cursor<'g, 'a> {
g: &'g [Pair<'a>],
i: usize,
}
impl Cursor<'_, '_> {
/// The next group's value when it has `code` (consumed).
fn opt(&mut self, code: i32) -> Option<&str> {
let p = self.g.get(self.i).filter(|p| p.code == code)?;
self.i += 1;
Some(p.value)
}
fn num(&mut self, code: i32) -> Option<f64> {
self.opt(code).and_then(number)
}
fn count(&mut self, code: i32) -> Option<usize> {
self.num(code).filter(|n| *n >= 0.0 && *n <= 1e7).map(|n| n as usize)
}
fn point(&mut self, code: i32) -> Option<Point> {
Some(Point::new(self.num(code)?, self.num(code + 10)?))
}
.or_else(|| curve::through(&s.fit.iter().map(|p| point(*p)).collect::<Vec<_>>(), s.flags & 1 != 0))
}
/// One hatch boundary loop, closed.
fn boundary(c: &mut Cursor<'_, '_>) -> Option<BezPath> {
let flags = c.num(92)? as i64;
let mut bp = BezPath::new();
if flags & 2 != 0 {
let bulges = c.num(72).unwrap_or(0.0) != 0.0;
let _closed = c.opt(73);
let n = c.count(93)?;
let mut verts = Vec::with_capacity(n.min(4096));
for _ in 0..n {
let p = c.point(10)?;
let bulge = if bulges { c.num(42).unwrap_or(0.0) } else { 0.0 };
verts.push(Vertex { p, bulge });
fn boundary(path: &HatchPath) -> Option<BezPath> {
let xy = |p: &[f64; 2]| Point::new(p[0], p[1]);
match path {
HatchPath::Polyline { vertices, .. } => {
let verts: Vec<Vertex> = vertices.iter().map(|[x, y, b]| Vertex { p: Point::new(*x, *y), bulge: *b }).collect();
curve::polyline(&verts, true)
}
bp = curve::polyline(&verts, true)?;
} else {
let n = c.count(93)?;
for _ in 0..n {
let edge = edge(c)?;
append(&mut bp, &edge);
}
if bp.elements().is_empty() {
return None;
}
bp.close_path();
}
// The boundary objects it was made from.
if let Some(n) = c.count(97) {
for _ in 0..n {
if c.opt(330).is_none() {
break;
}
}
}
Some(bp)
}
/// One edge of a hatch boundary.
fn edge(c: &mut Cursor<'_, '_>) -> Option<BezPath> {
match c.num(72)? as i64 {
1 => {
HatchPath::Edges(edges) => {
let mut bp = BezPath::new();
bp.move_to(c.point(10)?);
bp.line_to(c.point(11)?);
for e in edges {
let seg = match e {
HatchEdge::Line { start, end } => {
let mut bp = BezPath::new();
bp.move_to(xy(start));
bp.line_to(xy(end));
Some(bp)
}
HatchEdge::Arc { center, radius, start_angle, end_angle, ccw } => {
let sweep = ccw_sweep(*start_angle, *end_angle);
// Clockwise arcs have their angles measured clockwise.
let (start, sweep) = if *ccw { (*start_angle, sweep) } else { (-start_angle, -sweep) };
curve::arc(xy(center), *radius, start.to_radians(), sweep.to_radians())
}
HatchEdge::Ellipse { center, major, ratio, start_angle, end_angle, ccw } => {
let (centre, major) = (xy(center), xy(major).to_vec2());
let minor = Vec2::new(-major.y, major.x) * *ratio * if *ccw { 1.0 } else { -1.0 };
let sweep = ccw_sweep(*start_angle, *end_angle).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start_angle.to_radians(), sweep)
}
HatchEdge::Spline { degree, rational, knots, control, weights, fit, .. } => {
let ctrl: Vec<Point> = control.iter().map(xy).collect();
let degree = usize::try_from(*degree).ok()?;
let weights = (*rational && weights.len() == ctrl.len()).then_some(weights.as_slice());
curve::nurbs(degree, knots, &ctrl, weights).or_else(|| curve::through(&fit.iter().map(xy).collect::<Vec<_>>(), false))
}
};
append(&mut bp, &seg?);
}
if bp.elements().is_empty() {
return None;
}
bp.close_path();
Some(bp)
}
2 => {
let (centre, r, start, end) = (c.point(10)?, c.num(40)?, c.num(50)?, c.num(51)?);
let ccw = c.num(73).unwrap_or(1.0) != 0.0;
let sweep = ccw_sweep(start, end);
// Clockwise arcs have their angles measured clockwise.
let (start, sweep) = if ccw { (start, sweep) } else { (-start, -sweep) };
curve::arc(centre, r, start.to_radians(), sweep.to_radians())
}
3 => {
let (centre, major, ratio, start, end) = (c.point(10)?, c.point(11)?.to_vec2(), c.num(40)?, c.num(50)?, c.num(51)?);
let ccw = c.num(73).unwrap_or(1.0) != 0.0;
let minor = Vec2::new(-major.y, major.x) * ratio * if ccw { 1.0 } else { -1.0 };
let sweep = ccw_sweep(start, end).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start.to_radians(), sweep)
}
4 => {
let degree = c.count(94)?;
let rational = c.num(73).unwrap_or(0.0) != 0.0;
let _periodic = c.opt(74);
let (nk, nc) = (c.count(95)?, c.count(96)?);
let knots: Vec<f64> = (0..nk).map(|_| c.num(40)).collect::<Option<_>>()?;
let mut ctrl = Vec::with_capacity(nc.min(4096));
let mut weights = Vec::with_capacity(nc.min(4096));
for _ in 0..nc {
ctrl.push(c.point(10)?);
weights.push(c.num(42).unwrap_or(1.0));
}
// Fit data (DXF 2010 and later): a count, then that many points. Older files have none,
// and the 97 that may follow is the boundary's count of source objects (then their
// handles), so it is only the fit count when it is 0 or points follow.
let fit_count = match (c.g.get(c.i), c.g.get(c.i + 1)) {
(Some(count), next) if count.code == 97 => number(count.value) == Some(0.0) || next.is_some_and(|p| p.code == 11),
_ => false,
};
let fit: Vec<Point> = match fit_count.then(|| c.count(97)).flatten() {
Some(n) => (0..n).map(|_| c.point(11)).collect::<Option<_>>()?,
None => vec![],
};
// Start and end tangents.
for code in [12, 13] {
c.point(code);
}
curve::nurbs(degree, &knots, &ctrl, rational.then_some(weights.as_slice())).or_else(|| curve::through(&fit, false))
}
_ => None,
}
}
@@ -643,18 +527,21 @@ fn baseline(v: i64, height: f64) -> f64 {
}
}
fn text(g: &[Pair<'_>], attrib: bool) -> Option<TextItem> {
if attrib && g.int_or(70, 0) & 1 != 0 {
/// TEXT, or an ATTRIB's text. The string is read from group 1 as written, so that the caret and
/// percent codes are turned into text once, by `super::text`.
fn text(t: &model::Text, g: &Groups<'_>, attrib: bool, ocs: Affine) -> Option<TextItem> {
if attrib && g.i_or(70, 0) & 1 != 0 {
return None;
}
let s = super::text::plain(g.raw(1)?);
let s = super::text::plain(&g.s(1)?);
if s.trim().is_empty() {
return None;
}
let height = g.num(40).filter(|h| *h > 0.0)?;
let (h, v) = (g.int_or(72, 0), g.int_or(if attrib { 74 } else { 73 }, 0));
let (p1, p2) = (g.point(10), g.point_opt(11));
let mut angle = g.num_or(50, 0.0).to_radians();
let height = Some(t.height).filter(|h| *h > 0.0)?;
// An ATTRIB's 73 is its field length: its vertical alignment is 74.
let (h, v) = (t.halign, if attrib { g.i_or(74, 0) } else { t.valign });
let (p1, p2) = (point(t.insert), t.align.map(point));
let mut angle = t.rotation.to_radians();
let mut span = None;
// Aligned and fit text run from the first point to the second.
let anchor = match (h, p2) {
@@ -674,33 +561,36 @@ fn text(g: &[Pair<'_>], attrib: bool) -> Option<TextItem> {
_ => Justify::Left,
};
let v = if h == 4 { 2 } else { v };
let flags = g.int_or(71, 0);
let flags = t.generation;
let mirror = Affine::scale_non_uniform(if flags & 2 != 0 { -1.0 } else { 1.0 }, if flags & 4 != 0 { -1.0 } else { 1.0 });
let xf = ocs(g) * Affine::translate(anchor.to_vec2()) * Affine::rotate(angle) * mirror * Affine::translate((0.0, baseline(v, height)));
let xf = ocs * Affine::translate(anchor.to_vec2()) * Affine::rotate(angle) * mirror * Affine::translate((0.0, baseline(v, height)));
Some(TextItem {
text: s,
height,
xf,
width: g.num(41).filter(|w| *w > 0.0).unwrap_or(1.0),
width: Some(t.width_factor).filter(|w| *w > 0.0).unwrap_or(1.0),
justify,
style: g.name(7).unwrap_or("STANDARD").to_uppercase(),
style: t.style.to_uppercase(),
family: None,
leading: None,
span,
})
}
fn mtext(g: &[Pair<'_>]) -> Option<TextItem> {
// The text comes in 250-character chunks (3) before the last (1).
let raw: String = g.iter().filter(|p| p.code == 3).map(|p| p.value).chain(g.raw(1)).collect();
/// MTEXT. The contents are read from groups 3 and 1 as written, as for [`text`].
fn mtext(t: &model::MText, tags: &[craft_dxf::Tag]) -> Option<TextItem> {
// The text comes in 250-character chunks (3) before the last (1), up to an embedded object.
let (own, _) = model::text::split_embedded(tags);
let g = Groups(own);
let raw: String = own.iter().filter(|t| t.code == 3).map(craft_dxf::Tag::str).chain(g.s(1)).collect();
let (s, family) = super::text::mtext(&raw);
if s.trim().is_empty() {
return None;
}
let height = g.num(40).filter(|h| *h > 0.0)?;
let leading = height * LINE_SPACING * g.num(44).filter(|f| *f > 0.0).unwrap_or(1.0);
let height = Some(t.height).filter(|h| *h > 0.0)?;
let leading = height * LINE_SPACING * Some(t.line_spacing).filter(|f| *f > 0.0).unwrap_or(1.0);
let lines = s.lines().count().max(1) as f64;
let attach = g.int_or(71, 1).clamp(1, 9) - 1;
let attach = i64::from(t.attach) - 1;
let justify = [Justify::Left, Justify::Center, Justify::Right].get((attach % 3) as usize).copied().unwrap_or_default();
// The first baseline below the attachment point: under the top, around the middle, above
// the bottom of the lines.
@@ -710,18 +600,6 @@ fn mtext(g: &[Pair<'_>]) -> Option<TextItem> {
1 => total / 2.0 - height,
_ => (lines - 1.0) * leading,
};
let direction = g.point_opt(11).map(|p| p.to_vec2()).filter(|d| d.hypot() > 1e-12);
let angle = direction.map_or_else(|| g.num_or(50, 0.0), |d| d.atan2());
let xf = Affine::translate(g.point(10).to_vec2()) * Affine::rotate(angle) * Affine::translate((0.0, first));
Some(TextItem {
text: s,
height,
xf,
width: 1.0,
justify,
style: g.name(7).unwrap_or("STANDARD").to_uppercase(),
family,
leading: Some(leading),
span: None,
})
let xf = Affine::translate(point(t.insert).to_vec2()) * Affine::rotate(t.angle()) * Affine::translate((0.0, first));
Some(TextItem { text: s, height, xf, width: 1.0, justify, style: t.style.to_uppercase(), family, leading: Some(leading), span: None })
}
+68 -331
View File
@@ -1,156 +1,14 @@
//! Reading an ASCII DXF file: its text, the group-code pairs, and what the import uses of its
//! sections (header variables; the layer, linetype, text style and block record tables; the
//! blocks; the entities; the layouts).
//! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer,
//! linetype and text style tables; the blocks; the entities; the layouts.
use std::borrow::Cow;
use std::collections::HashMap;
use craft_dxf::model::{self, EntityRecord};
use vectorcraft_geom::Point;
/// The most group-code pairs a drawing may hold (about 300 MB of DXF).
const MAX_PAIRS: usize = 20_000_000;
/// The first bytes of a binary DXF file (its format's signature).
pub const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\x00";
/// One group: its code and its value as written.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Pair<'a> {
pub code: i32,
pub value: &'a str,
}
/// Values of a run of pairs by group code.
pub(crate) trait Groups<'a> {
/// The value of the first `code`, as written.
fn raw(&self, code: i32) -> Option<&'a str>;
/// The first `code` as a name (trimmed, never empty).
fn name(&self, code: i32) -> Option<&'a str> {
self.raw(code).map(str::trim).filter(|s| !s.is_empty())
}
/// The first `code` as a finite number.
fn num(&self, code: i32) -> Option<f64> {
self.raw(code).and_then(number)
}
fn num_or(&self, code: i32, default: f64) -> f64 {
self.num(code).unwrap_or(default)
}
/// The first `code` as a whole number.
fn int(&self, code: i32) -> Option<i64> {
self.raw(code).and_then(integer)
}
fn int_or(&self, code: i32, default: i64) -> i64 {
self.int(code).unwrap_or(default)
}
/// The point at `code` (x) and `code + 10` (y); 0 for what is missing.
fn point(&self, code: i32) -> Point {
Point::new(self.num_or(code, 0.0), self.num_or(code + 10, 0.0))
}
/// [`Groups::point`] when its x is given.
fn point_opt(&self, code: i32) -> Option<Point> {
self.num(code).map(|x| Point::new(x, self.num_or(code + 10, 0.0)))
}
}
impl<'a> Groups<'a> for [Pair<'a>] {
fn raw(&self, code: i32) -> Option<&'a str> {
self.iter().find(|p| p.code == code).map(|p| p.value)
}
}
/// A finite number (`1e999`, `NaN` and junk are none).
pub(crate) fn number(s: &str) -> Option<f64> {
s.trim().parse::<f64>().ok().filter(|v| v.is_finite())
}
/// A whole number; some writers put integers as `1.0`.
pub(crate) fn integer(s: &str) -> Option<i64> {
let s = s.trim();
s.parse::<i64>().ok().or_else(|| number(s).filter(|v| v.abs() < 9.0e15 && v.fract() == 0.0).map(|v| v as i64))
}
/// One object: its type (the value of its `0` group) and the groups up to the next object.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Record<'a> {
pub kind: &'a str,
pub g: &'a [Pair<'a>],
}
/// The text of a DXF file: UTF-8 (DXF 2007 and later), else the Windows code page older versions
/// write (a byte order mark is dropped).
pub(crate) fn decode(bytes: &[u8]) -> Cow<'_, str> {
let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
match std::str::from_utf8(bytes) {
Ok(s) => Cow::Borrowed(s),
Err(_) => Cow::Owned(bytes.iter().map(|b| windows_1252(*b)).collect()),
}
}
/// A byte of the Windows Western code page.
fn windows_1252(b: u8) -> char {
const HIGH: [char; 32] = [
'€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8D}', 'Ž', '\u{8F}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—',
'˜', '™', 'š', '›', 'œ', '\u{9D}', 'ž', 'Ÿ',
];
match b {
0x80..=0x9F => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or('?'),
_ => char::from(b),
}
}
/// The group-code pairs of `text`, up to `0 EOF`. A line that isn't a group code ends the
/// reading: what came before is kept and the second value says where the file is damaged.
pub(crate) fn pairs(text: &str) -> Result<(Vec<Pair<'_>>, Option<String>), String> {
let mut out = Vec::new();
let mut lines = text.lines().enumerate();
let mut damaged = None;
while let Some((n, code)) = lines.next() {
let c = code.trim();
if c.is_empty() && out.is_empty() {
continue;
}
let Ok(code) = c.parse::<i32>() else {
damaged = Some(format!("the file is damaged at line {}: what follows is left out", n + 1));
break;
};
let value = lines.next().map_or("", |(_, v)| v);
if code == 0 && value.trim() == "EOF" {
break;
}
if out.len() >= MAX_PAIRS {
return Err("the drawing is too large to open".into());
}
out.push(Pair { code, value });
}
if out.is_empty() {
return Err("not a DXF drawing".into());
}
Ok((out, damaged))
}
/// The objects in `pairs`: each from a `0` group up to the next.
fn records<'a>(pairs: &'a [Pair<'a>]) -> Vec<Record<'a>> {
let mut out = Vec::new();
let mut start: Option<usize> = None;
for (i, p) in pairs.iter().enumerate() {
if p.code == 0 {
if let Some(s) = start {
out.extend(record(pairs, s, i));
}
start = Some(i);
}
}
if let Some(s) = start {
out.extend(record(pairs, s, pairs.len()));
}
out
}
fn record<'a>(pairs: &'a [Pair<'a>], start: usize, end: usize) -> Option<Record<'a>> {
let kind = pairs.get(start)?.value.trim();
Some(Record { kind, g: pairs.get(start + 1..end)? })
}
/// The header variables the import reads.
#[derive(Clone, Debug, Default)]
pub(crate) struct Header {
@@ -186,7 +44,7 @@ pub(crate) struct LayerDef {
pub(crate) struct BlockDef<'a> {
pub name: String,
pub base: Point,
pub records: Vec<Record<'a>>,
pub records: Vec<EntityRecord<'a>>,
/// A reference to another drawing (its art isn't in this file).
pub xref: bool,
}
@@ -218,97 +76,51 @@ pub(crate) struct Drawing<'a> {
/// Blocks by upper-case name.
pub blocks: HashMap<String, BlockDef<'a>>,
/// The ENTITIES section.
pub entities: Vec<Record<'a>>,
pub entities: Vec<EntityRecord<'a>>,
/// Model space first, then the paper layouts in tab order.
pub layouts: Vec<LayoutDef>,
/// How many sections the file has (none: not a drawing).
pub sections: usize,
}
impl<'a> Drawing<'a> {
/// Read the sections of `pairs`.
pub fn read(pairs: &'a [Pair<'a>]) -> Self {
let mut d = Drawing { header: Header { ltscale: 1.0, lwdefault: 25, ..Header::default() }, ..Drawing::default() };
let all = records(pairs);
let mut section: Option<&str> = None;
let (mut tables, mut blocks, mut objects) = (vec![], vec![], vec![]);
for r in all {
match (r.kind, section) {
("SECTION", _) => {
d.sections += 1;
section = r.g.name(2);
if section == Some("HEADER") {
d.header = header(r.g);
}
}
("ENDSEC", _) => section = None,
(_, Some("TABLES")) => tables.push(r),
(_, Some("BLOCKS")) => blocks.push(r),
(_, Some("ENTITIES")) => d.entities.push(r),
(_, Some("OBJECTS")) => objects.push(r),
_ => {}
}
}
let mut block_records = HashMap::new();
let mut table = "";
for r in &tables {
match r.kind {
"TABLE" => table = r.g.name(2).unwrap_or(""),
"LAYER" if table == "LAYER" => {
if let Some(l) = layer(r.g) {
d.layer_index.entry(l.name.to_uppercase()).or_insert(d.layers.len());
d.layers.push(l);
}
}
"LTYPE" if table == "LTYPE" => {
if let Some(name) = r.g.name(2) {
let pattern: Vec<f64> = r.g.iter().filter(|p| p.code == 49).filter_map(|p| number(p.value)).collect();
d.linetypes.insert(name.to_uppercase(), pattern);
}
}
"STYLE" if table == "STYLE" => {
if let Some(name) = r.g.name(2) {
d.styles.insert(name.to_uppercase(), font_family(r.g));
}
}
"BLOCK_RECORD" if table == "BLOCK_RECORD" => {
if let (Some(h), Some(name)) = (r.g.name(5), r.g.name(2)) {
block_records.insert(h.to_uppercase(), name.to_uppercase());
}
}
_ => {}
}
}
d.read_blocks(&blocks, &mut block_records);
d.layouts = layouts(&objects, &block_records, &d.entities);
d
}
/// The colour of index `i` on paper: index 7 (white on a CAD screen) is black.
pub(crate) fn aci_paper(i: u8) -> [u8; 3] {
if i == 7 { [0; 3] } else { model::aci::rgb(i) }
}
fn read_blocks(&mut self, records: &[Record<'a>], block_records: &mut HashMap<String, String>) {
let mut current: Option<BlockDef<'a>> = None;
for r in records {
match r.kind {
"BLOCK" => {
let name = r.g.name(2).or_else(|| r.g.name(3)).unwrap_or("").to_string();
// R13+ blocks name their block record: layouts find their block through it.
if let Some(owner) = r.g.name(330) {
block_records.entry(owner.to_uppercase()).or_insert_with(|| name.to_uppercase());
}
let xref = r.g.int_or(70, 0) & 4 != 0;
current = Some(BlockDef { name, base: r.g.point(10), records: vec![], xref });
}
"ENDBLK" => {
if let Some(b) = current.take().filter(|b| !b.name.is_empty()) {
self.blocks.insert(b.name.to_uppercase(), b);
}
}
_ => {
if let Some(b) = &mut current {
b.records.push(*r);
}
}
}
impl<'a> Drawing<'a> {
/// What the import uses of `doc`.
pub fn read(doc: model::Document<'a>) -> Self {
let h = &doc.header;
let header = Header {
acadver: h.acadver().unwrap_or_default(),
insunits: h.insunits(),
measurement: h.measurement(),
ltscale: h.ltscale(),
lwdefault: i32::from(h.lwdefault()),
};
let mut d = Drawing { header, sections: doc.sections, ..Drawing::default() };
for l in doc.layers() {
d.layer_index.entry(l.name.to_uppercase()).or_insert(d.layers.len());
d.layers.push(layer(l));
}
for lt in doc.linetypes() {
d.linetypes.insert(lt.name.to_uppercase(), lt.pattern.iter().map(|e| e.length).collect());
}
for st in doc.text_styles().into_iter().filter(|s| !s.name.is_empty()) {
d.styles.insert(st.name.to_uppercase(), st.family().unwrap_or_default());
}
let block_names = doc.block_names();
d.layouts = layouts(&doc, &block_names);
for b in doc.blocks {
if b.name.is_empty() {
continue;
}
let def = BlockDef { name: b.name.to_string(), base: point(b.base()), xref: b.flags() & 4 != 0, records: b.entities };
d.blocks.insert(b.name.to_uppercase(), def);
}
d.entities = doc.entities;
d
}
/// The layout named `name` (any case; `model` is model space).
@@ -317,7 +129,7 @@ impl<'a> Drawing<'a> {
}
/// The entity records of `layout`.
pub fn layout_records(&self, layout: &LayoutDef) -> Vec<Record<'a>> {
pub fn layout_records(&self, layout: &LayoutDef) -> Vec<EntityRecord<'a>> {
let block = |name: &str| self.blocks.get(name).map(|b| b.records.clone()).unwrap_or_default();
// The active paper layout keeps its art in the ENTITIES section, flagged paper space.
let (block_name, paper) = match &layout.block {
@@ -325,7 +137,7 @@ impl<'a> Drawing<'a> {
Some(b) if b == PAPER_BLOCK => (PAPER_BLOCK, true),
Some(b) => return block(b),
};
let mut out: Vec<Record<'a>> = groups(&self.entities).filter(|g| in_paper_space(g) == paper).flatten().copied().collect();
let mut out: Vec<EntityRecord<'a>> = self.entities.iter().filter(|e| e.paper_space() == paper).cloned().collect();
out.extend(block(block_name));
out
}
@@ -336,111 +148,47 @@ impl<'a> Drawing<'a> {
}
}
/// Is an entity (its first record) in paper space?
fn in_paper_space(group: &[Record<'_>]) -> bool {
group.first().is_some_and(|r| r.g.int(67) == Some(1))
pub(crate) fn point(p: model::Point) -> Point {
Point::new(p[0], p[1])
}
/// The entities of `records`, each with the records that belong to it (a polyline's vertices,
/// an insert's attributes, and the SEQEND closing them).
pub(crate) fn groups<'r, 'a>(records: &'r [Record<'a>]) -> impl Iterator<Item = &'r [Record<'a>]> {
let mut i = 0;
std::iter::from_fn(move || {
let start = i;
let head = records.get(start)?;
i += 1;
if matches!(head.kind, "POLYLINE" | "INSERT") {
while let Some(r) = records.get(i) {
match r.kind {
"VERTEX" | "ATTRIB" => i += 1,
"SEQEND" => {
i += 1;
break;
}
_ => break,
}
}
}
records.get(start..i)
})
}
fn header(g: &[Pair<'_>]) -> Header {
let mut h = Header { ltscale: 1.0, lwdefault: 25, ..Header::default() };
let mut var = "";
for p in g {
if p.code == 9 {
var = p.value.trim();
continue;
}
match (var, p.code) {
("$ACADVER", 1) => h.acadver = p.value.trim().to_string(),
("$INSUNITS", 70) => h.insunits = integer(p.value).unwrap_or(0),
("$MEASUREMENT", 70) => h.measurement = integer(p.value),
("$LTSCALE", 40) => h.ltscale = number(p.value).filter(|v| *v > 0.0).unwrap_or(1.0),
("$LWDEFAULT", 370) => h.lwdefault = integer(p.value).and_then(|v| i32::try_from(v).ok()).filter(|v| *v >= 0).unwrap_or(25),
_ => {}
}
}
h
}
fn layer(g: &[Pair<'_>]) -> Option<LayerDef> {
let name = g.name(2)?.to_string();
let aci = g.int_or(62, 7);
let flags = g.int_or(70, 0);
let rgb = super::entity::true_color(g).unwrap_or_else(|| super::entity::aci_paper(aci.unsigned_abs()));
Some(LayerDef {
fn layer(l: model::Layer) -> LayerDef {
let rgb = match l.color {
model::Color::Rgb(rgb) => rgb,
model::Color::Index(i) => aci_paper(i),
model::Color::ByLayer | model::Color::ByBlock => aci_paper(7),
};
LayerDef {
// CAD apps never plot this layer of dimension points.
plot: g.int_or(290, 1) != 0 && !name.eq_ignore_ascii_case("Defpoints"),
name,
plot: l.plot && !l.name.eq_ignore_ascii_case("Defpoints"),
rgb,
hidden: aci < 0 || flags & 1 != 0,
locked: flags & 4 != 0,
linetype: g.name(6).unwrap_or("CONTINUOUS").to_uppercase(),
lineweight: g.int(370).and_then(|v| i32::try_from(v).ok()).unwrap_or(-3),
})
}
/// A text style's font family: the one 2000-and-later files name, else the font file's name
/// (TrueType); CAD fonts (`.shx`) have none.
fn font_family(g: &[Pair<'_>]) -> String {
if let Some(i) = g.iter().position(|p| p.code == 1001 && p.value.trim() == "ACAD")
&& let Some(f) = g.get(i + 1..).and_then(|rest| rest.name(1000))
{
return f.to_string();
}
let file = g.name(3).unwrap_or("");
let path = std::path::Path::new(file);
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
match ext.as_str() {
"ttf" | "otf" | "ttc" => path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(),
_ => String::new(),
hidden: !l.on || l.frozen,
locked: l.locked,
linetype: l.linetype.to_uppercase(),
lineweight: i32::try_from(l.lineweight.to_dxf()).unwrap_or(-3),
name: l.name,
}
}
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
/// objects but with paper-space art has one paper layout.
/// The most bytes of layout and block names the layouts keep together. Each layout keeps its own
/// copy of its block's name, so many layouts naming one long block name multiplied it; real
/// drawings have a few dozen layouts with short names.
const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20;
fn layouts(objects: &[Record<'_>], block_records: &HashMap<String, String>, entities: &[Record<'_>]) -> Vec<LayoutDef> {
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
/// objects but with paper-space art has one paper layout.
fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<LayoutDef> {
let mut paper: Vec<(i64, LayoutDef)> = vec![];
let mut seen = std::collections::HashSet::new();
let mut name_bytes = 0usize;
for r in objects.iter().filter(|r| r.kind == "LAYOUT") {
// The layout's own groups follow its subclass marker.
let own = r.g.iter().position(|p| p.code == 100 && p.value.trim() == "AcDbLayout").and_then(|i| r.g.get(i + 1..)).unwrap_or(&[]);
let Some(name) = own.name(1) else { continue };
let block = own.name(330).and_then(|h| block_records.get(&h.to_uppercase()));
if name.eq_ignore_ascii_case(MODEL) || block.map(String::as_str) == Some(MODEL_BLOCK) {
for l in doc.layouts() {
let block = l.block_record.and_then(|h| block_names.get(&h)).map(|n| n.to_uppercase());
if l.name.eq_ignore_ascii_case(MODEL) || block.as_deref() == Some(MODEL_BLOCK) {
continue;
}
let Some(block) = block else { continue };
let key = name.to_ascii_lowercase();
let cost = name.len() + block.len();
let key = l.name.to_ascii_lowercase();
let cost = l.name.len() + block.len();
// A layout past the allowance is skipped alone: a later short one is still offered, and a
// skipped one reserves neither its name nor its bytes.
if seen.contains(&key) || name_bytes.saturating_add(cost) > MAX_LAYOUT_NAME_BYTES {
@@ -448,22 +196,11 @@ fn layouts(objects: &[Record<'_>], block_records: &HashMap<String, String>, enti
}
seen.insert(key);
name_bytes += cost;
paper.push((own.int_or(71, i64::MAX), LayoutDef { name: name.to_string(), block: Some(block.clone()) }));
paper.push((l.tab_order, LayoutDef { name: l.name, block: Some(block) }));
}
paper.sort_by_key(|(order, _)| *order);
if paper.is_empty() && groups(entities).any(in_paper_space) {
if paper.is_empty() && doc.entities.iter().any(EntityRecord::paper_space) {
paper.push((1, LayoutDef { name: "Layout1".into(), block: Some(PAPER_BLOCK.into()) }));
}
std::iter::once(LayoutDef { name: MODEL.into(), block: None }).chain(paper.into_iter().map(|(_, l)| l)).collect()
}
#[cfg(test)]
mod tests {
use super::integer;
#[test]
fn integer_rejects_fractional_float_values() {
assert_eq!(integer("1.0"), Some(1));
assert_eq!(integer("1.9"), None);
}
}
+8 -4
View File
@@ -997,7 +997,12 @@ fn binary_dwg_damaged_and_foreign_files() {
binary.extend([0u8; 40]);
assert!(is_dxf(&binary));
let e = import(&binary, &ImportOptions::default()).unwrap_err();
assert!(e.contains("binary DXF") && e.contains("ASCII"), "{e}");
assert!(e.contains("binary DXF") && e.contains("damaged"), "{e}");
// A binary DXF opens as its ASCII form does.
let ascii = entities(LINE);
let tags = craft_dxf::parse(&ascii).unwrap();
let r = open(&craft_dxf::write_binary(&tags, true), &points());
assert_eq!(leaves(&r.document).len(), 1);
let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err();
assert!(e.contains("DWG"), "{e}");
for junk in [&b""[..], b"hello", b"<svg/>", b"999\nnote\n"] {
@@ -1166,9 +1171,8 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() {
let one = [(0, "INSERT"), (8, "0"), (2, "NOPE"), (10, "0"), (20, "0"), (70, "100"), (71, "100"), (44, "1"), (45, "1")];
let e: Vec<(i32, &str)> = (0..3000).flat_map(|_| one).collect();
let bytes = entities(&e);
let text = reader::decode(&bytes);
let (pairs, _) = reader::pairs(&text).unwrap();
let d = reader::Drawing::read(&pairs);
let tags = craft_dxf::parse(&bytes).unwrap();
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
let model = d.layout("Model").or(d.layouts.first()).unwrap();
let mut conv = entity::Converter::default();
let items = conv.items(&d.layout_records(model));
+3 -3
View File
@@ -1,5 +1,5 @@
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader, and an
//! HP-GL/2 plot file reader and writer.
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on
//! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer.
//!
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
//! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths
@@ -11,7 +11,7 @@
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
//! clipping) is approximated or left out, and each such loss comes back as a warning.
//!
//! [`import()`] reads an ASCII DXF drawing (any version) into a document: see [`import`].
//! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`].
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
//!
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
+446 -86
View File
@@ -183,8 +183,8 @@ impl Document {
self.layers.retain(|l| !l.is_ruler_guide());
gone -= self.layers.len();
for l in &mut self.layers {
if layer_untidy(l) {
gone += tidy_layer(Arc::make_mut(l));
if let Some(found) = untidy(l, &Node::is_ruler_guide) {
gone += tidy_layer(Arc::make_mut(l), found);
}
}
let others = self
@@ -198,8 +198,8 @@ impl Document {
if root.is_ruler_guide() {
*root = Arc::new(Node::group(root.id, vec![]));
gone += 1;
} else if any_guide(root) {
gone += drop_guides_below(Arc::make_mut(root));
} else if let Some(found) = guides_below(root, &Node::is_ruler_guide) {
gone += drop_guides_below(Arc::make_mut(root), found);
}
}
gone
@@ -272,8 +272,8 @@ impl Document {
return;
}
for l in &mut self.layers {
if l.holds_ruler_guides() {
Arc::make_mut(l).strip_ruler_guides();
if let Some(held) = picked_in_layers(l, &Node::is_ruler_guide) {
drop_picked(l, held);
}
}
self.saved_guides.extend(guides);
@@ -347,16 +347,14 @@ impl Document {
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
let mut layer = self.remove(id)?;
if !layer.holds_ruler_guides() {
return Ok(layer);
}
let Some(held) = picked_in_layers(&layer, &Node::is_ruler_guide) else { return Ok(layer) };
let mut guides = vec![];
layer.walk(&mut |c| {
if c.is_ruler_guide() {
guides.push(Arc::new(c.clone()));
}
});
Arc::make_mut(&mut layer).strip_ruler_guides();
drop_picked(&mut layer, held);
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
self.children_mut(Some(home))?.extend(guides);
Ok(layer)
@@ -418,21 +416,11 @@ impl Document {
if gone.is_empty() {
return 0;
}
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
}
if !holds(layer, gone) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
for c in ch.iter_mut().filter(|c| c.is_layer()) {
drop(c, gone);
}
}
let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id);
for l in &mut self.layers {
drop(l, &gone);
if let Some(held) = picked_in_layers(l, &pick) {
drop_picked(l, held);
}
}
sel.guides.retain(|id| !gone.contains(id));
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
@@ -444,29 +432,11 @@ impl Document {
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
/// position).
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn holds(n: &Node, id: u32) -> bool {
n.is_layer()
&& n.children().is_some_and(|ch| {
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
})
}
if !holds(layer, id) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for c in ch.iter_mut() {
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
} else if c.is_layer() {
visit(c, id, f);
}
}
}
let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id);
for l in &mut self.layers {
visit(l, id, f);
if let Some(held) = picked_in_layers(l, &pick) {
edit_picked(l, held, f);
}
}
}
@@ -580,65 +550,172 @@ impl Document {
}
}
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
fn any_guide(n: &Node) -> bool {
let mut any = false;
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
any
/// What a walk picked in a node: its children by index in order, each with what was picked
/// inside it, and what was picked in its opacity-mask art. Empty for a node picked itself.
#[derive(Debug, Default)]
struct Picked {
children: Vec<(usize, Picked)>,
mask: Option<Box<Picked>>,
}
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_guides_below(n: &mut Node) -> usize {
let mut gone = drop_mask_guides(n);
if let Some(ch) = n.children_mut() {
let before = ch.len();
ch.retain(|c| !c.is_ruler_guide());
gone += before - ch.len();
for c in ch.iter_mut().filter(|c| any_guide(c)) {
gone += drop_guides_below(Arc::make_mut(c));
impl Picked {
fn is_empty(&self) -> bool {
self.children.is_empty() && self.mask.is_none()
}
/// `self`, or `None` when nothing was picked.
fn some(self) -> Option<Self> {
(!self.is_empty()).then_some(self)
}
}
/// The children of `n`, if it is a layer, that `pick` picks (with nothing inside), and its
/// sublayers holding one (with what they hold), or `None` when it holds none. `pick` looks at
/// each child of the layers once.
fn picked_in_layers(n: &Node, pick: &impl Fn(&Node) -> bool) -> Option<Picked> {
if !n.is_layer() {
return None;
}
let children = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if pick(c) { Some((i, Picked::default())) } else { picked_in_layers(c, pick).map(|p| (i, p)) })
.collect();
Picked { children, mask: None }.some()
}
/// Remove the children of `layer` and of its sublayers that [`picked_in_layers`] picked (`held`).
/// Only the layers holding one are copied, and only those are visited.
fn drop_picked(layer: &mut Arc<Node>, held: Picked) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
let mut held = held.children.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; a child picked itself has nothing inside.
if inner.is_empty() {
return false;
}
drop_picked(c, inner);
true
});
}
/// Change with `f` (whether it is vertical, its position) the line of each ruler guide of `layer`
/// and of its sublayers that [`picked_in_layers`] picked (`held`), in the order they lie in. Only
/// the layers holding one, and the guides, are copied, and only those layers are visited.
fn edit_picked(layer: &mut Arc<Node>, held: Picked, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for (i, inner) in held.children {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.is_empty() {
edit_picked(c, inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
/// `n` picked itself when it is a ruler guide by `is_guide`, else the ruler guides below it
/// ([`guides_below`]).
fn guide_or_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
if is_guide(n) { Some(Picked::default()) } else { guides_below(n, is_guide) }
}
/// The ruler guides below `n`, by `is_guide`: those among its members and its opacity-mask art
/// (each with nothing inside), and the members and mask art holding one further down (with what
/// they hold), or `None` when there is none. `is_guide` looks at each node below `n` once, and at
/// nothing inside a ruler guide.
fn guides_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
let mask = n.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
let children = n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| guide_or_below(c, is_guide).map(|p| (i, p))).collect();
Picked { children, mask }.some()
}
/// Remove the ruler guides below `n` that [`guides_below`] `found`, in its members and its
/// opacity-mask art (`n` itself stays). Mask art that is a ruler guide becomes an empty group.
/// Only the nodes holding one are copied, and only those are visited. Returns how many went.
fn drop_guides_below(n: &mut Node, found: Picked) -> usize {
let mut gone = drop_mask_guides(n, found.mask);
if let Some(ch) = n.children_mut() {
let mut found = found.children.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
if inner.is_empty() {
gone += 1;
return false;
}
gone += drop_guides_below(Arc::make_mut(c), inner);
true
});
}
gone
}
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
/// becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node) -> usize {
/// Remove the ruler guides `found` in the opacity-mask art of `n` ([`guides_below`]'s mask
/// part). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node, found: Option<Box<Picked>>) -> usize {
let Some(found) = found else { return 0 };
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
if mask.art.is_ruler_guide() {
if found.is_empty() {
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
1
} else if any_guide(&mask.art) {
drop_guides_below(Arc::make_mut(&mut mask.art))
} else {
0
drop_guides_below(Arc::make_mut(&mut mask.art), *found)
}
}
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
/// in one of its sublayers?
fn layer_untidy(l: &Node) -> bool {
let Some(ch) = l.children() else { return false };
let start = Node::guide_run_start(ch);
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
/// The ruler guides, by `is_guide`, that layer `l` holds out of place, or `None` when it holds
/// none: those below art (each with nothing inside), those in its mask art and in its objects
/// ([`guides_below`]), and its sublayers holding one out of place (with what they hold).
/// `is_guide` looks at each node once; the guides at the end of a layer are in place and are
/// not looked at.
fn untidy(l: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
let ch = l.children()?;
let mask = l.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
let children = ch
.iter()
.enumerate()
.take(Node::guide_run_start(ch))
.filter_map(|(i, c)| {
let found = if is_guide(c) {
Some(Picked::default())
} else if c.is_layer() {
untidy(c, is_guide)
} else {
guides_below(c, is_guide)
};
found.map(|p| (i, p))
})
.collect();
Picked { children, mask }.some()
}
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
fn tidy_layer(l: &mut Node) -> usize {
let mut gone = drop_mask_guides(l);
/// [`Document::tidy_ruler_guides`] for layer `l`, whose guides out of place [`untidy`] `found`.
/// Only the nodes holding one are copied, and only those are visited. Returns how many guides
/// were removed.
fn tidy_layer(l: &mut Node, found: Picked) -> usize {
let mut gone = drop_mask_guides(l, found.mask);
let Some(ch) = l.children_mut() else { return gone };
for c in ch.iter_mut() {
if c.is_layer() {
if layer_untidy(c) {
gone += tidy_layer(Arc::make_mut(c));
}
} else if !c.is_ruler_guide() && any_guide(c) {
gone += drop_guides_below(Arc::make_mut(c));
let mut below_art = false;
for (i, inner) in found.children {
let Some(c) = ch.get_mut(i) else { continue };
if inner.is_empty() {
below_art = true;
} else if c.is_layer() {
gone += tidy_layer(Arc::make_mut(c), inner);
} else {
gone += drop_guides_below(Arc::make_mut(c), inner);
}
}
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
if below_art {
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
*ch = art;
ch.extend(guides);
@@ -698,3 +775,286 @@ impl std::fmt::Debug for GuideCache {
f.write_str("GuideCache")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Appearance, OpacityMask, Symbol};
use std::cell::Cell;
use vectorcraft_geom::shapes;
/// The sublayers in [`nested`]'s chain: with the top-level layer around them and the objects in
/// the innermost, the deepest a document goes ([`crate::MAX_DEPTH`]).
const CHAIN: u64 = 30;
fn rect(id: u64) -> Arc<Node> {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))
}
fn guide(id: u64, artboard: Option<u32>) -> Arc<Node> {
Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: id as f64, artboard }))
}
fn group(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
Arc::new(Node::group(NodeId(id), children))
}
/// `n` with `art` as its opacity-mask art.
fn masked(n: Arc<Node>, art: Arc<Node>) -> Arc<Node> {
let mut n = (*n).clone();
n.extras_mut().mask = Some(Box::new(OpacityMask { art, clip: true, invert: false, disabled: false, linked: true }));
Arc::new(n)
}
/// A sublayer like a new document's first layer, holding `children`.
fn sublayer(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
let mut l = (*Document::new(1.0, 1.0).layers[0]).clone();
l.id = NodeId(id);
if let Some(ch) = l.children_mut() {
*ch = children;
}
Arc::new(l)
}
/// A document whose first layer holds `children`.
fn doc(children: Vec<Arc<Node>>) -> Document {
let mut d = Document::new(100.0, 100.0);
if let Some(ch) = d.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) {
*ch = children;
}
d
}
/// The ids of the nodes in the layers, in tree order.
fn ids(d: &Document) -> Vec<u64> {
fn walk(n: &Node, out: &mut Vec<u64>) {
out.push(n.id.0);
for c in n.children().into_iter().flatten() {
walk(c, out);
}
}
let mut out = vec![];
for l in &d.layers {
walk(l, &mut out);
}
out
}
/// [`CHAIN`] sublayers, each inside the one before and holding an object, a canvas guide and a
/// guide of artboard 7 (the innermost: object 150, guides 200 and 201). Beside the chain, a
/// sublayer with a canvas guide only. Returns the document and that sublayer.
fn nested() -> (Document, Arc<Node>) {
let mut chain = sublayer(100, vec![rect(150), guide(200, None), guide(201, Some(7))]);
for depth in 1..CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth * 2, None), guide(301 + depth * 2, Some(7))]);
}
let still = sublayer(500, vec![rect(502), guide(501, None)]);
(doc(vec![chain, Arc::clone(&still)]), still)
}
/// How many children the layers of [`nested`] hold: the first layer's 2, the untouched
/// sublayer's 2, the innermost sublayer's 3 and 4 in each sublayer around it.
const NESTED_CHILDREN: usize = 2 + 2 + 3 + (CHAIN as usize - 1) * 4;
fn on_artboard_7(n: &Node) -> bool {
matches!(n.kind, NodeKind::RulerGuide { artboard: Some(7), .. })
}
#[test]
fn removing_guides_looks_at_each_child_of_nested_layers_once() {
let (mut d, still) = nested();
assert!(!d.clone().limit_depth(), "the chain is as deep as a document goes");
let mut deeper = doc(vec![sublayer(999, d.layers[0].children().cloned().unwrap_or_default())]);
assert!(deeper.limit_depth(), "a document nested deeper is brought within the cap when it is read");
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let pick = |n: &Node| {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
drop_picked(&mut d.layers[0], held);
assert_eq!(looked.get(), NESTED_CHILDREN, "removing looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
// The command's own entry point removes the same guides.
let before = whole.clone();
let mut sel = Selection::default();
sel.set_guides([NodeId(200), NodeId(201), NodeId(501)]);
sel.objects.push(NodeId(150));
sel.key_guide = Some(NodeId(201));
assert_eq!(whole.retain_guides(&mut sel, |g| g.artboard != Some(7)), CHAIN as usize);
assert_eq!(ids(&whole), ids(&d));
assert_eq!(ids(&whole).len(), ids(&before).len() - CHAIN as usize);
assert!(whole.ruler_guides().iter().all(|g| g.artboard.is_none()));
assert_eq!(whole.ruler_guides().len(), CHAIN as usize + 1);
assert_eq!((sel.objects.as_slice(), sel.guides.as_slice(), sel.key_guide), (&[NodeId(150)][..], &[NodeId(200), NodeId(501)][..], None));
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
// The document as it was (an undo step's copy) still holds every guide.
assert_eq!(before.ruler_guides().len(), CHAIN as usize * 2 + 1);
// Saving the guides as a list, and removing a layer but not its guides, take the guides
// out of the nested layers too.
let mut saved = before.clone();
saved.guides_to_saved();
assert_eq!(saved.saved_guides, before.ruler_guides());
assert_eq!(ids(&saved).len(), 1 + CHAIN as usize * 2 + 2);
assert!(saved.layers[0].children().is_some_and(|c| !Arc::ptr_eq(&c[1], &still) && c[1].children().is_some_and(|c| c.len() == 1)));
let mut edited = before.clone();
let chain = edited.remove_edit_layer(NodeId(100 + CHAIN - 1)).unwrap();
assert!(!chain.holds_ruler_guides());
assert_eq!(edited.ruler_guides().len(), before.ruler_guides().len(), "the removed layer's guides stay in the document");
assert_eq!(edited.guides_on(edited.layers[0].id).len(), CHAIN as usize * 2);
// Keeping every guide changes nothing and copies no layer.
let kept = whole.clone();
assert_eq!(whole.retain_guides(&mut sel, |_| true), 0);
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
// Removing every guide leaves the objects.
assert_eq!(whole.retain_guides(&mut sel, |_| false), CHAIN as usize + 1);
assert!(whole.ruler_guides().is_empty() && sel.guides.is_empty());
assert_eq!(ids(&whole).len(), 1 + CHAIN as usize * 2 + 2);
assert_eq!(sel.objects, [NodeId(150)]);
// A document without layers, and one without guides, have nothing to remove.
let mut empty = Document::new(10.0, 10.0);
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
empty.layers.clear();
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
}
#[test]
fn moving_an_artboards_guides_looks_at_each_child_of_nested_layers_once() {
let (mut d, still) = nested();
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let pick = |n: &Node| {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
edit_picked(&mut d.layers[0], held, &mut |vertical, pos: &mut f64| {
seen.push((vertical, *pos));
*pos += 9.0;
});
assert_eq!(looked.get(), NESTED_CHILDREN, "changing looks at nothing again");
// A sublayer comes before its layer's own guides, so the innermost guide is changed first.
let order: Vec<(bool, f64)> = [201.0].into_iter().chain((1..CHAIN).map(|depth| (301 + depth * 2) as f64)).map(|pos| (false, pos)).collect();
assert_eq!(seen, order, "each guide of the artboard is changed once, in the order the guides lie in");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with no guide of the artboard is not copied");
// The public moves change the same guides by the same amount.
let before = whole.clone();
whole.move_artboard_guides(7, Vec2::new(5.0, 9.0));
assert_eq!(whole, d);
assert_eq!(ids(&whole), ids(&before));
for g in whole.ruler_guides() {
let id = g.id.map_or(0, |id| id.0) as f64;
assert_eq!(g.pos, if g.artboard == Some(7) { id + 9.0 } else { id }, "guide {id}");
}
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
assert_eq!(before.ruler_guide(NodeId(201)).map(|g| g.pos), Some(201.0), "the document as it was keeps its guides");
whole.map_artboard_guides(7, Affine::scale(2.0));
assert_eq!(whole.ruler_guide(NodeId(201)).map(|g| g.pos), Some(420.0));
assert_eq!(whole.ruler_guide(NodeId(200)).map(|g| g.pos), Some(200.0), "a canvas guide stays");
// An artboard without guides, and a document without layers, change nothing and copy no layer.
let kept = whole.clone();
whole.move_artboard_guides(99, Vec2::new(5.0, 9.0));
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
let mut empty = Document::new(10.0, 10.0);
empty.layers.clear();
empty.move_artboard_guides(7, Vec2::new(5.0, 9.0));
assert!(empty.layers.is_empty());
}
#[test]
fn guides_in_objects_are_found_by_looking_at_each_node_once() {
// Groups, each inside the one before and holding an object and a guide. Beside them, an
// object whose mask art holds a guide, one whose mask art is a guide, and a group with none.
let mut chain = group(100, vec![rect(150), guide(200, None)]);
for depth in 1..CHAIN {
chain = group(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
}
let still = group(700, vec![rect(701)]);
let root = group(
1,
vec![chain, masked(rect(800), group(801, vec![guide(802, None), rect(803)])), masked(rect(810), guide(811, None)), Arc::clone(&still)],
);
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
// The chain's groups, objects and guides; a masked object, its mask group and the two in
// it; a masked object and its mask guide; the last group and its object.
let nodes = CHAIN as usize * 3 + 4 + 2 + 2;
let found = guides_below(&root, &is_guide).unwrap();
assert_eq!(looked.get(), nodes, "each node below the root is looked at once");
let mut cleared = (*root).clone();
assert_eq!(drop_guides_below(&mut cleared, found), CHAIN as usize + 2);
assert_eq!(looked.get(), nodes, "removing looks at nothing again");
assert!(guides_below(&cleared, &Node::is_ruler_guide).is_none());
let ch = cleared.children().unwrap();
assert!(Arc::ptr_eq(&ch[3], &still), "a group without guides is not copied");
assert_eq!(
ch[1].extras().mask.as_deref().map(|m| m.art.children().map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>())),
Some(Some(vec![803]))
);
assert_eq!(ch[2].extras().mask.as_deref().map(|m| (m.art.id, m.art.children().map(Vec::len))), Some((NodeId(811), Some(0))));
// Opening a file removes the same guides from an object on a layer and from a symbol's art.
let mut d = doc(vec![Arc::clone(&root), guide(900, None)]);
d.symbols = vec![Symbol { name: "s".into(), art: Arc::clone(&root), dynamic: false }];
assert_eq!(d.tidy_ruler_guides(), (CHAIN as usize + 2) * 2);
assert_eq!(d.layers[0].children().map(|c| (*c[0]).clone()), Some(cleared.clone()));
assert_eq!(*d.symbols[0].art, cleared);
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(NodeId(900))]);
}
#[test]
fn guides_out_of_place_are_found_by_looking_at_each_node_once() {
// Sublayers, each inside the one before, with their guides in place; the innermost also
// holds a guide below its art. Beside them, a group holding a guide, a sublayer with its
// guide in place, and a sublayer whose mask art holds a guide.
let mut chain = sublayer(100, vec![guide(200, None), rect(150), guide(201, None)]);
for depth in 1..CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
}
let still = sublayer(500, vec![rect(502), guide(501, None)]);
let with_mask = masked(sublayer(510, vec![rect(513)]), group(511, vec![guide(512, None)]));
let mut d = doc(vec![chain, group(700, vec![rect(701), guide(702, None)]), Arc::clone(&still), with_mask, guide(900, None)]);
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
// Below the guides at the end of each layer: the first layer's 4, the group's 2, the
// untouched sublayer's 1, the masked sublayer's mask group, its guide and the object, 2 in
// the innermost sublayer and 2 in each sublayer around it.
let nodes = 4 + 2 + 1 + 3 + 2 + (CHAIN as usize - 1) * 2;
let found = untidy(&d.layers[0], &is_guide).unwrap();
assert_eq!(looked.get(), nodes, "each node below the guides in place is looked at once");
assert_eq!(tidy_layer(Arc::make_mut(&mut d.layers[0]), found), 2);
assert_eq!(looked.get(), nodes, "tidying looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[2], &still)), "a sublayer with its guides in place is not copied");
assert!(untidy(&d.layers[0], &Node::is_ruler_guide).is_none());
// Opening a file does the same.
let before = whole.clone();
assert_eq!(whole.tidy_ruler_guides(), 2);
assert_eq!(whole, d);
let all = ids(&whole);
assert!(!all.contains(&702) && all.len() == ids(&before).len() - 1);
let innermost = whole.node(NodeId(100)).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>());
assert_eq!(innermost, Some(vec![150, 200, 201]), "a guide below art moves up to the other guides");
assert!(whole.node(NodeId(510)).is_some_and(|n| n.extras().mask.as_deref().is_some_and(|m| m.art.children().is_some_and(Vec::is_empty))));
// A tidy document is left alone, and no layer is copied.
let kept = whole.clone();
assert_eq!(whole.tidy_ruler_guides(), 0);
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
}
}
+61 -20
View File
@@ -763,33 +763,19 @@ impl Node {
children.iter().rposition(|c| !c.is_ruler_guide()).map_or(0, |i| i + 1)
}
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none.
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none. Only
/// layers that hold one are copied.
pub fn strip_ruler_guides(&mut self) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
ch.retain(|c| !c.is_ruler_guide());
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides()) {
Arc::make_mut(c).strip_ruler_guides();
}
if let Some(held) = held_guides(self, &Self::is_ruler_guide) {
strip_held(self, held);
}
}
/// Call `f` on the position (along the axis it crosses) of each ruler guide of this layer and
/// of its sublayers, with whether the guide is vertical. Only layers that hold one are copied.
pub fn map_ruler_guide_positions(&mut self, f: &mut impl FnMut(bool, &mut f64)) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
for c in ch.iter_mut().filter(|c| c.is_ruler_guide() || c.holds_ruler_guides()) {
let c = Arc::make_mut(c);
match &mut c.kind {
NodeKind::RulerGuide { vertical, pos, .. } => f(*vertical, pos),
_ => c.map_ruler_guide_positions(f),
}
}
if let Some(held) = held_guides(self, &Self::is_ruler_guide) {
map_held(self, held, f);
}
}
@@ -834,6 +820,61 @@ impl Node {
}
}
/// The ruler guides a layer holds: its children that are one, by index in order (each with
/// nothing inside), and its sublayers holding one (with what they hold).
#[derive(Debug, Default)]
pub(super) struct HeldGuides(Vec<(usize, HeldGuides)>);
/// The ruler guides, by `is_guide`, that `n` holds if it is a layer, or `None` when it holds
/// none. `is_guide` looks at each child of `n` and of its sublayers once.
pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<HeldGuides> {
if !n.is_layer() {
return None;
}
let held: Vec<_> = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if is_guide(c) { Some((i, HeldGuides::default())) } else { held_guides(c, is_guide).map(|h| (i, h)) })
.collect();
(!held.is_empty()).then_some(HeldGuides(held))
}
/// Remove the ruler guides of `layer` and of its sublayers that [`held_guides`] found (`held`).
/// Only the sublayers holding one are copied, and only those are visited.
pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) {
let Some(ch) = layer.children_mut() else { return };
let mut held = held.0.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; a ruler guide has nothing inside.
if inner.0.is_empty() {
return false;
}
strip_held(Arc::make_mut(c), inner);
true
});
}
/// Call `f` (whether it is vertical, its position) on each ruler guide of `layer` and of its
/// sublayers that [`held_guides`] found (`held`), in the order they lie in. Only the sublayers
/// holding one, and the guides, are copied, and only those sublayers are visited.
pub(super) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = layer.children_mut() else { return };
for (i, inner) in held.0 {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.0.is_empty() {
map_held(Arc::make_mut(c), inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
impl Node {
/// The Appearance panel's row for what this object's own fills and strokes paint around:
/// "Contents" for a group or layer (its members) and for an image (its pixels), "Characters"
+204
View File
@@ -598,3 +598,207 @@ fn compound_stroke_path_is_its_members_in_order() {
assert_eq!(bp.elements(), expected.elements());
assert!(!bp.elements().is_empty());
}
/// The sublayers in [`guide_layers`]'s chain, each inside the one before.
const GUIDE_CHAIN: u64 = 30;
/// How many children the layers of [`guide_layers`] hold: the layer's 6, 1 in the sublayer
/// without a guide, 2 at each of the two places the shared sublayer lies, the innermost
/// sublayer's 2 and 3 in each sublayer around it.
const GUIDE_LAYER_CHILDREN: usize = 6 + 1 + 2 * 2 + 2 + (GUIDE_CHAIN as usize - 1) * 3;
/// How many ruler guides the layers of [`guide_layers`] hold: one in each sublayer of the chain,
/// one at each place the shared sublayer lies and the layer's own.
const GUIDE_LAYER_GUIDES: usize = GUIDE_CHAIN as usize + 2 + 1;
/// A layer holding, in order: [`GUIDE_CHAIN`] sublayers, each inside the one before and holding an
/// object and a ruler guide; a sublayer with an object only; a sublayer with an object and a
/// guide; an object; that last sublayer again; and a guide. Guides differ in direction, artboard
/// and lock. Returns the layer, the sublayer without a guide and the one that lies twice.
fn guide_layers() -> (Node, Arc<Node>, Arc<Node>) {
let rect = |id| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()));
let guide = |id: u64| {
let kind = NodeKind::RulerGuide { vertical: id.is_multiple_of(2), pos: id as f64, artboard: id.is_multiple_of(3).then_some(7) };
let mut g = Node::new(NodeId(id), kind);
g.locked = id.is_multiple_of(5);
Arc::new(g)
};
let sublayer = |id, children: Vec<Arc<Node>>| {
let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1));
if let Some(ch) = l.children_mut() {
*ch = children;
}
Arc::new(l)
};
let mut chain = sublayer(100, vec![rect(150), guide(200)]);
for depth in 1..GUIDE_CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth)]);
}
let still = sublayer(500, vec![rect(501)]);
let twice = sublayer(510, vec![rect(511), guide(512)]);
let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = vec![chain, Arc::clone(&still), Arc::clone(&twice), rect(2), Arc::clone(&twice), guide(3)];
}
(layer, still, twice)
}
/// Whether `a` and `b` hold the same children, none of them copied.
fn same_children(a: &Node, b: &Node) -> bool {
let (a, b) = (a.children().unwrap(), b.children().unwrap());
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Arc::ptr_eq(a, b))
}
/// Stripping the ruler guides of a layer looks at each child of the layer and of its sublayers
/// once, however deep the sublayers nest. The art and its order stay, a sublayer without a guide is
/// not copied, and a copy of the layer held elsewhere keeps its guides.
#[test]
fn stripping_ruler_guides_looks_at_each_child_of_nested_layers_once() {
use std::cell::Cell;
let (whole, still, twice) = guide_layers();
let ids = |n: &Node| {
let mut out = vec![];
n.walk(&mut |c| out.push(c.id));
out
};
let mut art = vec![];
whole.walk(&mut |c| {
if !c.is_ruler_guide() {
art.push(c.id);
}
});
assert_eq!(ids(&whole).len(), art.len() + GUIDE_LAYER_GUIDES);
let mut n = whole.clone();
let looked = Cell::new(0_usize);
let pick = |c: &Node| {
looked.set(looked.get() + 1);
c.is_ruler_guide()
};
let held = super::ops::held_guides(&n, &pick).unwrap();
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "each child of the layers is looked at once");
super::ops::strip_held(&mut n, held);
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "removing looks at nothing again");
assert_eq!(ids(&n), art, "the art stays, in its order");
let ch = n.children().unwrap();
assert!(Arc::ptr_eq(&ch[1], &still), "a sublayer without a guide is not copied");
assert!(Arc::ptr_eq(&ch[3], &whole.children().unwrap()[3]), "an object is not copied");
assert!(!Arc::ptr_eq(&ch[2], &twice) && !Arc::ptr_eq(&ch[4], &twice) && !Arc::ptr_eq(&ch[2], &ch[4]));
assert_eq!(
(ch[2].children().map(Vec::len), ch[4].children().map(Vec::len)),
(Some(1), Some(1)),
"a sublayer lying twice is stripped at both places"
);
// The copies held elsewhere (an undo step's, say) keep their guides.
assert_eq!(twice.children().map(Vec::len), Some(2));
assert_eq!(ids(&whole).len(), art.len() + GUIDE_LAYER_GUIDES);
// The method strips the same guides.
let mut same = whole.clone();
same.strip_ruler_guides();
assert_eq!(same, n);
assert!(Arc::ptr_eq(&same.children().unwrap()[1], &still));
// With no guide left there is nothing to remove, and nothing is copied.
let before = n.clone();
n.strip_ruler_guides();
assert!(same_children(&n, &before));
let mut empty = Node::layer(NodeId(900), "Empty", LayerColor::Preset(0));
empty.strip_ruler_guides();
assert_eq!(empty.children().map(Vec::len), Some(0));
// Only a layer holds ruler guides: a group is left as it is, on its own and in a layer.
let mut group = Node::group(NodeId(901), vec![Arc::clone(&twice)]);
assert!(super::ops::held_guides(&group, &Node::is_ruler_guide).is_none());
group.strip_ruler_guides();
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
let group = Arc::new(group);
let mut around = Node::layer(NodeId(902), "Around", LayerColor::Preset(0));
around.children_mut().unwrap().push(Arc::clone(&group));
around.strip_ruler_guides();
assert!(Arc::ptr_eq(&around.children().unwrap()[0], &group));
}
/// Changing the positions of the ruler guides of a layer looks at each child of the layer and of
/// its sublayers once, however deep the sublayers nest. Each guide is changed once, in the order
/// the guides lie in, and keeps everything else about it; the art is unchanged, a sublayer without
/// a guide is not copied, and a copy of the layer held elsewhere keeps its positions.
#[test]
fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
use std::cell::Cell;
let (whole, still, twice) = guide_layers();
let mut lines = vec![];
whole.walk(&mut |c| {
if let NodeKind::RulerGuide { vertical, pos, .. } = c.kind {
lines.push((vertical, pos));
}
});
assert_eq!(lines.len(), GUIDE_LAYER_GUIDES);
assert!(lines.iter().any(|l| l.0) && lines.iter().any(|l| !l.0), "guides in both directions");
let mut n = whole.clone();
let looked = Cell::new(0_usize);
let pick = |c: &Node| {
looked.set(looked.get() + 1);
c.is_ruler_guide()
};
let held = super::ops::held_guides(&n, &pick).unwrap();
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
super::ops::map_held(&mut n, held, &mut |vertical, pos| {
seen.push((vertical, *pos));
*pos = *pos * 2.0 + 1.0;
});
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "changing looks at nothing again");
assert_eq!(seen, lines, "each guide once, in the order the guides lie in");
// The same nodes in the same order: a guide differs in its position alone, and the art not
// at all.
let (mut was, mut now) = (vec![], vec![]);
whole.walk(&mut |c| was.push(c));
n.walk(&mut |c| now.push(c));
assert_eq!(was.len(), now.len());
for (a, b) in was.into_iter().zip(now) {
if a.is_layer() {
assert_eq!((b.id, b.is_layer(), b.children().map(Vec::len)), (a.id, true, a.children().map(Vec::len)));
continue;
}
let mut want = a.clone();
if let NodeKind::RulerGuide { pos, .. } = &mut want.kind {
*pos = *pos * 2.0 + 1.0;
}
assert_eq!(b, &want);
}
let ch = n.children().unwrap();
assert!(Arc::ptr_eq(&ch[1], &still), "a sublayer without a guide is not copied");
assert!(Arc::ptr_eq(&ch[3], &whole.children().unwrap()[3]), "an object is not copied");
assert!(!Arc::ptr_eq(&ch[2], &twice) && !Arc::ptr_eq(&ch[4], &twice) && !Arc::ptr_eq(&ch[2], &ch[4]));
// The copy held elsewhere keeps its position.
assert!(matches!(twice.children().unwrap()[1].kind, NodeKind::RulerGuide { pos, .. } if pos == 512.0));
// The method changes the same guides, each once.
let mut same = whole.clone();
let mut calls = 0;
same.map_ruler_guide_positions(&mut |_, pos| {
calls += 1;
*pos = *pos * 2.0 + 1.0;
});
assert_eq!((calls, &same), (GUIDE_LAYER_GUIDES, &n));
assert!(Arc::ptr_eq(&same.children().unwrap()[1], &still));
// A function that leaves the positions as they are is still called on each guide.
let mut kept = whole.clone();
let mut calls = 0;
kept.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert_eq!((calls, &kept), (GUIDE_LAYER_GUIDES, &whole));
// A layer without a guide, an empty layer and a group: nothing to change, nothing copied.
let mut bare = whole.clone();
bare.strip_ruler_guides();
let before = bare.clone();
let mut calls = 0;
bare.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert!(same_children(&bare, &before));
let mut empty = Node::layer(NodeId(900), "Empty", LayerColor::Preset(0));
empty.map_ruler_guide_positions(&mut |_, _| calls += 1);
let mut group = Node::group(NodeId(901), vec![Arc::clone(&twice)]);
group.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
assert_eq!(calls, 0);
}
+54 -20
View File
@@ -429,6 +429,12 @@ const MAX_MEMBERS: usize = 4096;
/// normals): past it the object is too complex to export.
const MAX_MESH_TRIANGLES: usize = 2_000_000;
/// The most facets of solid colors under colored lights that one 3D effect draws as faces of their
/// own, to go in one order with other solids' faces. Each such face is about 16 nodes, a composite
/// of a whole surface about 6 per facet, so at this count the faces hold about as many nodes as the
/// composites do at the paint-copy allowance. Past it those solids draw as one composite each.
const MAX_FACE_COMPOSITES: usize = 30_720;
/// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path,
/// compound path and type in it (after [`resolve`] gives it the art of its symbol instances, blends
/// and clipping groups), at any depth of its groups, each through its own geometry
@@ -535,9 +541,12 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
}
/// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and
/// blend mode (so overlapping facets don't add up their transparency).
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool) -> Node {
if colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some()) {
/// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid
/// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless
/// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order
/// with the faces of other solids.
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node {
if !faces && composites_facets(&facets, paint, colored) {
let mut group = crate::lighting::solid_surface(n.id, &facets, paint);
group.opacity = opacity;
group.blend = blend;
@@ -583,6 +592,12 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
/// Is a surface of `facets` in `paint` one composite of all its facets when [`surface`] draws it
/// whole: a solid color under colored lights with smooth shading?
fn composites_facets(facets: &[Facet], paint: &Paint, colored: bool) -> bool {
colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some())
}
/// `item`'s paint, its opacity times `member` (the opacity of the objects it is in) and its blend.
fn paint_of(item: &AppearanceItem, member: f32) -> (Paint, f32, BlendMode) {
match item {
@@ -600,10 +615,10 @@ fn paint_ref(item: &AppearanceItem) -> &Paint {
}
/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored
/// lights give each facet derived paints (`lighting::solid_surface`).
/// lights give each facet derived paints (`lighting::solid_surface`, or `lighting::facet_art` for
/// each face).
fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize {
let derived = colored && paint.color().is_some() && facets.iter().any(|f| f.rgb_gradient.is_some());
facets.len().saturating_mul(if derived { 6 } else { 2 })
facets.len().saturating_mul(if composites_facets(facets, paint, colored) { 6 } else { 2 })
}
/// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the
@@ -1265,8 +1280,9 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// The 3D art of one effect `fx` on `path` (already through the effects before it).
/// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a
/// solid from the path for the top visible fill and one from the outline of each visible stroke,
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as
/// each in its own paint. When every one is opaque with normal blending, their faces are drawn in
/// one back-to-front order, a solid color under colored lights included up to
/// [`MAX_FACE_COMPOSITES`] facets (where depths tie, as
/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's
/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and
/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the
@@ -1521,7 +1537,8 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) });
}
}
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
let art =
if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored, false) };
out.push((s.scopes.as_slice(), Arc::new(art)));
}
}
@@ -1554,22 +1571,31 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
opacity >= 1.0 && blend == BlendMode::Normal
});
let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path));
// A solid whose surface is one composite of all its facets ([`surface`]: a solid color under
// colored lights with smooth shading) has no faces to order.
let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some());
// The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under
// a member's opacity mask or blending, each member's faces go in one order of their own when its
// fills and strokes are opaque, blend normally, carry no opacity mask and are not composites.
let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f));
// A solid color under colored lights with smooth shading draws as one composite of its facets
// ([`surface`]) unless its facets go in one order with other solids' faces. They do while all
// such facets together number at most MAX_FACE_COMPOSITES.
let composite = |item: &AppearanceItem, f: &[Facet]| composites_facets(f, paint_ref(item), colored);
let colored_faces: usize = solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum();
let split = colored_faces <= MAX_FACE_COMPOSITES;
// The faces are drawn in one order (below) when every solid is opaque and blends normally and
// no composite draws a surface whole. Under a member's opacity mask or blending, each member's
// faces go in one order of their own when its fills and strokes are opaque, blend normally,
// carry no opacity mask and are not composites.
let one_order = opaque && (split || !solids.iter().any(|(item, _, _, f, _)| composite(item, f)));
let shape_order: Vec<bool> = (0..shapes.len())
.map(|shape| {
solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| {
let (paint, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f)
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && (split || !composite(item, f))
})
})
.collect();
let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order };
// The solids whose faces share one order with another solid's: every solid in the one order of
// the object, or of its member under a mask. A lone solid draws its facets in their own order,
// so a solid color under colored lights stays one composite there ([`surface`]).
let shared: Vec<bool> =
(0..shapes.len()).map(|shape| ordered(shape) && solids.iter().filter(|s| !masks || s.4 == shape).nth(1).is_some()).collect();
if solids.iter().any(|s| ordered(s.4)) {
// A stroke face that passes through a fill wall or another stroke's face is cut where it
// does. The pieces count against the limits as the faces did: cutting stops before the
@@ -1605,6 +1631,10 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
.collect();
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
};
// With the pieces of the cuts, solid colors under colored lights past MAX_FACE_COMPOSITES draw
// as one composite each, so their surfaces draw whole (below).
let split =
split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::<usize>() <= MAX_FACE_COMPOSITES;
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
@@ -1613,7 +1643,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
let art = if classic {
classic::surface(n, f, &paint, opacity, blend, &p)
} else {
surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false))
};
(depths, art, scopes, ends)
})
.collect();
@@ -1622,8 +1656,8 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
_ => extrude_options(&p).cap,
};
// One order takes a plain group of faces from each solid, one face for each facet. With
// colored lights a surface can instead be one clipped composite of all its facets. A composite
// One order takes a plain group of faces from each solid, one face for each facet. A lone
// solid's surface can instead be one clipped composite of all its facets ([`surface`]), which
// has no faces to order, so it draws whole.
let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len());
if masks {
+229 -14
View File
@@ -491,8 +491,8 @@ fn a_masked_members_fill_and_stroke_faces_go_in_one_order() {
}
/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the
/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color,
/// drawn as one composite of each surface's facets, still draws each surface whole.
/// fill's and the dashed stroke's faces in one order, as it does under a white light, and so does
/// Inflate in solid colors.
#[test]
fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
@@ -530,9 +530,111 @@ fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len();
assert_eq!(white.1, cut, "the white light's faces, cut");
assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light");
// A solid color under the colored light: a composite for each of the fill and the stroke.
// A solid color under the colored light: the fill's and the stroke's faces in one order too.
let solid = stroked(&letter_c());
assert_eq!(drawn(&solid, Some(colored)).0, 2);
assert_eq!(drawn(&solid, Some(colored)).0, 1);
}
/// The bounds of face `f` of 3D art: its path's, or for a clipped colored composite
/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 1 pt.
fn drawn_face_bounds(f: &Node) -> Rect {
match &f.kind {
NodeKind::Path { .. } => f.path_data().and_then(PathData::bounds).unwrap(),
NodeKind::Group { clip: true, children } => {
let cover = &children[1].children().unwrap()[0];
cover.path_data().and_then(PathData::bounds).unwrap().inflate(-1.0, -1.0)
}
_ => panic!("a face is a path or a clipped composite"),
}
}
/// Under a light that is not white, a solid-color fill and a solid-color stroke, plain, dashed or
/// with a width profile, draw their faces in one order, the faces of both solids in the order of
/// their depths where they overlap, in Inflate and in Extrude & Bevel, with and without perspective
/// and in a member with an opacity mask. Drawing each solid whole, the fill's faces before the
/// stroke's, shows farther faces on top.
#[test]
fn colored_solid_fills_and_strokes_share_face_depth_order() {
use vectorcraft_doc::{Dash, WidthProfile};
type Style<'a> = (&'a str, &'a dyn Fn(&mut StrokeLayer));
let styles: [Style; 3] = [
("plain", &|_| {}),
("dashed", &|s| s.dash = Some(Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false })),
("profiled", &|s| s.profile = Some(WidthProfile::lens())),
];
let views = [
json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}),
json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}),
];
let mut whole_misdrawn = 0;
for id in [INFLATE, EXTRUDE] {
for view in &views {
for (style, set) in &styles {
let mut params = view.clone();
params["depth"] = json!(60);
params["lights"] = json!([{"color": "#ff8080"}, {"color": "#4060ff", "rotation": 120}]);
let mut n = stroked(&letter_c());
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
set(s);
}
let what = format!("{id} {view} {style}");
let parts = drawn_parts(&n, id, &params);
if id == INFLATE {
assert!(parts.iter().any(|(f, ..)| f.rgb_gradient.is_some()), "{what}: smooth colored facets");
}
let mut with = n.clone();
with.appearance.effects.push(fx(id, params.clone()));
let art = solid_art(&with).unwrap();
let surfaces = art.children().unwrap();
assert_eq!(surfaces.len(), 1, "{what}: one order");
let faces = surfaces[0].children().unwrap();
assert_eq!(faces.len(), parts.len(), "{what}: one face per facet");
for (k, (face, (facet, ..))) in faces.iter().zip(&parts).enumerate() {
let (a, b) = (drawn_face_bounds(face), facet.path().bounds().unwrap());
let close = [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6);
assert!(close, "{what}: face {k} drawn out of the order of the depths");
}
let allowed = if id == INFLATE { 5 } else { 0 };
let wrong = misdrawn(&parts);
assert!(wrong.len() <= allowed, "{what}: {} points show a farther face, first {:?}", wrong.len(), wrong.first());
// The same faces drawn as two whole surfaces, the fill's then the stroke's.
let mut whole = parts.clone();
whole.sort_by_key(|(_, part, _)| *part);
whole_misdrawn += misdrawn(&whole).len();
// In a group, under the member's opacity mask, the faces keep the same order.
if id == INFLATE && *style == "plain" {
let cover = Node::path(
NodeId(900),
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)),
Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0),
);
let mut masked = n.clone();
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true)));
let mut plain = Node::group(NodeId(2), vec![Arc::new(n.clone())]);
plain.appearance.effects.push(fx(id, params.clone()));
let mut g = Node::group(NodeId(2), vec![Arc::new(masked)]);
g.appearance.effects.push(fx(id, params.clone()));
let bounds = |art: &Node| {
let mut out = vec![];
art.walk(&mut |n| {
if let NodeKind::Group { clip: true, .. } = &n.kind {
out.push(drawn_face_bounds(n));
}
});
out
};
let (plain, scoped) = (solid_art(&plain).unwrap(), solid_art(&g).unwrap());
let mut masks = 0;
scoped.walk(&mut |n| masks += usize::from(n.extras().mask.is_some()));
assert!(masks > 0, "{what}: drawn in the member's mask");
let ordered = bounds(&plain);
assert!(ordered.len() > 100, "{what}: clipped faces");
assert_eq!(bounds(&scoped), ordered, "{what}: the member's faces in one order");
}
}
}
}
assert!(whole_misdrawn > 0, "whole surfaces show farther faces");
}
/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they
@@ -1322,11 +1424,12 @@ fn legacy_white_inflate_keeps_polygon_faces_and_its_seam_range() {
assert!(faces(&art).iter().all(|face| matches!(face.kind, NodeKind::Path { .. })));
}
/// A solid color under colored lights is one composite of all its facets, with one clip and a fixed
/// number of groups, where its solid's faces draw in no order shared with another solid's: a lone
/// fill, or a fill and a translucent stroke. A fill and an opaque stroke draw each face on its own,
/// in one order.
#[test]
fn colored_solid_inflate_batches_channels_and_clips_once_per_surface() {
let mut n = square_node();
n.appearance.effects.push(fx(INFLATE, json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff"}]})));
let art = solid_art(&n).unwrap();
fn count(n: &Node) -> (usize, usize, usize) {
let (mut groups, mut clips, mut paths) = match &n.kind {
NodeKind::Group { clip, .. } => (1, usize::from(*clip), 0),
@@ -1341,13 +1444,125 @@ fn colored_solid_inflate_batches_channels_and_clips_once_per_surface() {
}
(groups, clips, paths)
}
let (groups, clips, paths) = count(&art);
assert!(paths > 1000, "exercise a tessellated surface");
// The fill's solid and the stroke's, each one composite with its own clip.
let surfaces = art.children().unwrap().len();
assert_eq!(surfaces, 2);
assert_eq!(clips, surfaces);
assert_eq!(groups, 1 + 6 * surfaces, "group count must not grow with triangle count");
let lights = json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff"}]});
let lone = |n: &mut Node| n.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_)));
let translucent = |n: &mut Node| {
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
s.opacity = 0.5;
}
};
for (what, set, surfaces) in [("a lone fill", &lone as &dyn Fn(&mut Node), 1), ("a translucent stroke", &translucent, 2)] {
let mut n = square_node();
set(&mut n);
n.appearance.effects.push(fx(INFLATE, lights.clone()));
let art = solid_art(&n).unwrap();
let (groups, clips, paths) = count(&art);
assert!(paths > 1000, "{what}: exercise a tessellated surface");
// Each solid one composite with its own clip.
assert_eq!(art.children().unwrap().len(), surfaces, "{what}");
assert_eq!(clips, surfaces, "{what}");
assert_eq!(groups, 1 + 6 * surfaces, "{what}: group count must not grow with triangle count");
}
// An opaque fill and stroke: one order of faces, each its own clipped composite or shaded path.
let mut n = square_node();
n.appearance.effects.push(fx(INFLATE, lights));
let art = solid_art(&n).unwrap();
let surfaces = art.children().unwrap();
assert_eq!(surfaces.len(), 1, "one order");
let faces = surfaces[0].children().unwrap();
assert!(faces.len() > 100, "one face per facet");
assert!(faces.iter().all(|f| matches!(&f.kind, NodeKind::Path { .. } | NodeKind::Group { clip: true, .. })));
assert!(faces.iter().any(|f| matches!(&f.kind, NodeKind::Group { clip: true, .. })), "colored ramps");
}
/// Solid colors under colored lights go in one order of faces while their facets together, with the
/// pieces of the cuts, number at most `MAX_FACE_COMPOSITES`. Past it each solid draws whole, as one
/// composite.
#[test]
fn colored_solids_past_the_face_limit_draw_as_composites() {
let lights = json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff","rotation":90}]});
let mut base = square_node();
base.appearance.effects.push(fx(INFLATE, lights.clone()));
let stroke = base.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).cloned().unwrap();
// The facets each solid draws under these lights. Strokes alike each build the same solid.
let shapes = [Profile { path: profile(&base).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&base), opacity: 1.0, scopes: vec![] }];
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let counts: Vec<usize> = built_solids(INFLATE, &crate::merged_params(INFLATE, &lights), &parts, bounds, MAX_OBJECT_FACES)
.map(|f| f.unwrap().map_or(0, |f| f.len()))
.collect();
let [fill, each] = counts[..] else { panic!("a fill's solid and a stroke's") };
let fits = (MAX_FACE_COMPOSITES - fill) / each;
assert!(fits >= 4, "{fill} + {fits} × {each}");
// Under the limit; under it before the cuts but past it with their pieces; past it before them.
let mut seen = vec![];
for strokes in [fits / 2, fits, fits + 1] {
let mut n = base.clone();
n.appearance.items.extend(std::iter::repeat_n(stroke.clone(), strokes - 1));
let uncut = fill + strokes * each;
let cut = drawn_parts(&n, INFLATE, &lights).len();
let one_order = cut <= MAX_FACE_COMPOSITES;
seen.push((uncut <= MAX_FACE_COMPOSITES, one_order));
let art = solid_art(&n).unwrap();
let surfaces = art.children().unwrap();
if one_order {
assert_eq!(surfaces.len(), 1, "{uncut} faces, {cut} cut: one order");
} else {
assert_eq!(surfaces.len(), 1 + strokes, "{uncut} faces, {cut} cut: each solid whole");
assert!(surfaces.iter().all(|s| s.children().is_some_and(|c| c.len() < 10)), "each solid one composite");
}
}
assert_eq!(seen, [(true, true), (true, false), (false, false)], "every case");
}
/// A solid-color face drawn on its own under colored lights takes the same colors as in the
/// surface's one composite: the paint, multiplied by the same red, green and blue light ramps, and
/// a seam of the same width.
#[test]
fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() {
let n = square_node();
let p = crate::merged_params(INFLATE, &json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff","rotation":90}]}));
let (path, rule) = profile(&n).unwrap();
let all = facets(INFLATE, &path, rule, path.bounds().unwrap(), &p).unwrap();
let face = all
.iter()
.find(|f| f.rgb_gradient.is_some_and(|g| g.channels[0] != g.channels[1] || g.channels[1] != g.channels[2]))
.expect("a facet with colored ramps")
.clone();
let paint = Paint::solid(RED);
// Each node's own fill paint, and its seam stroke's width, for every node under `n`.
let paints = |n: &Node| {
let mut out = vec![];
n.walk(&mut |n| {
for item in &n.appearance.items {
match item {
AppearanceItem::Fill(f) => out.push((Some(f.paint.clone()), None)),
AppearanceItem::Stroke(s) => out.push((None, Some(s.width))),
}
}
});
out
};
let alone = surface(&n, vec![face.clone()], &paint, 1.0, BlendMode::Normal, true, true);
let batch = surface(&n, vec![face.clone()], &paint, 1.0, BlendMode::Normal, true, false);
let [single] = alone.children().unwrap().as_slice() else { panic!("one face") };
assert!(matches!(&single.kind, NodeKind::Group { clip: true, .. }), "a clipped face");
// The face's paint cover and its three channel ramps.
let fills = |n: &Node| paints(n).into_iter().filter_map(|(f, _)| f).collect::<Vec<_>>();
let one = fills(single);
assert_eq!(one.len(), 4);
assert_eq!(one[0], paint, "the paint");
// The composite: its paint cover, then each channel's black backdrop and the face's ramp.
let all_fills = fills(&batch);
let ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect();
assert_eq!(all_fills.first(), Some(&paint));
assert_eq!(ramps, one.iter().skip(1).collect::<Vec<_>>(), "the same light ramps");
// The single face's clip holds its seam: the clip reaches past the facet by half the seam.
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0).collect();
assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}");
let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") };
let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap());
assert!((clip.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (clip.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1, "{clip:?} {facet:?}");
}
/// `square_node` moved right by `dx`, with id `id` and fill `fill`.
+2 -2
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply as Filter",
["Object", "Plug-ins", "Color Effects"],
None,
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step; their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed}",
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed}",
has_selection,
filter
),
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Nearest Swatch",
["Object", "Plug-ins", "Color Effects"],
None,
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
has_selection,
nearest::apply
),
@@ -713,6 +713,71 @@ fn corner_commands_refuse_bad_params() {
}
}
#[test]
fn corner_commands_refuse_an_unknown_item_key() {
let mut s = session();
let id = square(&mut s);
let i = id.0;
let set = json!({"items": [{"id": i, "anchor": [0]}], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &set).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[0].anchor`; did you mean `items[0].anchors`?"), "{e}");
let set_late = json!({"items": [{"id": i, "anchors": [0]}, {"id": i, "radius": 3}], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &set_late).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[1].radius`; the command takes: items[1].id, items[1].anchors"), "{e}");
refuses(&mut s, "addon.pathtools.cornerSet", &[set, set_late]);
s.execute("addon.pathtools.cornerSet", &json!({"radius": 10})).unwrap();
let remove = json!({"items": [{"id": i, "anchor": [0]}]});
let e = s.execute("addon.pathtools.cornerRemove", &remove).unwrap_err().to_string();
assert!(e.contains("unknown parameter `items[0].anchor`; did you mean `items[0].anchors`?"), "{e}");
refuses(&mut s, "addon.pathtools.cornerRemove", &[remove]);
assert_eq!(drawn(&s, id, 0), 10.0);
}
#[test]
fn corner_items_take_their_documented_keys() {
let mut s = session();
let id = square(&mut s);
let i = id.0;
let r = s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": i, "anchors": [0]}], "radius": 5})).unwrap();
assert_eq!((r["corners"].clone(), drawn(&s, id, 0), drawn(&s, id, 1)), (json!(1), 5.0, 0.0));
// A member without `anchors` takes the request's.
s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": i}], "anchors": [2], "radius": 6})).unwrap();
assert_eq!(drawn(&s, id, 2), 6.0);
let r = s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": i, "anchors": [0]}]})).unwrap();
assert_eq!((r["corners"].clone(), drawn(&s, id, 0), drawn(&s, id, 2)), (json!(1), 0.0, 6.0));
// A null `ids` beside `items` counts as not given.
s.execute("addon.pathtools.cornerRemove", &json!({"items": [{"id": i}], "ids": null})).unwrap();
assert_eq!(drawn(&s, id, 2), 0.0);
}
#[test]
fn corner_commands_refuse_items_with_ids() {
let mut s = session();
let id = square(&mut s);
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
let both = json!({"items": [{"id": id.0, "anchors": [0]}], "ids": [other.0], "radius": 5});
let e = s.execute("addon.pathtools.cornerSet", &both).unwrap_err().to_string();
assert!(e.contains("give `items` or `ids`, not both"), "{e}");
refuses(&mut s, "addon.pathtools.cornerSet", &[both]);
s.execute("addon.pathtools.cornerSet", &json!({"ids": [id.0], "radius": 5})).unwrap();
let both = json!({"items": [{"id": id.0}], "ids": [id.0]});
let e = s.execute("addon.pathtools.cornerRemove", &both).unwrap_err().to_string();
assert!(e.contains("give `items` or `ids`, not both"), "{e}");
refuses(&mut s, "addon.pathtools.cornerRemove", &[both]);
}
#[test]
fn saved_corner_steps_with_older_item_keys_still_play() {
let mut s = session();
let id = square(&mut s);
let other = line(&mut s, &[(350.0, 10.0), (390.0, 10.0), (390.0, 50.0)], false);
let saved = json!({"items": [{"id": id.0, "anchors": [0], "old": 1}], "ids": [other.0], "radius": 5});
s.replay("addon.pathtools.cornerSet", &saved).unwrap();
assert_eq!((drawn(&s, id, 0), drawn(&s, id, 1)), (5.0, 0.0));
s.replay("addon.pathtools.cornerRemove", &json!({"items": [{"id": id.0, "old": 1}]})).unwrap();
assert_eq!(drawn(&s, id, 0), 0.0);
}
/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd
/// numbers counting from 1), its inner corners at the odd ones.
fn star_path(s: &mut Session) -> NodeId {
+32 -5
View File
@@ -419,6 +419,27 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>>
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
}
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it";
/// The [`appearance_targets`] whose rows and effects a command edits: the art of graph designs drawn in graph series
/// ([`super::graph::is_design_art`]) is left out, as the graph draws it again from the design. A command whose targets
/// are all such art is refused.
pub(crate) fn edit_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let ids = appearance_targets(s, p)?;
without_design_art(&s.doc()?.doc, ids, "appearance")
}
/// `ids` without the art of graph designs drawn in graph series; `cmd` is refused when `ids` held nothing else.
pub(crate) fn without_design_art(d: &Document, mut ids: Vec<NodeId>, cmd: &str) -> Result<Vec<NodeId>> {
let given = ids.len();
ids.retain(|id| !super::graph::is_design_art(d, *id));
if given > 0 && ids.is_empty() {
return Err(bad(cmd, DESIGN_ART));
}
Ok(ids)
}
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
/// the Appearance panel lists those rows and edits them by index.
@@ -453,17 +474,17 @@ pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n)
}
/// Objects whose fill and stroke rows a command edits: the [`appearance_targets`], with a graph series group standing
/// for the paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
/// Objects whose fill and stroke rows a command edits: the [`edit_targets`], with a graph series group standing for the
/// paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let ids = appearance_targets(s, p)?;
let ids = edit_targets(s, p)?;
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
}
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
/// which can hold effects and a graphic style link of its own.
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let own = appearance_targets(s, p)?;
let own = edit_targets(s, p)?;
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
let groups = stood_for(&own, &ids);
ids.extend(groups);
@@ -869,6 +890,11 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`source` and `target` are the same object"));
}
let copy = switch_or(p, "copy", false, C)?;
// The art of a graph design in a series is read as a source, but neither takes an appearance nor gives one up.
without_design_art(&s.doc()?.doc, vec![target], C)?;
if !copy {
without_design_art(&s.doc()?.doc, vec![source], C)?;
}
// A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a
// move clears them all; as the target, each of them other than a source takes the appearance.
let sources = look_holders(&s.doc()?.doc, source);
@@ -1245,7 +1271,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
let aligned = aligned(p, C)?;
if p.get("from").and_then(Value::as_str) == Some("contents") {
// A graph series group's own Contents row, not its paths, which have none.
let ids = appearance_targets(s, p)?;
let ids = edit_targets(s, p)?;
if ids.is_empty() {
return Err(bad(C, "select objects or give ids"));
}
@@ -1447,6 +1473,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
(Some(clicked), leaf_targets(s, &selected)?)
};
targets.retain(|id| Some(*id) != source);
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
let node = match source {
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
+5 -5
View File
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Live Paint"],
Some("Cmd+Alt+X"),
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does → {id, faces, edges}",
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
has_selection_or_ids,
lp_make
),
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Merge",
["Object", "Live Paint"],
None,
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link) → {id, faces, edges}",
"{ids?|id?} add the other selected paths (compound paths, groups of paths and Live Paint groups too; type, images and other objects are refused, nothing changes) to the bottom-most Live Paint group, keeping its id, its paint and its own properties (name, lock, visibility, transparency, appearance, opacity mask, graphic style link); a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
has_multi_or_ids,
lp_merge
),
@@ -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; 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)}",
"{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; when every group already has the options and closeGaps finds no gap, nothing changes (no undo step) → {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], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), 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}",
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), 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; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}",
has_doc,
lp_fill
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point → {group, edge}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}",
has_doc,
lp_stroke_edge
),
+135 -33
View File
@@ -52,8 +52,34 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<
Ok((gid, nf, ne))
}
/// Select `ids` alone, without an undo step, when they are not selected that way already.
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
let st = s.doc()?;
let mut sel = st.selection.clone();
sel.set(ids.iter().copied());
if sel != st.selection {
s.select(|_, selection| *selection = sel)?;
}
Ok(())
}
/// Make or Merge given one Live Paint group and nothing else has nothing to add to it, so it leaves
/// the document as it is, records no undo step and selects the group: → its reply. `None` for any
/// other `roots`.
fn lone_live_group(s: &mut Session, roots: &[NodeId]) -> Result<Option<Value>> {
let d = &s.doc()?.doc;
let Some(&g) = roots.first().filter(|g| roots.iter().all(|r| r == *g)) else { return Ok(None) };
let Some(n) = d.node(g).filter(|n| is_live_paint(n)) else { return Ok(None) };
let reply = json!({ "id": g.0, "faces": b::faces(n).len(), "edges": b::edges(n).len() });
select_only(s, &[g])?;
Ok(Some(reply))
}
pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
let roots = root_ids(s, p)?;
if let Some(reply) = lone_live_group(s, &roots)? {
return Ok(reply);
}
let (id, faces, edges) = s.edit("Make Live Paint", |d, sel| make_live(d, sel, &roots))?;
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
@@ -130,6 +156,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
let roots = root_ids(s, p)?;
if let Some(reply) = lone_live_group(s, &roots)? {
return Ok(reply);
}
let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
@@ -230,27 +259,58 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
};
let close = switch_or(p, "closeGaps", false, C)?;
let targets = live_targets(s, p)?;
let with_params = |mut options: GapOptions| {
options.detect = detect.unwrap_or(options.detect);
options.size = size.unwrap_or(options.size);
options.color = color.unwrap_or(options.color);
options
};
// When every group already has these options and Close Gaps With Paths has no gap to close,
// nothing changes: no undo step, and the reply is the same.
let unchanged = {
let d = &s.doc()?.doc;
let (mut faces, mut gaps, mut same) = (0, vec![], true);
for g in &targets {
let old = d.node(*g).ok_or(EngineError::NoNode(*g))?;
let options = old.gap_options();
if with_params(options) != options {
same = false;
break;
}
let open = open_gaps(old, options);
if close && !open.is_empty() {
same = false;
break;
}
faces += b::faces(old).len();
gaps.extend(open);
}
same.then_some((faces, gaps))
};
if let Some((faces, gaps)) = unchanged {
select_only(s, &targets)?;
return Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": 0 }));
}
let (faces, gaps, closed) = s.edit("Gap Options", |d, sel| {
let (mut faces, mut gaps, mut closed) = (0, vec![], 0);
let mut changed = Beside::replacing(d, &targets);
for g in &targets {
let old = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
let mut options = old.gap_options();
options.detect = detect.unwrap_or(options.detect);
options.size = size.unwrap_or(options.size);
options.color = color.unwrap_or(options.color);
let options = with_params(old.gap_options());
let mut sources = source_nodes(&old);
let mut added = 0;
if close {
// Close Gaps With Paths adds an unpainted line across each gap to the group's paths.
for gap in po::find_gaps(&source_shapes(&sources).0, options.size.points()) {
let line = PathData::single(SubPath::polyline(&gap, false));
sources.push(Arc::new(Node::path(d.alloc_id(), line, Appearance::default())));
closed += 1;
added += 1;
}
}
closed += added;
let mut n = old.clone();
// The faces change only with what paint stops at, or with new paths.
if close || options.max_gap() != old.gap_options().max_gap() {
if added > 0 || options.max_gap() != old.gap_options().max_gap() {
let (children, _, _) = build_children(d, sources, options.max_gap())?;
if let Some(ch) = n.children_mut() {
*ch = children;
@@ -305,27 +365,9 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
let group = object_param(p, "group", C)?;
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
let (g, face) = s.edit("Live Paint Bucket", |d, sel| {
let gid = match group {
Some(g) => {
if !d.node(g).is_some_and(is_live_paint) {
return Err(bad(C, format!("{g} is not a Live Paint group")));
}
g
}
None => {
let live_at = |face: fn(&Node, Point) -> Option<&Arc<Node>>| {
roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face(n, pt).is_some()))
};
match (live_at(b::visible_face_at), live_at(face_at)) {
(Some(g), _) => g,
// At a point on a hidden face of a Live Paint group among the objects, the command returns an error
// and does not merge the objects.
(None, Some(_)) => return Err(EngineError::Other("no Live Paint face at that point".into())),
(None, None) => make_live(d, sel, &roots)?.0,
}
}
};
// The faces the click or drag paints in Live Paint group `gid`: the visible face at the point,
// and every visible face the drag crosses; → (the face at the point, the faces).
let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet<NodeId>)> {
let fid = d
.node(gid)
.and_then(|n| b::visible_face_at(n, pt))
@@ -355,11 +397,58 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
}
}
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
Ok((fid, targets))
};
// The Live Paint group the fill paints; `None` when the objects are made into one first.
let live = {
let d = &s.doc()?.doc;
match group {
Some(g) => {
if !d.node(g).is_some_and(is_live_paint) {
return Err(bad(C, format!("{g} is not a Live Paint group")));
}
Some(g)
}
None => {
let live_at = |face: fn(&Node, Point) -> Option<&Arc<Node>>| {
roots.iter().copied().find(|r| d.node(*r).is_some_and(|n| is_live_paint(n) && face(n, pt).is_some()))
};
match (live_at(b::visible_face_at), live_at(face_at)) {
(Some(g), _) => Some(g),
// At a point on a hidden face of a Live Paint group among the objects, the command returns an error
// and does not merge the objects.
(None, Some(_)) => return Err(EngineError::Other("no Live Paint face at that point".into())),
(None, None) => None,
}
}
}
Ok((gid, fid))
})?;
};
let (g, face) = match live {
Some(gid) => {
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
// Faces that already have the paint stay as they are: when every face has it, nothing
// changes and no undo step is recorded.
let d = &s.doc()?.doc;
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
if unpainted.is_empty() {
return Ok(json!({ "group": gid.0, "face": fid.0 }));
}
s.edit("Live Paint Bucket", |d, _| {
for target in unpainted {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
Ok((gid, fid))
})?
}
None => s.edit("Live Paint Bucket", |d, sel| {
let gid = make_live(d, sel, &roots)?.0;
let (fid, targets) = targets_in(d, gid)?;
for target in targets {
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
}
Ok((gid, fid))
})?,
};
s.remember_paint(&paint);
Ok(json!({ "group": g.0, "face": face.0 }))
}
@@ -375,9 +464,22 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "width out of range"));
}
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let edge = s.edit("Live Paint Bucket", |d, _| {
let (eid, unchanged) = {
let d = &s.doc()?.doc;
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
let eid = b::visible_edge_near(n, pt, tol).map(|e| e.id).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
// An edge that already has the paint and the width (or has no stroke and gets none) stays as
// it is, and no undo step is recorded.
let unchanged = match e.appearance.stroke() {
Some(st) => st.paint == paint && st.width == width,
None => paint.is_none(),
};
(e.id, unchanged)
};
if unchanged {
return Ok(json!({ "group": g.0, "edge": eid.0 }));
}
let edge = s.edit("Live Paint Bucket", |d, _| {
let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
e.appearance.set_stroke(paint.clone());
if let Some(st) = e.appearance.stroke_mut() {
+48 -30
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Invert Colors",
["Edit", "Edit Colors"],
None,
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
has_selection,
|s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert)
),
@@ -104,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Front to Back",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects (solid fills or gradient meshes, which keep their shading): intermediate fills graded between the frontmost and backmost fill. On a path directly in a graph series, the graph also stores the new fill, as for the other Blend commands (docs/mcp.md) → {changed}",
"{} ≥3 filled objects (solid fills or gradient meshes, which keep their shading): intermediate fills graded between the frontmost and backmost fill. On a path directly in a graph series, the graph also stores the new fill, as for the other Blend commands (docs/mcp.md); no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Stack)
),
@@ -113,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Horizontally",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects or meshes: fills graded between the leftmost and rightmost → {changed}",
"{} ≥3 filled objects or meshes: fills graded between the leftmost and rightmost; no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Horizontal)
),
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Vertically",
["Edit", "Edit Colors"],
None,
"{} ≥3 filled objects or meshes: fills graded between the topmost and bottommost → {changed}",
"{} ≥3 filled objects or meshes: fills graded between the topmost and bottommost; no undo step when no fill changes → {changed}",
has_selection,
|s, _| blend(s, BlendOrder::Vertical)
),
@@ -457,8 +457,8 @@ pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str,
run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p, cmd)?, f, links))
}
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`;
/// errors name the command `cmd`. The reply's `notChanged` counts the locked and hidden objects the
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`,
/// or none when the pass changes nothing; errors name the command `cmd`. The reply's `notChanged` counts the locked and hidden objects the
/// selection left out ([`left_out`]) that the pass would have changed.
fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -> Result<Value> {
let (ids, left) = match ids_param(p, "ids", cmd)? {
@@ -471,20 +471,47 @@ fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -
}
};
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let (n, not_changed) = s.edit(label, |d, _| {
let (n, not_changed) = edit_if_changed(s, label, |_, d| {
let not_changed = NotChanged::of(pass.again().would_change(d, &left).into_iter().map(|(_, hidden)| hidden));
let n = keeping_series_paint(d, &ids, |d| {
let n = pass.run(d, &ids);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(cmd, e))?;
Ok(n)
})?;
Ok((n, not_changed))
Ok(((n, not_changed), n > 0))
})?;
let mut out = json!({ "changed": n });
not_changed.report(&mut out);
Ok(out)
}
/// [`Session::edit`] for an Edit Colors pass, which may change nothing: `f` runs on a copy of the
/// document (it gets the document as it is too) and returns its result with whether it changed the
/// copy. Only a changed copy becomes the document, as one undo step named `label`; otherwise the
/// undo and redo steps and the saved state stay as they were.
pub(crate) fn edit_if_changed<T>(s: &mut Session, label: &str, f: impl FnOnce(&Document, &mut Document) -> Result<(T, bool)>) -> Result<T> {
if s.script_running() {
return Err(EngineError::Busy);
}
// A typing session ends here as `s.edit` would end it, before the copy is taken, so that the
// copy holds what was typed.
if !s.previewing && super::typing_in_progress(s) {
super::settle_interaction(s)?;
}
let before = s.doc()?.doc.clone();
let mut doc = (*before).clone();
let (v, changed) = f(&before, &mut doc)?;
// The document is shared with `before` no longer, so `s.edit` does not copy it again.
drop(before);
if changed {
s.edit(label, |d, _| {
*d = doc;
Ok(())
})?;
}
Ok(v)
}
/// Run `recolor` on `d` (it returns how many objects it changed) over `roots`, then store on their graphs what it changed
/// on the graph series marks among `roots` and inside them, so the marks keep their new paint when the graph is drawn
/// again.
@@ -597,11 +624,6 @@ fn pass_targets(s: &Session, p: &Value, cmd: &str) -> Result<Targets> {
fn to_indexed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.colors.toIndexed";
let indexing = Indexing::of(s, p)?;
// A typing session ends here as `s.edit` would end it, before the copy is taken, so that the
// copy holds what was typed.
if !s.previewing && super::typing_in_progress(s) {
super::settle_interaction(s)?;
}
let remake = |b: &ImageBlob| indexing.convert(b);
let images = Scope { fill: false, stroke: false, images: true, patterns: false };
let pass = Recolor { remake: Some(&remake), ..Recolor::new(images, &same) };
@@ -609,22 +631,18 @@ fn to_indexed(s: &mut Session, p: &Value) -> Result<Value> {
// indexed PNG yet; it is not converted to find out. The empty PNG only gives it a new key.
let would = |b: &ImageBlob| (!b.indexed_png() && b.pixel_size().is_some()).then(|| ImageBlob::png(vec![]));
let (ids, left) = pass_targets(s, p, C)?;
let st = s.doc()?;
let colorized_ok = super::paint::check_colorized(&st.doc).is_ok();
let not_changed = NotChanged::of(
Recolor { remake: Some(&would), ..Recolor::new(images, &same) }.would_change(&st.doc, &left).into_iter().map(|(_, hidden)| hidden),
);
let mut doc = (*st.doc).clone();
let n = pass.run(&mut doc, &ids);
if let Some((w, h)) = indexing.too_large.get() {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to convert (at most {} pixels)", Indexing::MAX_PIXELS)));
}
if n > 0 {
s.edit("Convert to Indexed Color", |d, _| {
*d = doc;
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))
})?;
}
let (n, not_changed) = edit_if_changed(s, "Convert to Indexed Color", |now, doc| {
let colorized_ok = super::paint::check_colorized(now).is_ok();
let not_changed = NotChanged::of(
Recolor { remake: Some(&would), ..Recolor::new(images, &same) }.would_change(now, &left).into_iter().map(|(_, hidden)| hidden),
);
let n = pass.run(doc, &ids);
if let Some((w, h)) = indexing.too_large.get() {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to convert (at most {} pixels)", Indexing::MAX_PIXELS)));
}
super::paint::check_colorized_kept(colorized_ok, doc).map_err(|e| bad(C, e))?;
Ok(((n, not_changed), n > 0))
})?;
let mut out = json!({ "changed": n });
not_changed.report(&mut out);
Ok(out)
@@ -923,7 +941,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result<Value> {
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(label, e))?;
Ok(changed)
};
let changed = s.edit(label, |d, _| keeping_series_paint(d, &ids, run))?;
let changed = edit_if_changed(s, label, |_, d| keeping_series_paint(d, &ids, run).map(|n| (n, n > 0)))?;
Ok(json!({ "changed": changed }))
}
@@ -536,6 +536,80 @@ fn a_document_replaced_in_the_back_is_measured_when_the_front_one_closes() {
assert_eq!(actual.cached_bounds, Some(expected));
}
/// The type of document `index` with id `id`, wherever its tab is.
fn text_in(s: &Session, index: usize, id: u64) -> vectorcraft_doc::TextObject {
match &s.documents()[index].doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
/// A document replaced while in the back has its type measured in its own composite fonts at once,
/// while the front document stays in front with its own definition registered; coming to the front
/// does not measure that type again.
#[test]
fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() {
let (bytes, id, width) = full_roman_file("CF Pane");
let mut s = session();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Pane")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
assert_eq!(s.active_index(), Some(1));
let front = vectorcraft_text::FontDb::global().composite_font("CF Pane").unwrap();
assert_eq!(front.parts.get(vectorcraft_doc::CharClass::Roman).size, 50.0);
let measured = text_in(&s, 0, id);
assert!((measured.cached_bounds.unwrap().width() - width).abs() < 1e-6);
let node = s.documents()[0].doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
assert!((node.width() - width).abs() < 1e-6);
let doc = std::sync::Arc::as_ptr(&s.documents()[0].doc);
assert!(s.set_active(0));
assert!(std::ptr::eq(doc, std::sync::Arc::as_ptr(&s.documents()[0].doc)));
assert_eq!(text(&s, id).cached_bounds, measured.cached_bounds);
}
/// Type a document replaced in the back sets in a composite font that only the front document
/// defines is measured in that font while the front one is registered, and again, as missing, when
/// the replaced document comes to the front.
#[test]
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
let back = text_in(&s, 0, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds;
assert_eq!(back.cached_bounds, Some(expected));
assert!(s.set_active(0));
assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none());
let actual = text(&s, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// Text holding an inline graphic whose symbol's art is type in a composite font, in a document
/// replaced in the back, is measured with the graphic at the size the document's own definition
/// gives it before it comes to the front.
#[test]
fn a_document_replaced_in_the_back_measures_inline_graphics_in_its_own_definition() {
let mut s = session();
let mut full = font("CF Back Inline");
full["parts"]["roman"]["size"] = json!(100);
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
let art =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Back Inline"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.new", &json!({"name": "CF Back Inline Mark", "ids": [art]})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "x", "size": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "CF Back Inline Mark"})).unwrap();
let width = text(&s, id).cached_bounds.unwrap().width();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Back Inline")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
assert!((text_in(&s, 0, id).cached_bounds.unwrap().width() - width).abs() < 1e-6);
}
/// A failed batch takes back the composite fonts it set, in the font database too.
#[test]
fn a_failed_batch_takes_back_its_composite_fonts() {
+4 -1
View File
@@ -781,7 +781,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the first of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect();
let mut kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = HashMap::new();
for b in &library {
kinds.entry(b.name.as_str()).or_insert(&b.kind);
}
let brush_entries: Vec<Value> =
brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect();
let brush_rows: Vec<(String, String)> = brushes
+7 -6
View File
@@ -13,7 +13,7 @@ use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData};
use vectorcraft_render::effects;
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at};
use super::appearance::{ItemTarget, aligned, appearance_targets, edit_targets, index_param, item_indices, item_target, item_target_at};
use super::expand::has_seeded;
use super::rasterfx;
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, cmd, fileio, has_doc, str_param, switch_or};
@@ -49,7 +49,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Apply Effect",
[],
None,
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step) → {ids, index, item, grouped?}",
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
has_doc,
apply
),
@@ -298,7 +298,7 @@ fn ids_json(ids: &[NodeId]) -> Value {
/// edits its equal item, or its equal object-level effect, each target matched on its own whatever
/// the other targets have; in a target without them, `item` and `index` stand for themselves.
pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result<Vec<(NodeId, Option<usize>, usize)>> {
let roots = appearance_targets(s, p)?;
let roots = edit_targets(s, p)?;
let d = &s.doc()?.doc;
let per = item.per_target(s, &roots);
let first = roots.first().and_then(|f| d.node(*f));
@@ -453,7 +453,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
let item = item_target(s, p, C)?;
if effects::is_three_d(id) {
let targets = appearance_targets(s, p)?;
let targets = edit_targets(s, p)?;
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
let d = &s.doc()?.doc;
let n = d.node(target).ok_or(EngineError::NoNode(target))?;
@@ -492,8 +492,9 @@ fn loose_for_pathfinder(s: &Session, p: &Value, id: &str) -> Result<Option<Vec<N
if !effects::is_pathfinder(id) || ["ids", "id", "item", "target"].iter().any(|k| p.get(k).is_some()) {
return Ok(None);
}
let roots = super::appearance::subject_roots(s)?;
let d = &s.doc()?.doc;
// The art of a graph design in a series stays where the graph draws it.
let roots = super::appearance::without_design_art(d, super::appearance::subject_roots(s)?, "appearance")?;
let grouped = roots.iter().any(|r| d.node(*r).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })));
Ok((roots.len() >= 2 && !grouped).then_some(roots))
}
@@ -606,7 +607,7 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
let src = item_target_at(s, p, "fromItem", C)?;
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
let copy = switch_or(p, "copy", false, C)?;
let roots = appearance_targets(s, p)?;
let roots = edit_targets(s, p)?;
// Where an aligned effect would go in each of several different stacks isn't one place.
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
+2 -2
View File
@@ -7,7 +7,7 @@ use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_render::effects;
use super::super::appearance::{appearance_targets, index_param, item_target};
use super::super::appearance::{edit_targets, index_param, item_target};
use super::super::brushsym::{normalize, selection_art, store_symbol};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param};
use super::{effect_targets, ids_json};
@@ -95,7 +95,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
effect_targets(s, p, item, index, C)?
} else {
let mut out = vec![];
for id in appearance_targets(s, p)? {
for id in edit_targets(s, p)? {
let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?;
out.push((id, item, index));
}
+52 -9
View File
@@ -25,7 +25,7 @@ use super::dimension::EndedLink;
use super::edit::selected_roots;
use super::menucmds::{run_raw, squash};
use super::object::as_clipping_path;
use super::pathops::{assemble, node_path, outline_strokes, replace_leaves, styled_copy, with_transparency};
use super::pathops::{assemble, node_path, outlinable, outline_strokes, replace_leaves, styled_copy, with_transparency};
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selection, number_or, switch_or, text_param};
const C: &str = "object.expand";
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines (its own fills and strokes on paths of its whole outline, which Fill and Stroke expand), live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
has_selection,
expand
),
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand Options",
[],
None,
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character, or of the whole type for the type object's own fills), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
has_selection,
|s, _| {
let roots = selected_roots(s)?;
@@ -189,21 +189,37 @@ impl Expandable {
e.placed |= matches!(c.kind, NodeKind::PlacedDocument(_));
e.repeats |= matches!(c.kind, NodeKind::Repeat(_));
e.intertwines |= matches!(c.kind, NodeKind::Intertwine { .. });
// Type's outlines take its characters' stroke and fill, and a path of its whole outline
// takes the type object's own fills and strokes (see `type.createOutlines`).
// Any stroke Outline Stroke outlines, not only the topmost one.
let own_stroke = c.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st)));
let own_pattern = c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some());
let own_gradient = c.appearance.items.iter().any(|i| gradient_fill(i).is_some());
// Type without an outline (empty, or only spaces) gets no path for its own fills and strokes.
let whole = match &c.kind {
NodeKind::Text(t) if own_stroke || own_pattern || own_gradient => text_whole_outline(t),
_ => None,
};
e.stroke |= match &c.kind {
// Type's outlines take its characters' stroke (see `type.createOutlines`).
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && !c.appearance.stroke_paint().is_none(),
NodeKind::Text(t) => (own_stroke && whole.is_some()) || t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && own_stroke,
};
// Once one is found, the next path is not measured.
e.gradient = e.gradient
|| match &c.kind {
NodeKind::Text(t) => text_gradient_expands(d, t),
NodeKind::Text(t) => {
text_gradient_expands(d, t)
|| (own_gradient && whole.as_ref().is_some_and(|(path, tb)| text_object_gradient_expands(d, c, path, *tb)))
}
_ => shape && gradient_expands(d, c),
};
e.fill |= e.gradient;
e.fill |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())),
_ => shape && c.appearance.items.iter().any(|i| pattern_fill(d, i).is_some()),
NodeKind::Text(t) => {
(own_pattern && whole.is_some())
|| t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some()))
}
_ => shape && own_pattern,
};
});
}
@@ -275,6 +291,33 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
|| vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t).iter().any(|(run, bar)| expands(*run, bar))
}
/// The path of type `t`'s whole outline in the document (glyphs, ruby glyphs and underline and
/// strikethrough bars), which `type.createOutlines` paints with the type object's own fills and
/// strokes, and the layout's bounds there; `None` when the type has no outline.
fn text_whole_outline(t: &TextObject) -> Option<(PathData, Rect)> {
let db = vectorcraft_text::FontDb::global();
let lay = vectorcraft_text::layout(db, t);
let mut all = BezPath::new();
for g in lay.glyphs.iter().chain(&lay.ruby) {
all.extend(g.outline.iter());
}
for (_, bar) in vectorcraft_text::decorations(&lay, db, t) {
all.extend(bar.iter());
}
let path = PathData::from_bezpath(&all).transformed(t.xf);
(!path.is_empty()).then(|| (path, t.xf.transform_rect_bbox(lay.bounds)))
}
/// Whether type node `n` has a gradient fill of its own (not its characters') that Fill expands
/// once Object has outlined it: [`gradient_expands`] on `path`, the type's whole outline
/// ([`text_whole_outline`]), with its unplaced gradients fixed to `tb`, the layout's bounds in the
/// document. Leaves the document as it is.
fn text_object_gradient_expands(d: &Document, n: &Node, path: &PathData, tb: Rect) -> bool {
let mut appearance = Appearance { items: n.appearance.items.clone(), ..Default::default() };
appearance.pin_gradients(tb);
gradient_expands(d, &Node::path(NodeId(u64::MAX), path.clone(), appearance))
}
/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]).
fn piece_gradient_expands(d: &Document, l: &Node) -> bool {
if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) {
+1 -1
View File
@@ -123,7 +123,7 @@ mod formats;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
pub use access::{write_file_with, write_save_file, write_save_file_with};
pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests_readonly;
+18
View File
@@ -121,6 +121,24 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
out
}
/// The error for an SVG of a document that links a JavaScript file outside the read roots.
pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots";
/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ,
/// and those too unless read roots are in force and the document links a JavaScript file outside
/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked),
/// which the file's `<script>` element would name. The error names no file or folder.
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Result<()> {
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
return Ok(());
}
let doc_path = st.path.as_deref();
if st.doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) {
return Err(bad(cmd, SCRIPT_OUTSIDE));
}
Ok(())
}
/// `path` checked for writing against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn may_write(path: &str) -> Result<()> {
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
"DXF Info",
[],
None,
"{path} or {name?, dataBase64} what a DXF drawing holds → {version (2018, R12…), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}; a binary DXF or a DWG answers an error saying to save it as ASCII DXF",
"{path} or {name?, dataBase64} what a DXF drawing holds → {version (2018, R12…), units (its drawing unit: Millimeters, Inches, Unitless…), layouts: [\"Model\", paper layouts…], layers: [name…], unit, scale (the default ratio: 1 unit = scale drawing units, the drawing at 1:1)}; a DWG answers an error saying to save it as DXF",
always,
dxf_info
)]
+5 -1
View File
@@ -12,7 +12,8 @@ use crate::DocState;
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
use super::encode::single_artboard;
use super::{
ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return,
ARTBOARD_PARAMS, Format, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded,
write_or_return,
};
/// The keys the export commands take for every format, beside the path, the format and the
@@ -53,6 +54,7 @@ pub fn unused_option_notes(cmd: &str, f: &Format, p: &Value) -> Vec<String> {
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
let unused = unused_option_notes("document.serialize", f, p);
let expanded = expand_presets(s, "document.serialize", p)?;
let p = with_black_output(s, &expanded);
@@ -96,6 +98,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
}
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
check_linked_scripts("document.export", f.id, s.doc()?)?;
let unused = unused_option_notes("document.export", f, p);
let expanded = expand_presets(s, "document.export", p)?;
let p = with_black_output(s, &expanded);
@@ -355,6 +358,7 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
}
let f = writable(C, text_param(p, "format", C)?, path)?;
check_linked_scripts(C, f.id, s.doc()?)?;
let unused = unused_option_notes(C, f, p);
let expanded = expand_presets(s, C, p)?;
let p = with_black_output(s, &expanded);
+2 -1
View File
@@ -822,6 +822,7 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i64>) -> Result<SaveJob> {
let cmd = plan.mode.command();
super::check_linked_scripts(cmd, plan.format.id, st)?;
let mut own = doc_to_save(st, plan.format);
// The file the document is saved as (else its own) titles it if New's name is all it has.
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
@@ -1238,7 +1239,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
+4
View File
@@ -1030,6 +1030,10 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
o.one_source()?;
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
let st = s.doc()?;
// Before the folder is made or any row is written.
for r in &rows {
super::check_linked_scripts(C, r.format.id, st)?;
}
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
let selection = o.selection_mode()?;
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
@@ -163,12 +163,12 @@ fn dxf_info_lists_layouts_layers_and_units() {
}
#[test]
fn binary_dxf_says_to_save_it_as_ascii() {
fn damaged_binary_dxf_says_so() {
let mut s = Session::new();
let mut bytes = vectorcraft_cad::import::BINARY_SENTINEL.to_vec();
bytes.extend([0u8; 64]);
let e = open(&mut s, &bytes, json!({})).unwrap_err().to_string();
assert!(e.contains("binary DXF") && e.contains("ASCII"), "{e}");
assert!(e.contains("binary DXF") && e.contains("damaged"), "{e}");
let e = s.execute("document.dxfInfo", &json!({"dataBase64": b64(&bytes)})).unwrap_err().to_string();
assert!(e.contains("binary DXF"), "{e}");
}
+3 -2
View File
@@ -46,8 +46,9 @@ use generate::generate;
use series::default_series_color;
pub(crate) use series::{
LabelTextChange, capture_label_anti_alias, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles,
capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, label_object_opacity_differs,
paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs, shown_paint,
capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs,
shown_paint,
};
#[cfg(test)]
+23 -10
View File
@@ -131,7 +131,7 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
}
let mut out = Vec::new();
for id in ids {
// The series' own marks: the art of a marker design inside it keeps the design's paint (painting it would
// The series' own marks: the art of a graph design inside it keeps the design's paint (painting it would
// last only until the graph is drawn again), so edit the design to change it.
match members.get(id) {
Some(r) if r.group == *id => {
@@ -139,7 +139,7 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
out.extend(group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id));
}
}
Some(r) if doc.parent_of(*id) != Some(r.group) => {}
Some(r) if doc.parent_of(*id) != Some(r.group) || doc.node(*id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })) => {}
_ => out.push(*id),
}
}
@@ -157,18 +157,11 @@ pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId>
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
// A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is
// looked up through its parent, with no pass over the document: the panels call this while they draw.
let is_series_group = |n: &Node| {
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
graph.is_some_and(|spec| index < series_count(spec))
};
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for id in ids {
match doc.node(*id) {
Some(group) if is_series_group(group) && stands(group) => {
Some(group) if is_series_group(doc, group) && stands(group) => {
let marks: Vec<NodeId> =
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
@@ -180,6 +173,26 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i
out
}
/// Whether `n` is a graph series group: a child of a graph with one of the graph's series indexes ([`series_members`]).
/// It is looked up through its parent, with no pass over the document: the panels call this while they draw.
fn is_series_group(doc: &Document, n: &Node) -> bool {
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
graph.is_some_and(|spec| index < series_count(spec))
}
/// Whether `id` is the art of a graph design drawn in a graph series (Object › Graph › Column or Marker): an object
/// inside a series group other than a path directly in it. The graph draws that art again from the design.
pub(crate) fn is_design_art(doc: &Document, id: NodeId) -> bool {
let Some(chain) = doc.ancestry(id) else { return false };
let Some(at) = chain.iter().position(|a| doc.node(*a).is_some_and(|n| is_series_group(doc, n))) else { return false };
match chain.len() - at {
1 => false,
2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })),
_ => true,
}
}
/// The paint of the topmost visible fill (`true`) or stroke (`false`) of `node`, and a stroke's weight (0 without paint).
/// With no such row: no paint.
pub(crate) fn shown_paint(node: &Node, fill: bool) -> (Paint, f64) {
+202 -7
View File
@@ -373,8 +373,8 @@ fn removing_a_series_marks_fill_forgets_its_kept_opacity() {
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
}
/// An opacity set on a row added to a graph design's copy inside a series is not kept for the series: the graph draws
/// the design again from the design itself.
/// A row or a row opacity is not given to a graph design's copy inside a series, and the graph keeps no opacity for the
/// series: the graph draws the design again from the design itself.
#[test]
fn an_opacity_on_a_design_copy_in_a_series_is_not_kept() {
let mut s = Session::new();
@@ -384,11 +384,143 @@ fn an_opacity_on_a_design_copy_in_a_series_is_not_kept() {
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
assert!(matches!(copy.kind, NodeKind::Group { .. }));
s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).unwrap();
s.execute("transparency.set", &json!({"ids": [copy.id.0], "item": 0, "opacity": 40})).unwrap();
assert!(s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).is_err());
assert!(s.execute("transparency.set", &json!({"ids": [copy.id.0], "item": 0, "opacity": 40})).is_err());
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()));
}
/// A column graph whose series 0 draws the design "Square": the graph, series 0's first copy of the design, a path
/// inside that copy, and the first mark of series 1, drawn plain.
fn design_art() -> (Session, NodeId, NodeId, NodeId, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
save_design(&mut s, "Square");
s.execute("graph.column", &json!({"id": id.0, "seriesIndexes": [0], "design": "Square"})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let copy = series(&n, 0).children().unwrap()[0].clone();
assert!(matches!(copy.kind, NodeKind::Group { .. }));
let mut art = vec![];
copy.walk(&mut |m| {
if matches!(m.kind, NodeKind::Path { .. }) {
art.push(m.id);
}
});
let mark = series(&n, 1).children().unwrap()[0].clone();
assert!(matches!(mark.kind, NodeKind::Path { .. }));
(s, id, copy.id, art[0], mark.id)
}
/// `cmd` with `p` is refused as an edit of graph design art, and the document keeps its undo history.
fn refused_on_design_art(s: &mut Session, cmd: &str, p: serde_json::Value) {
let steps = s.doc().unwrap().history.undo.len();
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains("drawn again from the design"), "{cmd}: {e}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}");
}
/// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by
/// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design.
#[test]
fn appearance_commands_refuse_a_graph_designs_art_in_a_series() {
let (mut s, _, copy, art, _) = design_art();
let (rect, _) = blue_style(&mut s, "Blue", false);
let graphic = s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [graphic]})).unwrap();
let fill = top_row(&s, art, true);
for ids in [json!([copy.0]), json!([art.0])] {
refused_on_design_art(
&mut s,
"graphicStyle.addFromLibrary",
json!({"library": "painted-sketched", "name": "Wet Ink", "apply": true, "ids": ids}),
);
for cmd in ["appearance.addFill", "appearance.addStroke", "appearance.clear", "appearance.reduceToBasic", "appearance.showAllHidden"] {
refused_on_design_art(&mut s, cmd, json!({"ids": ids}));
}
refused_on_design_art(&mut s, "appearance.moveItem", json!({"ids": ids, "from": "contents", "to": 0}));
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": ids}));
refused_on_design_art(&mut s, "appearance.addEffect", json!({"effect": "stylize.dropShadow", "ids": ids}));
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "ids": ids}));
refused_on_design_art(&mut s, "effect.move", json!({"ids": ids, "from": 0, "to": 0}));
refused_on_design_art(&mut s, "effect.remove", json!({"ids": ids, "index": 0}));
refused_on_design_art(&mut s, "threeD.mapGraphic", json!({"ids": ids, "symbol": "Mark"}));
refused_on_design_art(&mut s, "graphicStyle.apply", json!({"name": "Blue", "ids": ids}));
}
for cmd in ["appearance.removeItem", "appearance.duplicateItem"] {
refused_on_design_art(&mut s, cmd, json!({"ids": [art.0], "index": fill}));
}
refused_on_design_art(&mut s, "appearance.setItem", json!({"ids": [art.0], "index": fill, "color": "#00ff00"}));
refused_on_design_art(&mut s, "appearance.moveItem", json!({"ids": [art.0], "from": fill, "to": 0}));
refused_on_design_art(&mut s, "transparency.set", json!({"ids": [art.0], "item": fill, "opacity": 40}));
refused_on_design_art(&mut s, "appearance.copyFrom", json!({"source": rect.0, "ids": [art.0]}));
refused_on_design_art(&mut s, "appearance.transfer", json!({"source": rect.0, "target": art.0, "copy": true}));
refused_on_design_art(&mut s, "appearance.transfer", json!({"source": art.0, "target": rect.0}));
// Selected, and through the contents of the design's copy.
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
refused_on_design_art(&mut s, "appearance.addFill", json!({}));
refused_on_design_art(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Wet Ink", "apply": true}));
refused_on_design_art(&mut s, "appearance.addStroke", json!({"ids": [copy.0], "target": "contents"}));
// A Pathfinder effect does not group the selected paths of the design's copy.
let mut paths = vec![];
s.doc().unwrap().doc.node(copy).unwrap().walk(&mut |m| {
if matches!(m.kind, NodeKind::Path { .. }) {
paths.push(m.id.0);
}
});
assert_eq!(paths.len(), 2);
s.execute("select.set", &json!({"ids": paths})).unwrap();
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "pathfinder.add"}));
// Read as a source, the art gives its look.
s.execute("appearance.transfer", &json!({"source": art.0, "target": rect.0, "copy": true})).unwrap();
}
/// Given the art of a graph design in a series with other objects, the commands edit the other objects only.
#[test]
fn appearance_commands_edit_the_objects_given_with_a_graph_designs_art() {
let (mut s, id, copy, art, mark) = design_art();
let (rect, _) = blue_style(&mut s, "Blue", false);
let rows = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
let (copy_was, art_was, mark_was) = (rows(&s, copy), rows(&s, art), rows(&s, mark));
s.execute("appearance.addFill", &json!({"ids": [copy.0, mark.0]})).unwrap();
assert_eq!((rows(&s, copy), rows(&s, art)), (copy_was.clone(), art_was.clone()));
assert_eq!(rows(&s, mark).items.len(), mark_was.items.len() + 1);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [art.0, mark.0]})).unwrap();
assert_eq!(rows(&s, art), art_was);
assert_eq!(rows(&s, mark).effects.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [art.0, mark.0]})).unwrap();
assert_eq!(rows(&s, art), art_was);
assert_ne!(rows(&s, mark), mark_was);
s.execute("edit.undo", &json!({})).unwrap();
// The graph's contents: series 1's marks take the fill, the design's art does not.
s.execute("appearance.addFill", &json!({"ids": [id.0], "target": "contents"})).unwrap();
assert_eq!((rows(&s, copy), rows(&s, art)), (copy_was, art_was));
assert_eq!(rows(&s, mark).items.len(), mark_was.items.len() + 1);
}
/// The paint commands leave the art of a graph design in a series out, a copy of the design given by id with an item
/// included.
#[test]
fn paint_targets_leave_a_graph_designs_copy_out() {
let (s, _, copy, art, mark) = design_art();
let d = &s.doc().unwrap().doc;
assert_eq!(super::paint_targets(d, &[copy, art, mark]), [mark]);
}
/// The art of a marker design in a series is refused too.
#[test]
fn effect_commands_refuse_a_marker_designs_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Pill");
let id = graph(&mut s, "line");
s.execute("graph.marker", &json!({"id": id.0, "seriesIndexes": [1], "design": "Pill"})).unwrap();
let marker = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[1].clone();
assert!(matches!(marker.kind, NodeKind::Group { .. }), "the design's art");
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [marker.id.0]}));
}
/// A series' kept opacity goes on its generated marks only: a column design made of one path keeps its own opacity.
#[test]
fn a_column_design_keeps_its_own_opacity_under_a_series_opacity() {
@@ -1745,8 +1877,8 @@ fn a_paint_on_a_design_copy_or_the_other_kind_of_row_is_not_kept() {
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
assert!(matches!(copy.kind, NodeKind::Group { .. }));
s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [copy.id.0], "index": 0, "color": "#0000ff"})).unwrap();
assert!(s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).is_err());
assert!(s.execute("appearance.setItem", &json!({"ids": [copy.id.0], "index": 0, "color": "#0000ff"})).is_err());
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill.is_none()));
// A path inside the design's copy is a member of the series too, and its paint is not kept either.
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
@@ -1757,7 +1889,7 @@ fn a_paint_on_a_design_copy_or_the_other_kind_of_row_is_not_kept() {
}
});
let art = paths[0];
s.execute("appearance.setItem", &json!({"ids": [art.0], "index": top_row(&s, art, true), "color": "#00ff00"})).unwrap();
assert!(s.execute("appearance.setItem", &json!({"ids": [art.0], "index": top_row(&s, art, true), "color": "#00ff00"})).is_err());
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill.is_none()));
let mut s = Session::new();
@@ -6050,3 +6182,66 @@ fn graph_commands_refuse_params_of_the_wrong_type() {
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, null], [2, 3]], "series": null, "transpose": null})).unwrap();
assert_eq!(spec(&s).cells(), vec![vec![Some(1.0), None], vec![Some(2.0), Some(3.0)]]);
}
/// A `.ai` in PostScript form whose graph's records read whole (version 7 specification, appendix A)
/// opens as a graph whose data can be edited: Graph Data redraws it on its plot. Saving it as `.ai`
/// says its data and settings aren't written, in either form.
#[test]
fn a_graph_opened_from_ai_keeps_its_data_for_editing() {
let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\
%_1 () Ga\n%_0 13 0 0 0 0 0 () GA\n%_2 () Ga\n%_0 14 0 0 0 0 0 () GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n\
%_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n\
u\nu\n0.6 0 1 0 k\n110 100 m\n110 150 L\n130 150 L\n130 100 L\nf\nU\n%_2 1 0 0 Go\n\
u\n0 0 0 1 K\n100 200 m\n100 100 L\n300 100 L\nS\nU\nU\n%_GS\n";
let text = format!(
"%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 400 400\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 400 400\n%%EndComments\n\
%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Graph) Ln\n0 A\n{graph}LB\n\
%AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n"
);
let dir = vectorcraft_testkit::temp_dir("graph-ai-open");
let path = dir.join("graph.ai");
std::fs::write(&path, text).unwrap();
let mut s = Session::new();
s.execute("document.open", &json!({"path": path})).unwrap();
let mut found = vec![];
s.doc().unwrap().doc.walk(|n| {
if n.extras().graph.is_some() {
found.push(n.id);
}
});
assert_eq!(found.len(), 1);
let id = found[0];
let before = spec(&s, id);
assert_eq!(
(before.series.as_slice(), before.categories.as_slice(), before.rows.as_slice()),
(&["East".to_string()][..], &["Q1".to_string()][..], &[vec![5.0]][..])
);
// The fill of the series' first mark.
let series_fill = |s: &Session| {
let mut fill = None;
s.doc().unwrap().doc.walk(|n| {
if n.extras().series_index == Some(0) && fill.is_none() {
let first = n.children().and_then(|c| c.first().cloned());
fill = first.and_then(|m| m.appearance.items.iter().find(|i| i.is_fill()).map(|i| i.paint().clone()));
}
});
fill
};
let painted = series_fill(&s);
assert!(painted.is_some());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap();
let after = spec(&s, id);
assert_eq!(after.rows, [[8.0], [2.0]]);
assert_eq!(after.rect, before.rect, "the graph is redrawn on its plot");
assert_eq!(series_fill(&s), painted, "the series keeps the file's paint");
for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] {
let mut p = json!({"path": dir.join(name), "format": "ai"});
if let Some(v) = version {
p["aiVersion"] = json!(v);
}
let r = s.execute("file.saveAs", &p).unwrap();
let notes = r["warnings"].as_array().cloned().unwrap_or_default();
assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}");
}
}
+2 -2
View File
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Invert",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke (docs/mcp.md) → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke (docs/mcp.md); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -105,7 +105,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Complement",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
),
+26 -5
View File
@@ -10,7 +10,7 @@
//! save or Export for Screens: those are checked against the options of the formats the command
//! can write, in `marks`, `bleed` and the other objects too ([`check_export_options`]); and in the
//! objects of an array whose keys `MEMBER_KEYS` lists, such as the `items` of
//! `object.setLiveShape`.
//! `object.setLiveShape` and `addon.pathtools.cornerSet`.
//!
//! [`Session::execute`] answers a key the description doesn't name with a parameter error
//! ([`check_params`]), for every caller (the app, the control channel, MCP, the CLI) and for the
@@ -256,6 +256,22 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
}
}
/// Parameters a command takes instead of one another: (command, key, other key). Giving both,
/// neither null, is a parameter error ([`check_exclusive_keys`]).
const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids")];
/// `params` of command `id` give at most one of each pair in [`EXCLUSIVE_KEYS`], or the parameter
/// error naming the pair.
fn check_exclusive_keys(id: &str, params: &Value) -> Result<()> {
let given = |key: &str| params.get(key).filter(|v| !v.is_null());
for (_, key, other) in EXCLUSIVE_KEYS.iter().filter(|(c, ..)| *c == id) {
if given(key).is_some() && given(other).is_some() {
return Err(bad(id, format!("give `{key}` or `{other}`, not both")));
}
}
Ok(())
}
/// The parameter error of command `id` for `key`, which isn't one of `keys`: with the nearest of
/// them, or all of them.
pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError {
@@ -273,7 +289,11 @@ pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError
/// Commands whose params hold an array of objects with keys of their own: the command, the key of
/// the array and the keys each of its objects takes.
const MEMBER_KEYS: &[(&str, &str, &[&str])] = &[("object.setLiveShape", "items", &["id", "corners"])];
const MEMBER_KEYS: &[(&str, &str, &[&str])] = &[
("object.setLiveShape", "items", &["id", "corners"]),
("addon.pathtools.cornerSet", "items", &["id", "anchors"]),
("addon.pathtools.cornerRemove", "items", &["id", "anchors"]),
];
/// Each object in the arrays [`MEMBER_KEYS`] names for command `id` has only the keys it lists, or
/// the parameter error naming the first other one with its place (`items[0].corner`), and the
@@ -848,9 +868,9 @@ fn check_export_options(id: &str, params: &Value) -> Result<()> {
check_option_keys(id, "", given, &keys, why_not, &trees)
}
/// [`check_keys`] for an engine command, the steps of a `command.batch` or an `action.batch` included,
/// [`check_effect_params`] for the effect `effect.apply` adds and [`check_export_options`] for an
/// export. A command the engine doesn't have passes: running it reports that.
/// [`check_keys`], [`check_exclusive_keys`] and [`check_member_keys`] for an engine command, the steps of a `command.batch` or an
/// `action.batch` included, [`check_effect_params`] for the effect `effect.apply` adds and
/// [`check_export_options`] for an export. A command the engine doesn't have passes: running it reports that.
pub fn check_params(id: &str, params: &Value) -> Result<()> {
check_params_in(id, params, false)
}
@@ -869,6 +889,7 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
return Ok(());
}
check_keys(id, spec.params, params)?;
check_exclusive_keys(id, params)?;
check_member_keys(id, params)?;
if in_batch {
crate::schemas::check(spec, params, false)?;
+1 -1
View File
@@ -962,7 +962,7 @@ pub(crate) fn ordered_map<T: Sync, R: Send>(
// ---------- Outline Stroke ----------
/// Can Outline Stroke turn `st` into filled art?
fn outlinable(st: &StrokeLayer) -> bool {
pub(crate) fn outlinable(st: &StrokeLayer) -> bool {
st.visible && !st.paint.is_none() && st.width > 0.0
}
+21 -13
View File
@@ -793,7 +793,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Preferences",
[],
None,
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
"{path?} write the preferences as a JSON file {format: \"vectorcraft-preferences\", version: 1, prefs: {key: value, …}}: every preference prefs.list lists and the eyedropper, perspectiveWidget, pathfinder, glyphSnap and pixelSnap groups, without the folder preferences fontsFolder, pluginsFolder, scratchPrimary, scratchSecondary, recoveryFolder and templatesFolder and without saved presets; a file over 1 MB, which prefs.import would refuse, is an error and is not written → {path, count}; without path → {data: the file's text, count}",
always,
export
),
@@ -802,7 +802,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Preferences",
[],
None,
"{path? | data?: the file's text} apply the preferences of a file prefs.export wrote (at most 1 MB). Every value is checked first, as prefs.set checks it: another format, a newer version, an unknown preference, a value of the wrong type or out of range, or a folder preference is an error, and nothing changes. Preferences the file leaves out keep their values; the open document's units stay as they are; no undo step; not a command.batch step → {imported: count}",
"{path? | data?: the file's text} apply the preferences of a file prefs.export wrote (at most 1 MB). Every value is checked first, as prefs.set checks it: another format, a newer version, an unknown preference, a value of the wrong type or out of range, or a folder preference (for scratchPrimary and scratchSecondary, a folder; the choices Startup and None are read) is an error, and nothing changes. Preferences the file leaves out keep their values; the open document's units stay as they are; no undo step; not a command.batch step → {imported: count}",
always,
import
),
@@ -818,8 +818,20 @@ pub const PREFS_VERSION: u64 = 1;
/// The largest preferences file `prefs.import` reads.
const MAX_PREFS_FILE_BYTES: usize = 1 << 20;
/// Folder preferences, which name folders on one computer: a preferences file leaves them out.
const FOLDER_PREFS: &[&str] = &["fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
/// Folder preferences, which name folders on one computer: a preferences file leaves them out, and
/// under automation read roots one outside them is not shown.
pub const FOLDER_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
/// The scratch disk choices that are not folders.
pub const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
/// Does `value`, set as preference `key`, name a folder: is `key` a folder preference
/// ([`FOLDER_PREFS`]) and `value`, trimmed as the app uses it, neither empty (the default folder)
/// nor a scratch disk choice ([`SCRATCH_CHOICES`])?
pub fn names_a_folder(key: &str, value: &str) -> bool {
let path = value.trim();
FOLDER_PREFS.contains(&key) && !path.is_empty() && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path))
}
/// The preferences `prefs.export` writes: every [`PREF_SPECS`] key but the [`FOLDER_PREFS`], and
/// the [`PREF_GROUPS`].
@@ -868,7 +880,9 @@ fn read_prefs_file(bytes: &[u8]) -> std::result::Result<Map<String, Value>, Stri
if prefs.is_empty() {
return Err("the file holds no preferences".into());
}
if let Some(key) = prefs.keys().find(|k| FOLDER_PREFS.contains(&k.as_str())) {
// A scratch disk choice or an empty scratch disk names no folder, and is read.
let folder = |k: &str, v: &Value| FOLDER_PREFS.contains(&k) && (!k.starts_with("scratch") || v.as_str().is_some_and(|v| names_a_folder(k, v)));
if let Some(key) = prefs.iter().find(|(k, v)| folder(k, v)).map(|(k, _)| k) {
return Err(format!("`{key}` names a folder, which preferences files leave out"));
}
Ok(prefs.clone())
@@ -893,14 +907,8 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "imported": values.len() }))
}
/// The preferences that name a folder: the [`FOLDER_PREFS`] and the scratch disks.
const PATH_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
/// The scratch disk choices that are not folders.
const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
/// The preferences as `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show them to the
/// request being served. Under automation read roots, a folder preference ([`PATH_PREFS`]) outside
/// request being served. Under automation read roots, a folder preference ([`FOLDER_PREFS`]) outside
/// them is `null`, as `ui.inspect` leaves it out, and an export preset's `folder` outside them is
/// left out. An empty value (the default folder) and a scratch
/// disk choice ([`SCRATCH_CHOICES`]) are shown. Without roots the preferences are shown as they are.
@@ -911,7 +919,7 @@ fn shown_prefs(prefs: &Prefs) -> Value {
}
// The app trims a folder before it uses it.
let hidden = |path: &str| !path.trim().is_empty() && crate::file_access::check_read(path.trim()).is_err();
for key in PATH_PREFS {
for key in FOLDER_PREFS {
let Some(path) = all[key].as_str() else { continue };
if hidden(path) && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path.trim())) {
all[key] = Value::Null;
+7 -4
View File
@@ -15,7 +15,7 @@ use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Point, Rect};
use super::colorcmds::{NotChanged, Recolor, Scope, keeping_series_paint, left_out};
use super::colorcmds::{NotChanged, Recolor, Scope, edit_if_changed, keeping_series_paint, left_out};
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param};
pub fn specs() -> Vec<CommandSpec> {
@@ -34,7 +34,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 (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. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {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), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
"{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 (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke (docs/mcp.md) → {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), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
has_doc,
apply
),
@@ -1661,7 +1661,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
};
let rename = text_param(p, "rename", C)?;
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let (changed, edit, added, converted, not_changed) = s.edit(label, |d, _| {
let (changed, edit, added, converted, not_changed) = edit_if_changed(s, label, |now, d| {
// The rows' library swatches join the document (one it has with that name and colour is
// used as it is).
let mut added = vec![];
@@ -1716,7 +1716,10 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let not_changed = NotChanged::of(
before.iter().filter(|(id, colors, _)| d.node(*id).is_some_and(|now| shown_colors(d, now) == *colors)).map(|(_, _, hidden)| *hidden),
);
Ok((changed, edit, added, map.converted.get(), not_changed))
// Rewriting the group's swatches and relinking its art are not counted in `changed`, so a
// pass that counts nothing compares the documents.
let any = changed > 0 || !added.is_empty() || *d != *now;
Ok(((changed, edit, added, map.converted.get(), not_changed), any))
})?;
let mut out = json!({ "changed": changed, "swatches": added });
not_changed.report(&mut out);
+1 -1
View File
@@ -332,7 +332,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
let i = style_index(&s.doc()?.doc, name)?;
let add = bool_or(p, "add", false);
let chars = s.prefs.override_char_color;
let own = super::appearance::appearance_targets(s, p)?;
let own = super::appearance::edit_targets(s, p)?;
let ids = super::appearance::rowless_series_marks(&s.doc()?.doc, &own);
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
// and a style added on top unlinks them.
+6 -4
View File
@@ -161,11 +161,13 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "graphicStyle.addFromLibrary";
let (info, lib) = library_param(s, p, C)?;
let (apply, add) = (switch_or(p, "apply", false, C)?, switch_or(p, "add", false, C)?);
if p.get("ids").is_some_and(|v| !v.is_null()) {
let ids_given = p.get("ids").is_some_and(|v| !v.is_null());
if ids_given {
checked_ids_param(s, p, "ids", C)?;
} else if apply {
// A selection that can't take a style is refused before any style is added.
super::appearance::appearance_targets(s, &json!({}))?;
}
if apply {
// Objects that can't take a style are refused before any style is added.
super::appearance::edit_targets(s, &if ids_given { json!({"ids": p["ids"]}) } else { json!({}) })?;
}
let mut names = names_param(p, C)?;
names.extend(text_param(p, "name", C)?.map(str::to_string));
+5 -1
View File
@@ -34,8 +34,12 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// The Offset a wrap object takes, in points.
pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive<f64> = -1000.0..=1000.0;
fn wrap_param(p: &Value, base: TextWrap) -> TextWrap {
TextWrap { offset: f64_or(p, "offset", base.offset).clamp(-1000.0, 1000.0), invert: bool_or(p, "invert", base.invert) }
let (lo, hi) = (*TEXT_WRAP_OFFSET_RANGE.start(), *TEXT_WRAP_OFFSET_RANGE.end());
TextWrap { offset: f64_or(p, "offset", base.offset).clamp(lo, hi), invert: bool_or(p, "invert", base.invert) }
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
+30 -2
View File
@@ -4,7 +4,9 @@
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{AreaFit, Document, Justify, Node, NodeId, NodeKind, RubyAlign, RubyPosition, RubySpan, TextObject};
use vectorcraft_doc::{
Appearance, AppearanceItem, AreaFit, Document, Justify, Node, NodeId, NodeKind, RubyAlign, RubyPosition, RubySpan, TextObject,
};
use vectorcraft_geom::{Affine, PathData, Vec2};
use super::edit::selected_roots;
@@ -39,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Outlines",
["Type"],
Some("Cmd+Shift+O"),
"{} convert the selected text to groups of compound paths (one per glyph); a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
"{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
has_selection,
create_outlines
),
@@ -672,13 +674,39 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
}
placed.extend(ruby.map(|(_, r)| r));
let mut children = placed;
// The whole outline the object's own fills and strokes paint: every glyph, ruby glyph
// and bar, as the canvas paints them.
let mut all = kurbo::BezPath::new();
for g in lay.glyphs.iter().chain(&lay.ruby) {
all.extend(g.outline.iter());
}
// Underline and strikethrough bars become paths of their run's paint too (#847).
for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) {
all.extend(bar.iter());
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
let mut node = shape_node(d, PathData::from_bezpath(&bar).transformed(t.xf), None);
node.appearance = st.appearance().into();
children.push(Arc::new(node));
}
// The object's own fills and strokes (not its characters') paint the whole outline:
// those below the Characters row under the characters, the others over them, with
// their unplaced gradients fixed to the layout's bounds in the document.
let all = PathData::from_bezpath(&all).transformed(t.xf);
if !n.appearance.items.is_empty() && !all.is_empty() {
let (below, above) = n.appearance.split_contents();
let tb = t.xf.transform_rect_bbox(lay.bounds);
let mut whole = |items: &[AppearanceItem]| {
let mut ap = Appearance { items: items.to_vec(), ..Default::default() };
ap.pin_gradients(tb);
Arc::new(Node::path(d.alloc_id(), all.clone(), ap))
};
if !below.is_empty() {
children.insert(0, whole(below));
}
if !above.is_empty() {
children.push(whole(above));
}
}
let (par, idx, _) = d.position(tid).ok_or(EngineError::NoNode(tid))?;
d.remove(tid)?;
if children.is_empty() {
+1 -1
View File
@@ -867,7 +867,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Data Sets…",
["Window", "Variables"],
None,
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 with a byte-order mark, UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
"{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}",
has_doc,
dataset_import
),
+37 -12
View File
@@ -32,20 +32,17 @@ fn datasets_csv_bytes(p: &Value, cmd: &str) -> Result<(Vec<u8>, bool)> {
}
/// The text of a datasets CSV given as a file or as `dataBase64`: UTF-16 after a UTF-16
/// byte-order mark, else UTF-8, with or without a byte-order mark, else Windows-1252. A file
/// that starts with a byte-order mark must be valid in its encoding, and a file without one must
/// not hold NUL bytes (UTF-16 without a byte-order mark).
/// byte-order mark, else UTF-16 without one when the file holds NUL bytes (see
/// [`utf16_without_mark`]), else UTF-8, with or without a byte-order mark, else Windows-1252. A
/// file that starts with a byte-order mark must be valid in its encoding, and a file with NUL
/// bytes and no byte-order mark must read as UTF-16 by [`utf16_without_mark`]'s rule.
fn datasets_csv_text(bytes: &[u8], cmd: &str) -> Result<String> {
let utf16 = |rest: &[u8], le: bool| {
let (units, odd) = rest.as_chunks::<2>();
let units = units.iter().map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) });
let text = char::decode_utf16(units).collect::<std::result::Result<String, _>>();
text.ok().filter(|_| odd.is_empty()).ok_or_else(|| bad(cmd, "CSV is not UTF-16"))
};
match bytes {
[0xFF, 0xFE, rest @ ..] => return utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => return utf16(rest, false),
_ if bytes.contains(&0) => return Err(bad(cmd, "CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark")),
[0xFF, 0xFE, rest @ ..] => return utf16(rest, true).ok_or_else(|| bad(cmd, "CSV is not UTF-16")),
[0xFE, 0xFF, rest @ ..] => return utf16(rest, false).ok_or_else(|| bad(cmd, "CSV is not UTF-16")),
_ if bytes.contains(&0) => {
return utf16_without_mark(bytes).ok_or_else(|| bad(cmd, "CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark"));
}
_ => {}
}
match std::str::from_utf8(bytes) {
@@ -55,6 +52,34 @@ fn datasets_csv_text(bytes: &[u8], cmd: &str) -> Result<String> {
}
}
/// `bytes` as UTF-16, little-endian when `le` is set, or `None` when they aren't valid UTF-16.
fn utf16(bytes: &[u8], le: bool) -> Option<String> {
let (units, odd) = bytes.as_chunks::<2>();
let units = units.iter().map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) });
char::decode_utf16(units).collect::<std::result::Result<String, _>>().ok().filter(|_| odd.is_empty())
}
/// `bytes`, which hold NUL bytes and no byte-order mark, as UTF-16, or `None`. At least half of
/// the two-byte units must hold a NUL byte, as characters from U+0001 to U+00FF do; a file with
/// fewer, such as UTF-8 or Windows-1252 text with stray NUL bytes, is refused. The byte order is
/// the one that reads a line break (`\n` or `\r`). The other order reads one only from U+0A00 or
/// U+0D00, so a file that reads one in both orders is refused. A file that reads none in either
/// order has no data rows, and is read little-endian so that the import reports that. The text
/// must be valid UTF-16 in that order and hold no NUL character.
fn utf16_without_mark(bytes: &[u8]) -> Option<String> {
let (units, odd) = bytes.as_chunks::<2>();
if !odd.is_empty() || units.iter().filter(|c| c.contains(&0)).count() * 2 < units.len() {
return None;
}
let is_line_break = |u: u16| matches!(u, 0x0A | 0x0D);
let lines_le = units.iter().any(|&c| is_line_break(u16::from_le_bytes(c)));
let lines_be = units.iter().any(|&c| is_line_break(u16::from_be_bytes(c)));
if lines_le && lines_be {
return None;
}
utf16(bytes, !lines_be).filter(|text| !text.contains('\0'))
}
/// A row of a datasets CSV: the file line it starts on, its cells, and for each cell whether it was quoted.
type CsvRow = (usize, Vec<String>, Vec<bool>);
+6
View File
@@ -128,6 +128,11 @@ pub struct DocState {
empty_artboards: std::cell::RefCell<EmptyArtboards>,
/// What [`DocState::any_art_to_fit`] last measured. Not saved.
art_to_fit: std::cell::RefCell<Option<ArtToFit>>,
/// The document as [`crate::Session::replace_document`] left it in a tab in the back, with its
/// type measured in its own composite fonts, and the lowercased names of those fonts. When the
/// same document comes to the front, its type set in them is not measured again. While this
/// reference lasts, its allocation holds no other document. Not saved.
pub(crate) measured_in_own: Option<(std::sync::Weak<Document>, std::collections::HashSet<String>)>,
}
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
@@ -345,6 +350,7 @@ impl DocState {
empty_artboards: Default::default(),
plugin_effects: Default::default(),
art_to_fit: Default::default(),
measured_in_own: None,
}
}
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
+1
View File
@@ -33,6 +33,7 @@ pub use cmd::params::{check_keys, check_params};
pub use cmd::pathops::auto_simplify_level;
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step};
pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE;
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use cmd::{EyedropperOptions, PathfinderOptions};
pub use journal::Journal;
+43 -17
View File
@@ -241,10 +241,18 @@ impl Session {
/// Register the composite fonts of the document now in front ([`cmd::compositefonts::sync`]),
/// after a switch or a close brought it there. Its type set in a composite font that differs
/// from the one of that name before (added, changed or removed) is measured again, and type not
/// measured yet (in a document replaced while in the back) is measured now.
/// measured yet is measured now. Type that [`Session::replace_document`] measured in the
/// document's own composite fonts while it was in the back is not measured again when the
/// document is unchanged since.
fn sync_front_composite_fonts(&mut self) {
let changed: HashSet<String> = cmd::compositefonts::sync(self).into_iter().collect();
let mut changed: HashSet<String> = cmd::compositefonts::sync(self).into_iter().collect();
let Some(index) = self.active else { return };
if let Some(st) = self.docs.get_mut(index)
&& let Some((doc, own)) = st.measured_in_own.take()
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
{
changed.retain(|n| !own.contains(n));
}
self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() || sets_in_any(t, &changed));
}
@@ -347,14 +355,10 @@ impl Session {
doc.resolve_inline_art();
doc.guides_into_nodes();
cmd::dimension::conform(&mut doc);
// In the back, type set in a font named like a composite font is measured when the document
// comes to the front and its own composite fonts are registered, not in the front
// document's.
let mut back_names = None;
if self.active == Some(index) {
// Pending tool work (typing, a drag) belongs to the content being thrown away.
self.reset_tool_for_doc_switch();
} else {
// In the back, type set in a font named like a composite font is measured again below, in
// the document's own composite fonts, not in the front document's.
let back = self.active != Some(index);
if back {
let mut names = cmd::compositefonts::names_in_use(self);
names.extend(doc.composite_fonts.iter().map(|f| f.name.to_lowercase()));
for tree in text_trees_mut(&mut doc) {
@@ -363,7 +367,9 @@ impl Session {
t.cached_baselines.clear();
});
}
back_names = Some(names);
} else {
// Pending tool work (typing, a drag) belongs to the content being thrown away.
self.reset_tool_for_doc_switch();
}
let old = &self.docs[index];
let mut st = DocState::new(doc, old.path.clone());
@@ -396,16 +402,36 @@ impl Session {
if let Some(stash) = &mut self.batch_stash {
stash.push(old);
}
match back_names {
Some(names) => self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() && !sets_in_any(t, &names)),
None => {
self.sync_opened_composite_fonts(index);
self.sync_front_profiles();
}
if back {
self.measure_back_document(index);
} else {
self.sync_opened_composite_fonts(index);
self.sync_front_profiles();
}
true
}
/// Measure the type not measured yet in open document `index`, which is in the back, in its own
/// composite fonts, lent for the measuring, so its type has the bounds it will have when the
/// document comes to the front. The front document stays the one whose composite fonts are
/// registered. The names of the document's composite fonts its type was measured in are kept,
/// so its coming to the front does not measure that type again.
fn measure_back_document(&mut self, index: usize) {
let Some(st) = self.docs.get(index) else { return };
let fonts = st.doc.composite_fonts.clone();
let db = vectorcraft_text::FontDb::global();
let lent = db.lend_composite_fonts(&fonts);
// A name another loan holds with a different definition is not lent: type set in it is
// measured again when the document comes to the front.
let own: HashSet<String> =
fonts.iter().filter(|f| db.composite_font(&f.name).is_some_and(|have| *have == **f)).map(|f| f.name.to_lowercase()).collect();
self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none());
drop(lent);
if let Some(st) = self.docs.get_mut(index) {
st.measured_in_own = Some((Arc::downgrade(&st.doc), own));
}
}
/// Close the document in tab `index` (`file.close`). Closing a tab other than the current one
/// keeps the current document current, and its tool keeps its state: no document is switched
/// to. Closing the current document makes the tab now at `index` current, or the last tab when
+388 -3
View File
@@ -1748,6 +1748,203 @@ fn shape_builder_arrow_keys_pass_swatches_of_the_same_color() {
assert_eq!(s.paint.fill, after, "the swatch after Twin B");
}
/// The colors of the cursor swatch preview's chips, left to right, and which one is ringed.
fn swatch_chips(s: &mut Session, v: ViewInfo) -> Vec<([u8; 4], bool)> {
let mut chips: Vec<(f64, [u8; 4], bool)> = s
.overlays(v)
.into_iter()
.filter_map(|o| match o {
vectorcraft_tools::Overlay::Swatch { p, color, selected } => Some((p.x, color, selected)),
_ => None,
})
.collect();
chips.sort_by(|a, b| a.0.total_cmp(&b.0));
chips.into_iter().map(|(_, c, sel)| (c, sel)).collect()
}
/// A solid paint's color as the chips draw it.
fn chip_color(p: &Paint) -> [u8; 4] {
match p {
Paint::Solid { color, .. } => color.to_rgba8(1.0),
_ => panic!("not a solid color: {p:?}"),
}
}
/// Live Paint Bucket: Left and Right step the active paint through the document's color swatches
/// (the selected art keeps its paint), the Cursor Swatch Preview (on at first) shows the active
/// paint ringed between the swatches before and after it, and with it off the arrows still step.
#[test]
fn live_paint_bucket_arrow_keys_step_the_active_paint_through_the_swatches() {
let mut s = session();
let (a, _) = two(&mut s);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
assert_eq!(s.tool_options_of("livePaintBucket")["cursorSwatchPreview"], json!(true));
assert!(s.tool_claims_key(ToolKey::Right, v) && s.tool_claims_key(ToolKey::Left, v));
assert!(!s.tool_claims_key(ToolKey::Up, v), "Up and Down keep their own use");
let list: Vec<(String, Paint)> =
vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc).iter().map(|sw| (sw.name.clone(), sw.paint.clone())).collect();
assert!(list.len() >= 4);
let n = list.len();
let stroke = s.paint.stroke.clone();
s.execute("paint.setFill", &json!({"swatch": list[0].0, "ids": []})).unwrap();
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, list[2].1);
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, list[1].1);
assert_eq!(s.paint.stroke, stroke, "the stroke stays");
assert_eq!(node(&s, a).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "A keeps its fill");
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap();
assert_eq!(swatch_chips(&mut s, v), vec![(chip_color(&list[0].1), false), (chip_color(&list[1].1), true), (chip_color(&list[2].1), false)]);
let alt = Mods { alt: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0).with_mods(alt), v).unwrap();
assert!(swatch_chips(&mut s, v).is_empty(), "Alt samples with the eyedropper and shows no chips");
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap();
// Past the first swatch, Left wraps around to the last.
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, list[n - 1].1);
assert_eq!(swatch_chips(&mut s, v).iter().map(|c| c.0).collect::<Vec<_>>(), [&list[n - 2].1, &list[n - 1].1, &list[0].1].map(chip_color));
// With the Stroke proxy in front, the arrows step the stroke and the chips show it.
s.execute("paint.toggleActive", &json!({"fill": false})).unwrap();
let fill = s.paint.fill.clone();
s.execute("paint.setStroke", &json!({"swatch": list[1].0, "ids": []})).unwrap();
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!((&s.paint.fill, &s.paint.stroke), (&fill, &list[2].1));
assert!(!s.fill_active, "the Stroke proxy stays in front");
assert_eq!(swatch_chips(&mut s, v)[1], (chip_color(&list[2].1), true));
assert_eq!(node(&s, a).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "A keeps its paint");
// Cursor Swatch Preview off hides the chips; the arrows still step.
s.set_tool_option_cmd(&json!({"tool": "livePaintBucket", "values": {"cursorSwatchPreview": false}})).unwrap();
assert!(swatch_chips(&mut s, v).is_empty());
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.stroke, list[3].1);
}
/// The Live Paint Bucket and the Shape Builder take Left and Right for swatches only without
/// modifiers: Shift, Alt and Cmd/Ctrl arrows are left to their shortcuts and change no paint.
#[test]
fn swatch_arrow_keys_leave_modified_arrows_to_the_shortcuts() {
let mut s = session();
two(&mut s);
let v = ViewInfo::default();
let first = vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc)[0].name.clone();
s.execute("paint.setFill", &json!({"swatch": first, "ids": []})).unwrap();
for tool in ["livePaintBucket", "shapeBuilder"] {
s.select_tool(tool, v).unwrap();
if tool == "shapeBuilder" {
s.set_tool_option_cmd(&json!({"tool": tool, "values": {"pickColorFrom": "swatches"}})).unwrap();
}
let fill = s.paint.fill.clone();
assert!(s.tool_claims_key_with(ToolKey::Right, Mods::default(), v), "{tool}");
for m in [Mods { shift: true, ..Default::default() }, Mods { alt: true, ..Default::default() }, Mods { cmd: true, ..Default::default() }] {
for key in [ToolKey::Left, ToolKey::Right] {
assert!(!s.tool_claims_key_with(key, m, v), "{tool} {key:?} {m:?}");
s.tool_key(key, m, v).unwrap();
assert_eq!(s.paint.fill, fill, "{tool} {key:?} {m:?}");
}
}
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_ne!(s.paint.fill, fill, "{tool}: a plain Right steps");
}
}
/// Two swatches of the same color: the Bucket's arrows step through both, and the fill and the
/// stroke each step on from the swatch picked for them.
#[test]
fn live_paint_bucket_arrow_keys_pass_swatches_of_the_same_color_for_fill_and_stroke() {
let mut s = session();
two(&mut s);
for name in ["Twin A", "Twin B"] {
s.execute("swatch.new", &json!({"name": name, "color": "#123456"})).unwrap();
}
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
let names: Vec<String> = vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc).iter().map(|sw| sw.name.clone()).collect();
let a = names.iter().position(|n| n == "Twin A").unwrap();
assert_eq!(names[a + 1], "Twin B");
let after = vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc)[(a + 2) % names.len()].paint.clone();
// The fill goes to Twin B.
s.execute("paint.setFill", &json!({"swatch": "Twin A", "ids": []})).unwrap();
let twin = s.paint.fill.clone();
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, twin, "Twin B");
// The stroke starts at Twin A: Right goes to Twin B, then past it.
s.execute("paint.setStroke", &json!({"swatch": "Twin A", "ids": []})).unwrap();
assert!(!s.fill_active);
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.stroke, twin, "Twin B for the stroke");
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.stroke, after, "the swatch after Twin B");
// Back on the fill, which is still Twin B: Right goes past it.
s.execute("paint.toggleActive", &json!({"fill": true})).unwrap();
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, after, "the fill steps on from Twin B");
}
/// A color that is no swatch shows alone and Right picks the first swatch, Left the last; a paint
/// that is not a solid color shows no chip; one swatch steps to itself; with no color swatch the
/// tool leaves the arrows alone; during a fill drag the arrows change nothing.
#[test]
fn live_paint_bucket_arrow_keys_handle_unmatched_paint_few_swatches_and_drags() {
let mut s = session();
live(&mut s);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap();
let list: Vec<Paint> = vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc).iter().map(|sw| sw.paint.clone()).collect();
let odd = Paint::solid(Color::rgb8(0x12, 0x34, 0x57));
assert!(!list.contains(&odd));
s.paint.fill = odd.clone();
assert_eq!(swatch_chips(&mut s, v), vec![(chip_color(&odd), true)]);
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, list[0]);
s.paint.fill = odd.clone();
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, list[list.len() - 1]);
s.paint.fill = Paint::None;
assert!(swatch_chips(&mut s, v).is_empty());
// During a fill drag the arrows are not taken and change nothing.
s.paint.fill = list[0].clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
assert!(s.tool_busy());
assert!(!s.tool_claims_key(ToolKey::Right, v));
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, list[0]);
assert!(swatch_chips(&mut s, v).is_empty(), "no chips during a drag");
s.pointer(&PointerEvent::new(PointerKind::Up, 25.0, 50.0), v).unwrap();
// One color swatch: both arrows pick it, and it stands on both sides of itself.
let one = list[0].clone();
s.edit("t", |d, _| {
d.swatch_groups.clear();
d.swatches.retain(|sw| sw.paint == one);
d.swatches.truncate(1);
Ok(())
})
.unwrap();
assert_eq!(vectorcraft_tools::builder::color_swatches(&s.doc().unwrap().doc).len(), 1);
s.paint.fill = odd;
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, one);
s.pointer(&PointerEvent::new(PointerKind::Move, 301.0, 300.0), v).unwrap();
assert_eq!(swatch_chips(&mut s, v), vec![(chip_color(&one), false), (chip_color(&one), true), (chip_color(&one), false)]);
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, one);
// No color swatch: the arrows are left to the canvas and the paint stays.
s.edit("t", |d, _| {
d.swatches.clear();
Ok(())
})
.unwrap();
assert!(!s.tool_claims_key(ToolKey::Right, v) && !s.tool_claims_key(ToolKey::Left, v));
s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
assert_eq!(s.paint.fill, one);
}
#[test]
fn shape_builder_tool_alt_deletes_line_pieces() {
let mut s = session();
@@ -2446,6 +2643,193 @@ fn live_paint_stroke_edge() {
assert!(s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [300, 300]})).is_err());
}
/// The undo and redo depths, the unsaved state and the revision of the active document.
fn history_state(s: &Session) -> (usize, usize, bool, u64) {
let st = s.doc().unwrap();
(st.history.undo.len(), st.history.redo.len(), st.is_dirty(), st.revision)
}
/// Draw a rectangle and undo it, so a redo step is waiting, then mark the document saved with `g`
/// alone selected.
fn redo_waiting_and_saved(s: &mut Session, g: NodeId) {
rect(s, 300.0, 300.0, 10.0, 10.0);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.doc_mut().unwrap().mark_saved();
}
/// The active document and its [`history_state`].
type Snapshot = (vectorcraft_doc::Document, (usize, usize, bool, u64));
fn snapshot(s: &Session) -> Snapshot {
((*s.doc().unwrap().doc).clone(), history_state(s))
}
/// After a Live Paint edit that changed nothing: the document, the undo and redo steps, the saved
/// state and the revision are as `before`, and Redo still brings back the rectangle
/// [`redo_waiting_and_saved`] undid. Undoes the rectangle again, marks the document saved and
/// takes a new `before`.
fn assert_unchanged(s: &mut Session, before: &mut Snapshot, what: &str) {
assert!(*s.doc().unwrap().doc == before.0, "{what}: the document is as it was");
assert_eq!(history_state(s), before.1, "{what}: no undo step, the redo step kept, still saved");
let children = layer_children(s);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(layer_children(s), children + 1, "{what}: Redo brings back the rectangle");
s.execute("edit.undo", &json!({})).unwrap();
s.doc_mut().unwrap().mark_saved();
*before = snapshot(s);
}
#[test]
fn live_paint_fill_same_paint_is_no_op() {
let mut s = session();
let g = live(&mut s);
let drag = json!({"group": g.0, "point": [25, 50], "points": [[25, 50], [125, 50]], "color": "#00ff00"});
s.execute("livePaint.fill", &drag).unwrap();
redo_waiting_and_saved(&mut s, g);
// A color used since stays the newest recent color and the last color.
let blue = Color::rgb(0.0, 0.0, 1.0);
s.remember_paint_now(&Paint::solid(blue));
let recent = (s.recent_colors.clone(), s.last_solid);
let mut before = snapshot(&s);
let click = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap();
let face = vectorcraft_tools::builder::face_at(&node(&s, g), Point::new(75.0, 50.0)).unwrap().id;
assert_eq!(click, json!({"group": g.0, "face": face.0}), "the usual reply");
assert_unchanged(&mut s, &mut before, "a click on a face with the paint");
s.execute("livePaint.fill", &drag).unwrap();
assert_unchanged(&mut s, &mut before, "a drag over faces with the paint");
// Without a group, the click finds the Live Paint group among the selected objects.
s.execute("livePaint.fill", &json!({"point": [125, 50], "color": "#00ff00"})).unwrap();
assert_unchanged(&mut s, &mut before, "a click in the selected group");
assert_eq!((s.recent_colors.clone(), s.last_solid), recent, "the recent colors are as they were");
// A drag that reaches one face without the paint is one undo step and remembers the color.
let red = Paint::solid(Color::from_hex("#ff0000").unwrap());
for x in [25, 75] {
s.execute("livePaint.fill", &json!({"group": g.0, "point": [x, 50], "color": "#ff0000"})).unwrap();
}
s.remember_paint_now(&Paint::solid(blue));
let depth = s.doc().unwrap().history.undo.len();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "points": [[25, 50], [125, 50]], "color": "#ff0000"})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
assert_eq!(Paint::solid(s.last_solid), red);
let gn = node(&s, g);
for x in [25.0, 75.0, 125.0] {
assert_eq!(vectorcraft_tools::builder::face_at(&gn, Point::new(x, 50.0)).unwrap().appearance.fill_paint(), red, "{x}");
}
}
#[test]
fn live_paint_bucket_click_with_the_face_paint_is_no_op() {
let mut s = session();
let g = live(&mut s);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = Paint::solid(Color::rgb(0.0, 1.0, 1.0));
let click = |s: &mut Session, x: f64| {
s.pointer(&PointerEvent::new(PointerKind::Down, x, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, x, 50.0), v).unwrap();
};
click(&mut s, 125.0);
redo_waiting_and_saved(&mut s, g);
let mut before = snapshot(&s);
click(&mut s, 125.0);
assert_unchanged(&mut s, &mut before, "a Bucket click on a face with the paint");
// A drag over faces with the paint changes nothing either.
click(&mut s, 25.0);
click(&mut s, 75.0);
redo_waiting_and_saved(&mut s, g);
let mut before = snapshot(&s);
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
assert_unchanged(&mut s, &mut before, "a Bucket drag over faces with the paint");
}
#[test]
fn live_paint_stroke_edge_same_paint_and_width_is_no_op() {
let mut s = session();
let g = live(&mut s);
let call = json!({"group": g.0, "point": [100, 50], "color": "#ff0000", "width": 3});
let first = s.execute("livePaint.strokeEdge", &call).unwrap();
redo_waiting_and_saved(&mut s, g);
s.remember_paint_now(&Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let last = s.last_solid;
let mut before = snapshot(&s);
assert_eq!(s.execute("livePaint.strokeEdge", &call).unwrap(), first, "the usual reply");
assert_unchanged(&mut s, &mut before, "an edge with the paint and the width");
assert_eq!(s.last_solid, last, "the last color is as it was");
// Another width is an edit.
s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [100, 50], "color": "#ff0000", "width": 2})).unwrap();
assert_eq!(history_state(&s).0, before.1.0 + 1);
}
#[test]
fn live_paint_gap_options_same_values_are_no_op() {
let mut s = session();
let g = live_square_with_a_gap(&mut s);
let set = json!({"detect": true, "size": "small", "color": "#123456"});
let first = s.execute("livePaint.gapOptions", &set).unwrap();
redo_waiting_and_saved(&mut s, g);
let mut before = snapshot(&s);
assert_eq!(s.execute("livePaint.gapOptions", &set).unwrap(), first, "the usual reply");
assert_unchanged(&mut s, &mut before, "the options the group has");
s.execute("livePaint.gapOptions", &json!({})).unwrap();
assert_unchanged(&mut s, &mut before, "no options given");
// Close Gaps With Paths with a gap to close is an edit.
let r = s.execute("livePaint.gapOptions", &json!({"closeGaps": true})).unwrap();
assert_eq!(r["closed"], 1);
assert_eq!(history_state(&s).0, before.1.0 + 1);
}
#[test]
fn live_paint_gap_options_close_without_gaps_is_no_op() {
let mut s = session();
let g = live(&mut s);
redo_waiting_and_saved(&mut s, g);
let mut before = snapshot(&s);
let r = s.execute("livePaint.gapOptions", &json!({"id": g.0, "closeGaps": true})).unwrap();
assert_eq!((ids(&r), &r["faces"], &r["closed"], gaps_of(&r).len()), (vec![g], &json!(3), &json!(0), 0));
assert_unchanged(&mut s, &mut before, "no gap to close");
// With other options, the faces keep their ids when no path is added.
let faces = |s: &Session| vectorcraft_tools::builder::faces(&node(s, g)).iter().map(|f| f.id).collect::<Vec<_>>();
let ids_before = faces(&s);
s.execute("livePaint.gapOptions", &json!({"id": g.0, "closeGaps": true, "color": "#00ff00"})).unwrap();
assert_eq!(history_state(&s).0, before.1.0 + 1);
assert_eq!(faces(&s), ids_before);
}
#[test]
fn live_paint_make_existing_group_is_no_op() {
let mut s = session();
let g = live(&mut s);
redo_waiting_and_saved(&mut s, g);
let mut before = snapshot(&s);
let r = s.execute("livePaint.make", &json!({})).unwrap();
assert_eq!((NodeId(r["id"].as_u64().unwrap()), &r["faces"]), (g, &json!(3)));
assert_eq!(r["edges"].as_u64().unwrap(), vectorcraft_tools::builder::edges(&node(&s, g)).len() as u64);
assert_unchanged(&mut s, &mut before, "Make with the group alone");
}
#[test]
fn live_paint_merge_single_group_is_no_op() {
let mut s = session();
let g = live(&mut s);
let other = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
redo_waiting_and_saved(&mut s, g);
// Given by id, the group is selected without an undo step.
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
let before = snapshot(&s);
let r = s.execute("livePaint.merge", &json!({"ids": [g.0]})).unwrap();
assert_eq!((NodeId(r["id"].as_u64().unwrap()), &r["faces"]), (g, &json!(3)));
assert_eq!(s.doc().unwrap().selection.objects, vec![g]);
assert!(*s.doc().unwrap().doc == before.0);
let (undo, redo, dirty, _) = history_state(&s);
assert_eq!((undo, redo, dirty), (before.1.0, before.1.1, before.1.2));
// A path to add is an edit.
s.execute("livePaint.merge", &json!({"ids": [g.0, other.0]})).unwrap();
assert_eq!(history_state(&s).0, before.1.0 + 1);
}
/// Shape Builder refuses an on/off option that is not true or false and a tolerance or gap that is
/// not a number, given as text or as another value of the wrong kind, naming the key; the document
/// and the undo history stay as they were. True, false and null still work.
@@ -3097,9 +3481,10 @@ fn live_paint_tool_options_refuse_invalid_values_and_change_nothing() {
let colors = [json!(3), json!("nope"), json!("#12345"), json!("#00ff0080"), json!("00ff0080"), json!("#0f08"), json!(null)];
let widths = [json!("wide"), json!(null), json!(true)];
let switches = [json!("true"), json!(null), json!(1)];
for (tool, keys) in
[("livePaintBucket", &["paintFills", "paintStrokes", "highlight"][..]), ("livePaintSelection", &["selectFills", "selectStrokes"][..])]
{
for (tool, keys) in [
("livePaintBucket", &["paintFills", "paintStrokes", "cursorSwatchPreview", "highlight"][..]),
("livePaintSelection", &["selectFills", "selectStrokes"][..]),
] {
let mut bad: Vec<(&str, Value)> = keys.iter().flat_map(|k| switches.iter().map(move |v| (*k, v.clone()))).collect();
bad.extend(colors.iter().map(|v| ("color", v.clone())));
bad.extend(widths.iter().map(|v| ("width", v.clone())));
+42
View File
@@ -109,6 +109,48 @@ fn saturate_keeps_a_color_it_does_not_change() {
assert_eq!(paint(&s, b), cmyk);
}
/// An Edit Colors pass, a Blend or Recolor Artwork that changes nothing records no undo step, and the
/// step that redo would bring back stays; one that changes a color still records one.
#[test]
fn edit_colors_that_change_nothing_record_no_undo_step() {
let mut s = session();
let gray = rect(&mut s, json!("#808080"));
let a = rect(&mut s, json!("#ff0000"));
let b = rect(&mut s, json!("#808080"));
let c = rect(&mut s, json!("#0000ff"));
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
s.execute("edit.colors.blendFrontToBack", &json!({})).unwrap();
// A step for redo to bring back.
s.execute("edit.colors.invert", &json!({"ids": [a.0]})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let history = |s: &Session| {
let h = &s.doc().unwrap().history;
(h.undo.len(), h.redo.len())
};
let before = history(&s);
assert_eq!(before.1, 1, "one step to redo");
let doc = s.doc().unwrap().doc.clone();
let cases = [
("edit.colors.invert", json!({"fill": false, "stroke": false})),
("edit.colors.saturate", json!({"intensity": 0})),
("edit.colors.toRGB", json!({})),
("edit.colors.adjustBalance", json!({"mode": "rgb", "r": 0})),
("edit.colors.blendFrontToBack", json!({})),
("recolor.apply", json!({"map": {"#ff0000": "#ff0000"}})),
// The complement of a gray is the same gray.
("paint.complement", json!({"ids": [gray.0], "stroke": false})),
("addon.color.filter", json!({"effect": "addon.color.invert", "fill": false, "stroke": false})),
];
for (id, p) in cases {
let v = s.execute(id, &p).unwrap();
assert_eq!(v["changed"], 0, "{id}");
assert_eq!(history(&s), before, "{id}: no undo step, and redo is kept");
assert_eq!(s.doc().unwrap().doc, doc, "{id}: the document is unchanged");
}
s.execute("edit.colors.invert", &json!({})).unwrap();
assert_eq!(history(&s), (before.0 + 1, 0), "a pass that changes colors is one undo step");
}
/// Adjust Color Balance refuses a channel that is not a number, which it would otherwise read as 0.
#[test]
fn adjust_balance_refuses_a_channel_that_is_not_a_number() {
+88
View File
@@ -253,3 +253,91 @@ fn events_and_files_survive_a_native_round_trip_and_reach_svg() {
assert!(svg.contains(" onclick=\"show(&quot;menu&quot;) &amp;&amp; x &lt; 1\""), "{svg}");
assert!(svg.contains("<script xlink:href=\"menu.js\"/>"), "{svg}");
}
/// A caller confined to read roots: every SVG and SVGZ output of a document that links a
/// JavaScript file outside them is refused before a file or folder is written, with an error that
/// names no file or folder, and the document keeps the link.
#[test]
fn confined_svg_output_refuses_a_linked_javascript_file_outside_the_read_roots() {
let away = crate::tests_links::Folder::new("svg-script-away");
let home = crate::tests_links::Folder::new("svg-script-home");
let script = away.file("menu.js");
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "svgInteractivity.addFile", json!({"file": script}));
run(&mut s, "assets.add", json!({"ids": [a.0]}));
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "menu.js".to_string()];
let refused = |s: &mut Session, cmd: &str, p: Value| {
let e = crate::file_access::confine(Some(&roots), || s.execute(cmd, &p)).expect_err(cmd).to_string();
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{cmd} {p}: {e}");
for h in &hidden {
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
}
};
let out = home.file("out");
for format in ["svg", "svgz"] {
let file = |name: &str| home.file(&format!("{name}.{format}"));
refused(&mut s, "document.serialize", json!({"format": format}));
refused(&mut s, "document.export", json!({"format": format}));
refused(&mut s, "document.export", json!({"format": format, "path": file("export")}));
refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true}));
refused(&mut s, "document.exportSelection", json!({"format": format, "path": file("selection")}));
refused(&mut s, "document.save", json!({"path": file("save")}));
refused(&mut s, "file.saveAs", json!({"format": format, "path": file("save-as")}));
refused(&mut s, "file.saveCopy", json!({"format": format, "path": file("copy")}));
refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": format}]}));
refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": format}]}));
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": format}]}));
}
// A document saved as SVG saves as SVG again without a path: its file is left as it was.
let own = home.file("own.svg");
run(&mut s, "file.saveAs", json!({"path": own}));
let before = std::fs::read(&own).unwrap();
rect(&mut s, 50.0);
refused(&mut s, "document.save", json!({}));
assert_eq!(std::fs::read(&own).unwrap(), before);
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(written, ["own.svg"]);
assert_eq!(s.doc().unwrap().doc.svg_scripts, [script]);
}
/// A confined caller's SVG keeps every linked JavaScript file it may read, as stored: a file inside
/// the read roots, a path relative to the document's folder that leads inside them, and a URL. A
/// caller without roots writes a file outside them too.
#[test]
fn svg_output_keeps_linked_javascript_files_a_caller_may_read() {
let away = crate::tests_links::Folder::new("svg-script-kept-away");
let home = crate::tests_links::Folder::new("svg-script-kept-home");
let inside = home.file("menu.js");
let url = "https://example.com/scripts/menu.js";
let mut s = session();
rect(&mut s, 10.0);
for file in [inside.as_str(), "lib/tools.js", url] {
run(&mut s, "svgInteractivity.addFile", json!({"file": file}));
}
run(&mut s, "file.saveAs", json!({"path": home.file("doc.vectorcraft")}));
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
let svg = |s: &mut Session, format: &str| {
let r = crate::file_access::confine(Some(&roots), || s.execute("document.serialize", &json!({"format": format}))).unwrap();
match r["text"].as_str() {
Some(text) => text.to_string(),
None => {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
assert!(vectorcraft_svg::is_svgz(&bytes), "gzip magic");
vectorcraft_svg::text_of(&bytes).unwrap().into_owned()
}
}
};
for format in ["svg", "svgz"] {
let text = svg(&mut s, format);
for file in [inside.as_str(), "lib/tools.js", url] {
assert!(text.contains(&format!("<script xlink:href=\"{file}\"/>")), "{format} {file}: {text}");
}
}
// Without roots, a file outside them is written as stored.
let outside = away.file("menu.js");
run(&mut s, "svgInteractivity.addFile", json!({"file": outside}));
let text = run(&mut s, "document.serialize", json!({"format": "svg"}))["text"].as_str().unwrap().to_string();
assert!(text.contains(&format!("<script xlink:href=\"{outside}\"/>")), "{text}");
}
+153
View File
@@ -712,6 +712,159 @@ fn type_in_symbol_art_reports_a_gradient_only_when_it_expands() {
}
}
/// Selected type "Hi" at 64 pt whose characters have no paint, with fills and strokes of its own:
/// each of `items` is an `appearance.setItem` edit of a new object-level stroke when it has a
/// `weight`, else of a new object-level fill; the first `below` of them paint below the characters.
fn type_with_own_paint(s: &mut Session, items: &[Value], below: usize) -> NodeId {
let t = run(s, "text.create", json!({"x": 25, "y": 110, "text": "Hi", "size": 64}))["id"].as_u64().unwrap();
run(s, "select.set", json!({"ids": [t]}));
run(s, "paint.setFill", json!({"none": true}));
run(s, "paint.setStroke", json!({"none": true}));
for (i, item) in items.iter().enumerate() {
let add = if item.get("weight").is_some() { "appearance.addStroke" } else { "appearance.addFill" };
run(s, add, json!({"target": "object"}));
let mut p = item.clone();
p["index"] = json!(i);
run(s, "appearance.setItem", p);
}
run(s, "appearance.moveItem", json!({"from": "contents", "to": below}));
NodeId(t)
}
fn blue_stroke() -> Value {
json!({"color": "#0000ff", "weight": 5})
}
fn red_blue() -> Value {
json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}})
}
/// Create Outlines draws what the type drew: a gradient fill of the type object's own, below its
/// characters, keeps one gradient across both glyphs over the layout's box, and its stroke stays
/// over them.
#[test]
fn create_outlines_draws_the_type_objects_own_paint() {
let mut s = session();
type_with_own_paint(&mut s, &[red_blue(), blue_stroke()], 1);
let before = render(&s);
run(&mut s, "type.createOutlines", json!({}));
let after = render(&s);
let n = differing(&before, &after, 24);
assert!(n < 40, "{n} pixels differ");
assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something");
}
/// `object.expand.info` reports the type object's own stroke, pattern fill and gradient fill, which
/// Object turns into paths of its whole outline: a gradient only when that outline's box needs no
/// more runs than are written.
#[test]
fn type_objects_own_stroke_pattern_and_gradient_are_reported() {
let mut s = session();
type_with_own_paint(&mut s, &[blue_stroke()], 0);
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["object"].clone(), info["stroke"].clone(), info["fill"].clone()), (json!(true), json!(true), json!(false)), "{info}");
let mut s = session();
pattern_rect(&mut s, Rect::new(150.0, 150.0, 190.0, 190.0), false);
let t = type_with_own_paint(&mut s, &[json!({"swatch": "Dots"})], 0);
run(&mut s, "select.set", json!({"ids": [t.0]}));
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["fill"].clone(), info["gradient"].clone(), info["stroke"].clone()), (json!(true), json!(false), json!(false)), "{info}");
// 0.4 pt runs across about 80 pt: under the limit; 0.02 pt runs: far over it.
for (len, expands) in [(40.0, true), (2.0, false)] {
let mut s = session();
let gradient = json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [25, 100], "end": [25.0 + len, 100],
"stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}});
type_with_own_paint(&mut s, &[gradient], 0);
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(expands), json!(expands)), "{len}: {info}");
run(&mut s, "object.expand", json!({}));
let (gradients, texts) = gradients_and_type(&s);
assert_eq!(texts, 0, "{len}: outlined");
assert_eq!(gradients == 0, expands, "{len}: {gradients} gradient fills left");
}
}
/// Type with only spaces has no outline for its own stroke or pattern fill to go on, so
/// `object.expand.info` reports neither.
#[test]
fn type_without_an_outline_reports_no_own_stroke_or_fill() {
let mut s = session();
pattern_rect(&mut s, Rect::new(150.0, 150.0, 190.0, 190.0), false);
let t = run(&mut s, "text.create", json!({"x": 25, "y": 110, "text": " ", "size": 64}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [t]}));
run(&mut s, "paint.setFill", json!({"none": true}));
run(&mut s, "paint.setStroke", json!({"none": true}));
for (i, item) in [json!({"swatch": "Dots"}), blue_stroke()].into_iter().enumerate() {
let add = if item.get("weight").is_some() { "appearance.addStroke" } else { "appearance.addFill" };
run(&mut s, add, json!({"target": "object"}));
let mut p = item;
p["index"] = json!(i);
run(&mut s, "appearance.setItem", p);
}
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!(
(info["object"].clone(), info["stroke"].clone(), info["fill"].clone(), info["gradient"].clone()),
(json!(true), json!(false), json!(false), json!(false)),
"{info}"
);
}
/// How many objects in the document have a visible stroke with paint and weight.
fn painted_strokes(s: &Session) -> usize {
let mut n = 0;
s.doc().unwrap().doc.walk(|c| {
n += usize::from(
c.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if st.visible && !st.paint.is_none() && st.width > 0.0)),
);
});
n
}
/// A visible stroke under a topmost stroke with no paint still has something for Stroke to
/// outline, on type's own appearance and on a path: `object.expand.info` reports it, and Expand
/// outlines it.
#[test]
fn a_stroke_under_an_unpainted_stroke_is_reported_and_outlined() {
let mut s = session();
type_with_own_paint(&mut s, &[blue_stroke(), json!({"none": true, "weight": 1})], 0);
let mut r = session();
run(&mut r, "shape.rectangle", json!({"x": 40, "y": 40, "width": 100, "height": 80}));
run(&mut r, "paint.setStroke", json!({"color": "#0000ff"}));
run(&mut r, "stroke.set", json!({"weight": 4}));
run(&mut r, "appearance.addStroke", json!({"target": "object"}));
let top = node(&r, selected(&r).id).appearance.items.len() - 1;
run(&mut r, "appearance.setItem", json!({"index": top, "none": true}));
for (what, s) in [("type", &mut s), ("path", &mut r)] {
let info = run(s, "object.expand.info", json!({}));
assert_eq!(info["stroke"], json!(true), "{what}: {info}");
run(s, "object.expand", json!({}));
assert_eq!(painted_strokes(s), 0, "{what}: the stroke is outlined");
}
}
/// Expand keeps the type object's own stroke and gradient fill through Object: Stroke outlines the
/// stroke and Fill expands the gradient, and with those options off they stay live on the path of
/// the whole outline. The picture stays the same either way.
#[test]
fn expand_keeps_the_type_objects_own_paint() {
for (opts, live) in [(json!({}), false), (json!({"fill": false, "stroke": false}), true)] {
let mut s = session();
type_with_own_paint(&mut s, &[red_blue(), blue_stroke()], 1);
let before = render(&s);
run(&mut s, "object.expand", opts.clone());
let after = render(&s);
assert!(mean_diff(&before, &after) < 2.0, "{opts}: {}", mean_diff(&before, &after));
let (gradients, texts) = gradients_and_type(&s);
assert_eq!(texts, 0, "{opts}: outlined");
assert_eq!(gradients == 1, live, "{opts}: {gradients} gradient fills");
let mut strokes = 0;
s.doc().unwrap().doc.walk(|n| strokes += usize::from(!n.appearance.stroke_paint().is_none()));
assert_eq!(strokes == 1, live, "{opts}: {strokes} strokes");
}
}
#[test]
fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() {
for gradient in [
+45
View File
@@ -1043,6 +1043,51 @@ fn create_outlines_matches_text_bounds() {
assert!(s.doc().unwrap().doc.node(t).is_some());
}
/// The type object's own fills and strokes (not its characters') become paths of its whole outline,
/// with ids of their own: those below the Characters row under the glyph paths, the others over
/// them, in their order. The group keeps no appearance of its own, and Undo brings the type back.
#[test]
fn create_outlines_keeps_the_objects_own_fills_and_strokes() {
let mut s = session();
let t = text(&mut s, "Hi", 64.0);
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
for (cmd, p) in [
("appearance.addFill", json!({"target": "object"})),
("appearance.setItem", json!({"index": 0, "color": "#ff0000"})),
("appearance.addStroke", json!({"target": "object"})),
("appearance.setItem", json!({"index": 1, "color": "#0000ff", "weight": 5})),
("appearance.addFill", json!({"target": "object"})),
("appearance.setItem", json!({"index": 2, "color": "#00ff00", "opacity": 50})),
// The red fill paints below the characters; the stroke and the green fill over them.
("appearance.moveItem", json!({"from": "contents", "to": 1})),
] {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
}
let own = node(&s, t).appearance.items.clone();
assert_eq!(own.len(), 3);
let r = ids(&s.execute("type.createOutlines", &json!({})).unwrap());
let g = node(&s, r[0]);
assert!(g.appearance.items.is_empty(), "the group paints nothing of its own");
let ch = g.children().unwrap();
assert_eq!(ch.len(), 4, "a path below, the two glyphs, a path above");
let (first, last) = (&ch[0], &ch[3]);
assert_eq!(first.appearance.items, own[..1], "the item below the characters");
assert_eq!(last.appearance.items, own[1..], "the items over them, in their order");
for c in [first, last] {
assert!(matches!(c.kind, NodeKind::Path { .. }), "{:?}", c.kind);
assert!(c.id != t && c.id != g.id, "a fresh id");
}
assert!(first.id != last.id);
for c in &ch[1..3] {
assert_eq!(c.appearance.fill_paint(), Paint::solid(Color::BLACK), "the characters keep their own paint");
}
// The whole-outline paths cover both glyphs.
let glyphs = ch[1].geometric_bounds().unwrap().union(ch[2].geometric_bounds().unwrap());
assert!(close(first.geometric_bounds().unwrap(), glyphs, 1e-6), "{:?} vs {glyphs:?}", first.geometric_bounds());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, t).appearance.items, own, "one undo step brings the type back");
}
/// Colour bitmap glyphs (emoji) become embedded images where they sat; glyphs showing one image
/// share its pixels.
#[test]
+10 -1
View File
@@ -12,7 +12,7 @@ fn is_bad_params(r: Result<Value>) -> bool {
}
/// Folder preferences, which a preferences file leaves out.
const FOLDERS: [&str; 4] = ["fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"];
const FOLDERS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
/// A preferences file holding `prefs`, as `prefs.export` writes one.
fn file(prefs: Value) -> String {
@@ -46,7 +46,9 @@ fn in_file(s: &Session) -> Value {
fn exported_preferences_import_unchanged() {
let mut s = changed();
s.prefs.fonts_folder = "/fonts/here".into();
s.prefs.scratch_primary = "/scratch/here".into();
let r = s.execute("prefs.export", &json!({})).unwrap();
assert!(!r["data"].as_str().unwrap().contains("/scratch/here"), "a scratch disk folder is not written");
let text = r["data"].as_str().unwrap().to_string();
let written: Value = serde_json::from_str(&text).unwrap();
assert_eq!((written["format"].as_str(), written["version"].as_u64()), (Some(PREFS_FORMAT), Some(1)));
@@ -71,6 +73,7 @@ fn exported_preferences_import_unchanged() {
assert_eq!(t.doc().unwrap().doc.units, Unit::Millimeters, "the document's units stay as they are");
assert_eq!(t.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(t.prefs.fonts_folder, "", "folders are not carried over");
assert_eq!(t.prefs.scratch_primary, "Startup", "nor is a scratch disk");
// Through a file, too.
let path = std::env::temp_dir().join(format!("vc-prefs-{}.json", std::process::id())).to_string_lossy().to_string();
@@ -96,6 +99,10 @@ fn a_hand_written_file_sets_what_it_names_and_leaves_the_rest() {
assert_eq!(s.prefs.keyboard_increment, 3.0);
assert_eq!(s.prefs.guide_color, "#abcdef");
assert_eq!(s.prefs.history_states, 77, "a preference the file leaves out keeps its value");
// A scratch disk choice names no folder, and is read.
let choices = file(json!({"scratchPrimary": "None", "scratchSecondary": "Startup"}));
assert_eq!(s.execute("prefs.import", &json!({"data": choices})).unwrap(), json!({"imported": 2}));
assert_eq!((s.prefs.scratch_primary.as_str(), s.prefs.scratch_secondary.as_str()), ("None", "Startup"));
}
#[test]
@@ -119,6 +126,8 @@ fn a_bad_preferences_file_is_refused_and_nothing_changes() {
(json!({"data": file(json!({"uiAccent": "blue", "historyStates": 5000}))}), "`historyStates` must be a whole number between 5 and 1000"),
(json!({"data": file(json!({"uiAccent": "blue", "eyedropper": 5}))}), "`eyedropper` must be an object"),
(json!({"data": file(json!({"uiAccent": "blue", "fontsFolder": "/fonts"}))}), "`fontsFolder` names a folder"),
(json!({"data": file(json!({"uiAccent": "blue", "scratchPrimary": "/scratch"}))}), "`scratchPrimary` names a folder"),
(json!({"data": file(json!({"uiAccent": "blue", "scratchSecondary": " scratch "}))}), "`scratchSecondary` names a folder"),
(json!({"data": too_large}), "larger than 1 MB"),
(json!({"data": 5}), "`data` must be a string"),
(json!({"path": "/a.json", "data": file(json!({"uiAccent": "blue"}))}), "give `path` or `data`"),
+61 -3
View File
@@ -2137,8 +2137,9 @@ fn datasets_csv_reads_windows_1252_files() {
}
/// A CSV that starts with a UTF-16 byte-order mark is read as UTF-16, and
/// one that isn't valid UTF-16 is refused. A file with NUL bytes and no byte-order mark is refused.
/// A text value holding NUL imports back from the `csv` that `dataset.export` returns.
/// one that isn't valid UTF-16 is refused. A file with NUL bytes and no byte-order mark that isn't
/// UTF-16 is refused. A text value holding NUL imports back from the `csv` that `dataset.export`
/// returns.
#[test]
fn datasets_csv_reads_utf16_files() {
let mut s = session();
@@ -2160,7 +2161,7 @@ fn datasets_csv_reads_utf16_files() {
assert!(e.contains("CSV is not UTF-16"), "{e}");
let e = import(&mut s, &[b"\xff\xfe".as_slice(), "City\nAB,".as_bytes(), b"\x00\xd8"].concat()).unwrap_err().to_string();
assert!(e.contains("CSV is not UTF-16"), "{e}");
let e = import(&mut s, &utf16(b"", "City\nx\n", true)).unwrap_err().to_string();
let e = import(&mut s, b"City\nx\0\n").unwrap_err().to_string();
assert!(e.contains("CSV holds NUL bytes"), "{e}");
assert_eq!(value(&s, "Data Set 1"), text_value("José"), "a refused file changes nothing");
s.execute("dataset.set", &json!({"name": "Data Set 1", "values": {"City": "a\u{0}b"}})).unwrap();
@@ -2170,6 +2171,63 @@ fn datasets_csv_reads_utf16_files() {
assert_eq!(value(&s, "Data Set 1"), text_value("a\u{0}b"));
}
/// A CSV in UTF-16 without a byte-order mark, with a NUL byte in at least half of its units, is
/// read in the byte order that reads a line break: in either order, with characters whose bytes
/// read as a line break, a quote or NUL, and when its bytes are also valid UTF-8. Files with fewer
/// NUL bytes, that read a line break in both orders, that aren't valid UTF-16 in it, that hold a
/// NUL character or that have an odd length are refused.
#[test]
fn datasets_csv_reads_utf16_files_without_a_byte_order_mark() {
let mut s = session();
s.execute("variable.define", &json!({"name": "City", "kind": "text"})).unwrap();
let import = |s: &mut Session, bytes: &[u8]| s.execute("dataset.import", &json!({"dataBase64": vectorcraft_format::base64_encode(bytes)}));
let value = |s: &Session, name: &str| s.doc().unwrap().doc.variables.dataset(name).and_then(|d| d.values.get("City")).cloned();
let text_value = |v: &str| Some(vectorcraft_doc::DataValue::Text(v.into()));
let utf16 = |text: &str, le: bool| -> Vec<u8> { text.encode_utf16().flat_map(|u| if le { u.to_le_bytes() } else { u.to_be_bytes() }).collect() };
import(&mut s, &utf16("City\r\nParis\r\n", true)).unwrap();
assert_eq!(value(&s, "Data Set 1"), text_value("Paris"));
import(&mut s, &utf16("City\nZoë 😀\n", false)).unwrap();
assert_eq!(value(&s, "Data Set 1"), text_value("Zoë 😀"));
// U+4E00's low byte is NUL, U+010A holds a `\n` byte and U+2200 a `"` byte; all three files
// are valid UTF-8 too.
import(&mut s, &utf16("City\n一\n", true)).unwrap();
assert_eq!(value(&s, "Data Set 1"), text_value("一"));
import(&mut s, &utf16("City\nĊ\n", true)).unwrap();
assert_eq!(value(&s, "Data Set 1"), text_value("Ċ"));
import(&mut s, &utf16("City\n∀∀∀\n", true)).unwrap();
assert_eq!(value(&s, "Data Set 1"), text_value("∀∀∀"));
// A file with no line break has no data rows in either byte order.
for bytes in [utf16("City", true), utf16("City", false), b"\0aa\0".to_vec()] {
let e = import(&mut s, &bytes).unwrap_err().to_string();
assert!(e.contains("CSV has a header but no data rows"), "{e}");
}
import(&mut s, &utf16("City\tName\n一二三丁目\tKai\n", true)).unwrap();
assert_eq!(value(&s, "Data Set 1"), text_value("一二三丁目"));
// Most units hold their NUL byte where a big-endian file would (U+4E00); the line breaks
// give the byte order.
import(&mut s, &utf16("City\n一一一一一一一一一一二\n", true)).unwrap();
assert_eq!(value(&s, "Data Set 1"), text_value("一一一一一一一一一一二"));
// Windows-1252 and UTF-8 text with stray NUL bytes (the first with `\n\0` units), UTF-16 with
// fewer than half of its units holding a NUL byte, and, last, two files that read a line break
// in both byte orders (U+0D00 reads as `\r` and U+0A00 as `\n` big-endian).
let refused: [&[u8]; 9] = [
b"Caf\xe9\n\0Lyon\n\0",
b"Cit\0\n",
b"City\nx\0\n",
&utf16("City\n丁丁丁丁丁丁丁丁丁丁\n", true),
&utf16("City\na\u{0}\n", true),
&[utf16("City\n", true), vec![0x00, 0xD8], utf16("\n", true)].concat(),
&[utf16("City\n", false), vec![0xDC, 0x00], utf16("\n", false)].concat(),
&utf16("City\n\u{0D00}\u{0D00}\u{0D00}\n", true),
&utf16("City\u{0A00}\nParis\n", true),
];
for bytes in refused {
let e = import(&mut s, bytes).unwrap_err().to_string();
assert!(e.contains("CSV holds NUL bytes"), "{bytes:?}: {e}");
}
assert_eq!(value(&s, "Data Set 1"), text_value("一一一一一一一一一一二"), "a refused file changes nothing");
}
/// A data set of [`library`]: its name, and each variable's name with its paragraphs.
type LibrarySet<'a> = (&'a str, &'a [(&'a str, &'a [&'a str])]);
+6
View File
@@ -1164,6 +1164,12 @@ impl Session {
self.plane_key(key).is_some() || self.with_tool_cx(view, |t, cx| t.claims_key(cx, key))
}
/// Does the active tool take `key`, pressed with `mods` held, ahead of the shortcuts bound to it
/// (see `Tool::claims_key_with`)?
pub fn tool_claims_key_with(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> bool {
self.plane_key(key).is_some() || self.with_tool_cx(view, |t, cx| t.claims_key_with(cx, key, mods))
}
/// Has the active tool started something that Escape ends while no button is pressed (see
/// `Tool::ends_on_escape`)?
pub fn tool_ends_on_escape(&mut self, view: ViewInfo) -> bool {
+30
View File
@@ -7488,3 +7488,33 @@ proptest! {
prop_assert!(!notes.iter().any(|n| n.contains("art this can't read")), "the records aren't art: {:?}", notes);
}
}
/// A graph in `.ai` editing data whose records read whole (version 7 specification, appendix A), of
/// a table `rows` × `cols` (its label row and column included): a series group tagged by its
/// column, and the axes on the plot's edges.
fn live_graph_text(rows: &str, cols: &str) -> String {
format!(
"%_Gs\n%_10 90 110 10 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\
%_1 () Ga\n%_0 13 0 0 0 0 0 () GA\n%_2 () Ga\n%_0 14 0 0 0 0 0 () GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n\
%_{rows} {cols} 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n\
u\nu\n0 0 0 1 k\n20 10 m\n20 50 L\n40 50 L\n40 10 L\nf\nU\n%_2 1 0 0 Go\nu\n0 0 0 1 K\n10 90 m\n10 10 L\n110 10 L\nS\nU\nU\n%_GS\n"
)
}
proptest! {
#![proptest_config(config())]
/// A `.ai` graph that reads whole, then cut or damaged, or with a table of any size (zero, past
/// the limits, past what memory holds), never panics, and its drawn art always comes in.
#[test]
fn ai_live_graph_never_panics(cut in 0usize..800, edits in prop::collection::vec((0usize..800, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '%', '_', 'G', 'c', 'C', 'o', 's', 'S', 'u', 'U'])), 0..12), rows in prop_oneof![Just(2u64), 0u64..20_000, Just(u64::MAX)], cols in prop_oneof![Just(2u64), 0u64..400, Just(4_000_000_000u64)]) {
let text = mutate_text(&live_graph_text("2", "2"), cut, &edits);
survive("mutated live .ai graph", || Some(vectorcraft_eps::layered_ai(&ai_private(&text), Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?;
let sized = live_graph_text(&rows.to_string(), &cols.to_string());
let (doc, notes, read) = vectorcraft_eps::layered_ai(&ai_private(&sized), Document::new(4000.0, 200.0), vec![], false, true, 1.0);
prop_assert!(read, "{:?}", notes);
let mut paths = 0;
doc.walk(|n| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })));
prop_assert_eq!(paths, 2, "{:?}", notes);
}
}
@@ -502,3 +502,80 @@ fn batched_colored_inflate_preserves_compound_holes_and_surface_opacity() {
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(image.pixels, render(doc(&s)).pixels);
}
/// Under colored lights, an Inflate fill and stroke in solid colors draw each face on its own, in
/// one depth order: zoomed in, the fill's faces show the colors the one composite of the surface
/// shows (drawn when the stroke is translucent), with no seam between faces; at 1x, where a pixel
/// holds several faces, all but a few pixels show the average of the zoomed-in colors; and the art
/// keeps its colors through SVG export and Expand Appearance.
#[test]
fn colored_solid_inflate_faces_in_one_order_keep_the_composites_colors_and_seams() {
let mut s = Session::new();
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
s.execute("path.create", &json!({"d":"M100 100H300V300H100Z"})).unwrap();
s.execute("paint.setFill", &json!({"color":"#e0c080"})).unwrap();
s.execute("paint.setStroke", &json!({"color":"#204060","width":4})).unwrap();
s.execute(
"effect.apply",
&json!({"effect":"threeD.inflate","item":null,"params":{
"rotationX":0,"rotationY":0,"rotationZ":0,"lights":[{"color":"#ff4040"},{"color":"#4040ff","rotation":120}]
}}),
)
.unwrap();
let at = |d: &Document, scale: f64| {
vectorcraft_render::Renderer::new().render(
d,
400,
400,
kurbo::Affine::scale(scale) * kurbo::Affine::translate((-140.0, -140.0)),
&vectorcraft_render::RenderOptions { background: None, artboards: false, ..Default::default() },
)
};
let ordered = doc(&s).clone();
s.execute("transparency.set", &json!({"item":1,"opacity":99})).unwrap();
let whole = doc(&s).clone();
// The fill's puff, inside the stroke's: 150 to 250 pt across, 10 to 110 px at 1x.
let (near, near_whole, far) = (at(&ordered, 3.0), at(&whole, 3.0), at(&ordered, 1.0));
let (mut off, mut open) = (0, 0);
for y in 10..110u32 {
for x in 10..110u32 {
// At 3x each 1x pixel is nine pixels: the faces against the composite, pixel by pixel.
let mut sum = [0u32; 4];
for (dx, dy) in (0..9).map(|k| (k % 3, k / 3)) {
let (p, q) = (near.pixel(x * 3 + dx, y * 3 + dy), near_whole.pixel(x * 3 + dx, y * 3 + dy));
assert!(p[3] >= 254, "no seam at ({}, {}) at 3x: {p:?}", x * 3 + dx, y * 3 + dy);
assert!(
p.into_iter().zip(q).all(|(p, q)| p.abs_diff(q) <= 1),
"({}, {}) at 3x: {p:?} vs the composite's {q:?}",
x * 3 + dx,
y * 3 + dy
);
for (s, v) in sum.iter_mut().zip(p) {
*s += u32::from(v);
}
}
// At 1x, where a pixel holds several faces, a pixel has about the average of its nine:
// a few pixels where thin faces meet are off by more than 3 or let a little through.
let p = far.pixel(x, y);
assert!(p[3] >= 240, "a seam at ({x},{y}) at 1x: {p:?}");
open += usize::from(p[3] < 255);
off += usize::from(p.into_iter().zip(sum).any(|(p, s)| u32::from(p).abs_diff(s / 9) > 3));
}
}
assert!(open <= 500, "{open} of 10,000 pixels at 1x let the background through");
assert!(off <= 300, "{off} of 10,000 pixels at 1x are off the zoomed-in colors");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(doc(&s), &ordered);
let live = render(doc(&s));
let svg = s.execute("document.serialize", &json!({"format":"svg"})).unwrap()["text"].as_str().unwrap().to_owned();
assert!(!svg.contains("<image"));
let roundtrip = render(&vectorcraft_svg::import(&svg).unwrap());
for y in (110..290).step_by(9) {
for x in (110..290).step_by(9) {
let (a, b) = (live.pixel(x, y), roundtrip.pixel(x, y));
assert!(a.into_iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 6), "SVG ({x},{y}): {a:?} vs {b:?}");
}
}
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(render(doc(&s)).pixels, live.pixels);
}
+1
View File
@@ -9,6 +9,7 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P
workspace = true
[dependencies]
craft-eps = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
+247 -3
View File
@@ -7582,9 +7582,10 @@ fn a_linked_object_past_the_object_limit_warns_that_its_link_is_left_out() {
}
/// A link to a graphic style with Twist is kept where the reader reads Twist: on a curve, a curved
/// compound path or a group with nothing stroked up to a quarter turn, and on a path with straight
/// segments at any angle. A stroked curve, a group with a stroked member or a guide, or a curve,
/// compound path or group twisted further, is written without the link and warns.
/// compound path or a group with nothing stroked up to a quarter turn, and on a path or compound path
/// with straight segments up to half a turn. A stroked curve, a group with a stroked member or a
/// guide, a straight compound path with a guide member that reaches past its other members, or an
/// object twisted further, is written without the link and warns.
#[test]
fn a_link_to_a_twist_style_is_kept_where_the_reader_reads_it() {
// A document with the object `make` builds from its appearance, `ap` with Twist at `angle`,
@@ -7619,6 +7620,17 @@ fn a_link_to_a_twist_style_is_kept_where_the_reader_reads_it() {
n.appearance = ap.into();
n
};
// A compound path of a square and a guide, a rectangle with corners `a` and `b`.
let guided = |a: (f64, f64), b: (f64, f64)| {
move |doc: &mut Document, ap: Appearance| {
let outer = Node::path(doc.alloc_id(), square(), Appearance::default());
let path = shapes::rectangle(Rect::new(a.0, a.1, b.0, b.1));
let guide = Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true });
let mut n = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(guide)], rule: FillRule::NonZero });
n.appearance = ap.into();
n
}
};
// A group of a filled square and `second`.
let group = |second: fn(&mut Document) -> Node| {
move |doc: &mut Document, ap: Appearance| {
@@ -7649,6 +7661,8 @@ fn a_link_to_a_twist_style_is_kept_where_the_reader_reads_it() {
("a square twisted three quarters of a turn back", twisted(-270.0, filled(), path(square())), false),
("a straight compound path twisted half a turn", twisted(180.0, filled(), frame), true),
("a straight compound path twisted a full turn", twisted(360.0, filled(), frame), false),
("a straight compound path with a guide inside it", twisted(45.0, filled(), guided((30.0, 20.0), (70.0, 50.0))), true),
("a straight compound path with a guide reaching past it", twisted(45.0, filled(), guided((30.0, 20.0), (120.0, 50.0))), false),
("a curve twisted past a quarter turn", twisted(120.0, filled(), path(oval())), false),
("a stroked curve", twisted(45.0, Appearance::basic(black_fill(), red.clone(), 2.0), path(oval())), false),
("a curved compound path", twisted(-60.0, filled(), ring), true),
@@ -9793,3 +9807,233 @@ fn envelopes_document() -> Document {
}
doc
}
// ---------- text wrap ----------
/// `n` with text wrap options `offset` and `invert`.
fn wrapped(mut n: Node, offset: f64, invert: bool) -> Node {
n.extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset, invert });
n
}
/// The text wrap options of `nodes` and of the objects they hold, in order, each with its object's
/// name.
fn wraps(nodes: &[Arc<Node>]) -> Vec<(Option<String>, f64, bool)> {
let mut out = vec![];
for n in nodes {
n.walk(&mut |m| {
if let Some(w) = m.extras().wrap {
out.push((m.name.clone(), w.offset, w.invert));
}
});
}
out
}
/// `got` and `want` name the same objects with the same Invert Wrap, and offsets within `1e-6`.
fn same_wraps(got: &[(Option<String>, f64, bool)], want: &[(Option<String>, f64, bool)]) {
let close = got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.0 == w.0 && g.2 == w.2 && (g.1 - w.1).abs() < 1e-6);
assert!(close, "{got:?}\n{want:?}");
}
/// The dictionary entries of text wrap options `offset` (as written) and `invert`.
fn wrap_entries(offset: &str, invert: bool) -> String {
format!("%_{offset} /Real (AI11TextWrapOffset) ,\n%_{} /Bool (AI11TextWrapInvert) ,\n", u8::from(invert))
}
/// Text wrap options are written in each object's dictionary and read back: a positive and a
/// negative offset, Invert Wrap on and off, the default options, an object without them, a named
/// object with an opacity mask, a group, a compound path and a clipping group's clipping path. An
/// offset that isn't finite is written as the default 6 pt, and one past the -1000 to 1000 pt the
/// reader keeps as the nearer end of that range.
#[test]
fn text_wrap_options_are_written_and_read_back() {
let mut doc = Document::new(400.0, 200.0);
let layer = doc.layers[0].id;
let plain = |doc: &mut Document, x: f64| square(doc, Rect::new(x, 10.0, x + 20.0, 30.0), Color::gray(0.5));
let a = wrapped(plain(&mut doc, 10.0), 12.5, false);
let b = wrapped(plain(&mut doc, 40.0), -4.25, true);
let c = wrapped(plain(&mut doc, 70.0), 6.0, false);
let d = plain(&mut doc, 100.0);
let mut e = named(wrapped(plain(&mut doc, 130.0), 3.0, true), "Badge");
let mask_art = plain(&mut doc, 130.0);
e.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false)));
let members = vec![plain(&mut doc, 160.0), plain(&mut doc, 190.0)];
let f = wrapped(group(&mut doc, members, false), -2.0, false);
let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(220.0, 10.0, 260.0, 50.0)), Appearance::default());
let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(230.0, 20.0, 250.0, 40.0)), Appearance::default());
let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd });
ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into();
let g = wrapped(ring, 7.0, true);
let clip = wrapped(clipping(&mut doc, shapes::rectangle(Rect::new(280.0, 10.0, 320.0, 50.0))), 5.0, false);
let clipped = plain(&mut doc, 290.0);
let h = group(&mut doc, vec![clip, clipped], true);
for n in [a, b, c, d, e, f, g, h] {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
assert_eq!(doc.layers[0].children().unwrap()[2].extras().wrap, Some(vectorcraft_doc::TextWrap::default()));
let text = program(&doc);
for entries in
[wrap_entries("12.5", false), wrap_entries("-4.25", true), wrap_entries("6", false), wrap_entries("-2", false), wrap_entries("7", true)]
{
assert!(text.contains(&entries), "{entries}\n{text}");
}
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 7, "{text}");
assert!(!text.contains("AI11TextWrapPath"), "{text}");
let back = read_back(&doc);
same_wraps(&wraps(back.layers[0].children().unwrap()), &wraps(doc.layers[0].children().unwrap()));
let kept: Vec<_> = back.layers[0].children().unwrap().iter().map(|n| (n.extras().wrap, n.extras().mask.is_some())).collect();
let want: Vec<_> = doc.layers[0].children().unwrap().iter().map(|n| (n.extras().wrap, n.extras().mask.is_some())).collect();
assert_eq!(kept, want);
// An offset that isn't finite, and offsets past the range the reader keeps.
let mut doc = Document::new(200.0, 100.0);
let odd = wrapped(plain(&mut doc, 10.0), f64::NAN, true);
let far = wrapped(plain(&mut doc, 40.0), 1e300, false);
let far_in = wrapped(plain(&mut doc, 70.0), -1000.5, false);
let layer = doc.layers[0].id;
for n in [odd, far, far_in] {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
let text = program(&doc);
for entries in [wrap_entries("6", true), wrap_entries("1000", false), wrap_entries("-1000", false)] {
assert!(text.contains(&entries), "{entries}\n{text}");
}
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 6.0, true), (None, 1000.0, false), (None, -1000.0, false)]);
}
/// The art drawn for an object (a blend's steps, a stained symbol instance's art) is written
/// without the text wrap options of the objects it is made from, which wrap no type; the object
/// keeps its own. A symbol's art and a live instance keep theirs.
#[test]
fn drawn_art_keeps_only_its_objects_text_wrap() {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let keys = vec![
Arc::new(wrapped(square(&mut doc, Rect::new(10.0, 10.0, 12.0, 12.0), Color::gray(0.5)), 2.0, true)),
Arc::new(wrapped(square(&mut doc, Rect::new(30.0, 10.0, 32.0, 12.0), Color::gray(0.5)), 2.0, true)),
];
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), ..Default::default() };
let blend = wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 8.0, false);
let art = wrapped(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), 4.0, true);
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
let mut stained = instance(&mut doc, "Leaf", Affine::translate((50.0, 10.0)));
stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
let live = wrapped(instance(&mut doc, "Leaf", Affine::translate((80.0, 10.0))), -3.0, false);
for n in [blend, stained, live] {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
let back = read_back(&doc);
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(None, 8.0, false), (None, -3.0, false)]);
assert!(matches!(back.layers[0].children().unwrap()[2].kind, NodeKind::SymbolInstance { .. }));
same_wraps(&wraps(&[back.symbols[0].art.clone()]), &[(None, 4.0, true)]);
// An object kept with an art style: its options go with the object, not its drawn look.
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let shadow = fx("stylize.dropShadow", serde_json::json!({"x": 6.0, "y": 4.0, "blur": 8.0}));
let shadowed = styled_rect(&mut doc, "Shadowed", Rect::new(10.0, 10.0, 60.0, 50.0), solid(Color::gray(0.5)), Paint::None, vec![shadow]);
doc.insert(Some(layer), usize::MAX, wrapped(shadowed, 9.0, true)).unwrap();
let text = program(&doc);
assert!(text.contains("(Anon 1) XW") && text.matches("(AI11TextWrapOffset)").count() == 1, "{text}");
let back = read_back(&doc);
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(Some("Shadowed".into()), 9.0, true)]);
}
/// On a large canvas the offsets are written at the art's scale (1/10) and read back at their size,
/// an instance written as its art keeps its own options, and a symbol's art, defined at its own
/// size, keeps its offset as it is.
#[test]
fn text_wrap_offsets_on_a_large_canvas_come_back_at_their_size() {
let mut doc = Document::new(20_000.0, 20_000.0);
let layer = doc.layers[0].id;
let a = wrapped(square(&mut doc, Rect::new(1000.0, 1000.0, 1200.0, 1200.0), Color::gray(0.5)), -12.34, true);
let b = wrapped(square(&mut doc, Rect::new(1400.0, 1000.0, 1600.0, 1200.0), Color::gray(0.5)), 250.0, false);
let art = wrapped(square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), LEAF), 4.0, true);
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
let one = wrapped(instance(&mut doc, "Leaf", Affine::translate((2000.0, 1000.0))), -3.0, false);
for n in [a, b, one] {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
let text = program(&doc);
for entries in [wrap_entries("-1.234", true), wrap_entries("25", false), wrap_entries("-0.3", false), wrap_entries("4", true)] {
assert!(text.contains(&entries), "{entries}\n{text}");
}
let want = [(None, -12.34, true), (None, 250.0, false), (None, -3.0, false)];
let symbol = [(None, 4.0, true)];
// From the editing data alone.
let back = read_back(&doc);
same_wraps(&wraps(back.layers[0].children().unwrap()), &want);
same_wraps(&wraps(&[back.symbols[0].art.clone()]), &symbol);
// Beside a page of the artboard's size in points.
let (p, _) = private_data(&doc, &opts()).unwrap();
let (read, notes, layers) = crate::layered_ai(&p.data, Document::new(20_000.0, 20_000.0), vec![], false, true, 1.389);
assert!(layers, "{notes:?}");
same_wraps(&wraps(read.layers[0].children().unwrap()), &want);
same_wraps(&wraps(&[read.symbols[0].art.clone()]), &symbol);
}
/// Type and envelopes keep their own text wrap options: point type, each frame of threaded area
/// type (one with options, one without, in either order) and an envelope kept live.
#[test]
fn text_wrap_options_of_type_and_envelopes_are_read_back() {
use vectorcraft_doc::{TextKind, TextObject, TextRun};
for first_wraps in [true, false] {
let mut doc = Document::new(300.0, 100.0);
let layer = doc.layers[0].id;
let st = style(10.0, Color::BLACK);
let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone());
first.runs = vec![TextRun::new("One two three ", st.clone())];
first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) };
first.xf = Affine::IDENTITY;
let mut second = first.clone();
second.runs = vec![TextRun::new("four five", st.clone())];
second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(110.0, 10.0, 190.0, 40.0)) };
let (mut first, mut second) = (named(text_node(&mut doc, first), "First"), named(text_node(&mut doc, second), "Second"));
let frame = if first_wraps { &mut first } else { &mut second };
frame.extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset: 3.5, invert: true });
doc.text_threads.push(vec![first.id, second.id]);
let label = TextObject::point(vectorcraft_geom::Point::new(210.0, 30.0), "Label", st);
let label = wrapped(named(text_node(&mut doc, label), "Label"), -1.5, false);
for n in [first, second, label] {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
let back = read_back(&doc);
assert_eq!(back.text_threads.len(), 1, "the frames stay type");
let frame = if first_wraps { "First" } else { "Second" };
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(Some(frame.into()), 3.5, true), (Some("Label".into()), -1.5, false)]);
}
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let kinds = live_envelope_kinds();
let (_, arc) = kinds.iter().find(|(n, _)| *n == "arc").unwrap();
let bent = wrapped(envelope_node(&mut doc, arc.clone(), 50.0, false, vectorcraft_doc::live::EnvelopeOptions::NEW), 2.5, true);
doc.insert(Some(layer), usize::MAX, bent).unwrap();
let back = read_back(&doc);
let top = back.layers[0].children().unwrap();
assert!(matches!(top[0].kind, NodeKind::Envelope { .. }));
same_wraps(&wraps(top), &[(Some("Bent".into()), 2.5, true)]);
}
/// A clipping path inside art cut to a clipping object is written as its fills and its strokes,
/// two objects: its text wrap options are written once, whether it has both or only strokes.
#[test]
fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() {
for fill in [solid(Color::gray(0.5)), Paint::None] {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)));
cutter.appearance = Appearance::basic(fill, solid(Color::BLACK), 2.0).into();
let cutter = wrapped(cutter, 5.0, true);
let member = square(&mut doc, Rect::new(30.0, 30.0, 120.0, 60.0), Color::rgb(1.0, 0.0, 0.0));
let inner = group(&mut doc, vec![cutter, member], true);
let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9));
let frame = group(&mut doc, vec![frame], false);
let outer = group(&mut doc, vec![frame, inner], true);
doc.insert(Some(layer), usize::MAX, outer).unwrap();
let text = program(&doc);
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{text}");
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]);
}
}
+48 -6
View File
@@ -7,7 +7,7 @@ use std::sync::Arc;
use vectorcraft_color::cms::Cms;
use vectorcraft_color::swatch::{REGISTRATION, Swatch};
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer, TextWrap};
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath};
use vectorcraft_pathops::BoolOp;
@@ -56,6 +56,7 @@ pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose cli
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
pub(super) const ITEM_TRANSPARENCY: &str =
"the opacity and blending modes of single fills and strokes are left out of the editing data for other apps";
@@ -263,6 +264,10 @@ pub(super) struct Writer<'a> {
/// An object's drawn look is being written: no object in it is written with a style, and its
/// effects are the style's.
in_look: bool,
/// How many parts of art drawn for an object (a live object's art, a symbol instance's art, a
/// brushed stroke's pieces) the art being written is in. Text wrap options are written only
/// outside them, since only the document's own objects wrap type.
drawn: u32,
/// The brushes written ([`brushes`]).
brush_set: brushes::Brushes,
/// Brushes may be written; false on a large canvas, where they are left out.
@@ -329,6 +334,7 @@ impl<'a> Writer<'a> {
styled: HashMap::new(),
styles: styles::Styles::default(),
in_look: false,
drawn: 0,
brush_set: brushes::Brushes::default(),
brushes_live: true,
deform: false,
@@ -617,6 +623,9 @@ impl<'a> Writer<'a> {
if self.in_symbol {
self.wrote_fixed |= symbols::redrawn(n);
}
if n.extras().graph.is_some() && !self.in_look {
self.warn(GRAPHS);
}
// On the layers or in an opacity mask's art, outside art cut to a clipping object: with its
// art style, when it has one.
if !self.in_look
@@ -700,7 +709,9 @@ impl<'a> Writer<'a> {
art.locked = false;
art.name = None;
self.nest += 1;
self.drawn += 1;
self.node(&art);
self.drawn -= 1;
self.nest -= 1;
} else {
self.warn(SYMBOL_LIMIT);
@@ -744,9 +755,11 @@ impl<'a> Writer<'a> {
if self.nest < MAX_NEST {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
self.nest += 1;
self.drawn += 1;
for c in g.children().map(Vec::as_slice).unwrap_or_default() {
self.node(c);
}
self.drawn -= 1;
self.nest -= 1;
}
self.end_group("U", xy);
@@ -754,10 +767,12 @@ impl<'a> Writer<'a> {
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
/// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an
/// empty `AIArtName`), has an opacity mask (`AI9_Mask`, see [`Self::mask`]), or is a symbol's
/// art (its symbol's entries first, see [`Self::define_symbol`]).
/// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask
/// (`AI9_Mask`, see [`Self::mask`]), or is a symbol's art (its symbol's entries first, see
/// [`Self::define_symbol`]).
fn dictionary(&mut self, n: &Node) {
let name = n.name.as_deref().filter(|s| !s.is_empty());
let wrap = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look);
let placed = std::mem::take(&mut self.placed);
let typed = std::mem::take(&mut self.typed);
let bound = self.bound_variables(n, placed, typed);
@@ -771,7 +786,7 @@ impl<'a> Writer<'a> {
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
_ => None,
};
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() {
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() {
return;
}
let start = self.body.len();
@@ -792,17 +807,32 @@ impl<'a> Writer<'a> {
self.bound.push((n.id, id, bound));
}
}
if let Some(w) = wrap {
self.text_wrap(w);
}
// A mask whose art doesn't fit is left out, and with nothing else in it the dictionary too.
if let Some(m) = mask
&& !self.mask(m)
&& !has_id
&& !has_entries
&& wrap.is_none()
{
return self.body.truncate(start);
}
self.body.push_str("%_;\n%_\n");
}
/// Text wrap options, as entries of their object's dictionary: the offset in art space's points
/// (`AI11TextWrapOffset`, `/Real`; a value that isn't finite is written as the default 6 pt,
/// and one past the -1000 to 1000 pt the reader keeps as the nearer end of that range) and
/// Invert Wrap (`AI11TextWrapInvert`, `/Bool`, 1 or 0), as the reader reads them back.
fn text_wrap(&mut self, w: TextWrap) {
let offset = if w.offset.is_finite() { w.offset.clamp(-1000.0, 1000.0) } else { TextWrap::default().offset };
self.body.push_str("%_");
ps::push_num(&mut self.body, offset);
let _ = writeln!(self.body, " /Real (AI11TextWrapOffset) ,\n%_{} /Bool (AI11TextWrapInvert) ,", u8::from(w.invert));
}
/// An `/ArtDictionary` whose `AI10_ArtUID` is `name` as an XML id.
fn xml_id(&mut self, name: &str) {
let id = self.take_id(name);
@@ -1006,12 +1036,18 @@ impl<'a> Writer<'a> {
}
/// A container's members, the first one's outline cutting the others: its fills painted
/// behind them (cut to the region outside too), its strokes over them, not cut by it.
/// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text
/// wrap options are written once: with its fills, or without fills with its strokes.
fn clip_contents(&mut self, children: &[Arc<Node>]) {
let Some((first, rest)) = children.split_first() else { return };
// Nothing to clip by hides the clipped art.
let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return };
let paint = first.clip_paint();
let mut paint = first.clip_paint();
if let (Some(_), Some(stroke)) = (&paint.fill, &mut paint.stroke)
&& stroke.extras().wrap.is_some()
{
stroke.extras_mut().wrap = None;
}
let outer = self.clip.clone();
let region = self.cut(&PathData::from_bezpath(&outline), rule);
self.clip = Some(region);
@@ -1101,9 +1137,11 @@ impl<'a> Writer<'a> {
return true;
}
self.nest += 1;
self.drawn += 1;
for piece in &art {
self.node(piece);
}
self.drawn -= 1;
if let Some((locked, hidden)) = state {
self.state(locked, hidden);
}
@@ -1148,9 +1186,11 @@ impl<'a> Writer<'a> {
let region = self.cut(path, rule);
self.clip = Some(region);
self.nest += 1;
self.drawn += 1;
for t in &tiles {
self.node(t);
}
self.drawn -= 1;
if let Some((locked, hidden)) = state {
self.state(locked, hidden);
}
@@ -1343,7 +1383,9 @@ impl<'a> Writer<'a> {
art_node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true);
(art_node.visible, art_node.locked, art_node.name) = (true, false, None);
self.nest += 1;
self.drawn += 1;
self.node(&art_node);
self.drawn -= 1;
self.nest -= 1;
}
}
+5 -3
View File
@@ -204,8 +204,10 @@ impl Writer<'_> {
if sym.dynamic || doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() {
self.warn(SYMBOL_OPTIONS);
}
// The art's effects are its own, not those of a drawn look that first places it.
// The art's effects are its own, not those of a drawn look that first places it, and its
// text wrap options are its own, not left out with the drawn art that first places it.
let in_look = std::mem::take(&mut self.in_look);
let drawn = std::mem::take(&mut self.drawn);
self.defining_symbols.push(name.to_string());
// The objects of this definition and of those it defines first.
let before = self.charges();
@@ -222,7 +224,7 @@ impl Writer<'_> {
self.defining_symbols.pop();
self.keep_since(before);
self.warn(SYMBOL_COUNT);
self.in_look = in_look;
(self.in_look, self.drawn) = (in_look, drawn);
return false;
}
// The group that holds the art is an object of the definition ([`Self::take_objects`]);
@@ -308,7 +310,7 @@ impl Writer<'_> {
(self.wrote_fixed, self.inner_scale),
) = saved;
self.doc = page_doc;
self.in_look = in_look;
(self.in_look, self.drawn) = (in_look, drawn);
let art = std::mem::replace(&mut self.body, art);
self.defining_symbols.pop();
if self.left_out_since(art_start) {
+143 -7
View File
@@ -3,8 +3,11 @@
//! type runs along, `TP`), the modal character and paragraph attributes
//! (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's letter and word spacing `TC TW`, hanging
//! punctuation `Tq`, hyphenation `Th` and tab stops `Xb Xe XB`, and §15.3.4's writing direction `TV`,
//! Roman character rotation `Tv`, Kumi blocks `Ty TY` and binding punctuation `Tg`), the paint
//! style, and the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Type set in rendering modes 4 to 7 is a mask (§5.7): the
//! Roman character rotation `Tv`, Kumi blocks `Ty TY` and binding punctuation `Tg`, and §22.6's
//! hyphenation language `XL`), the paint style, the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends
//! a paragraph), manual kerning pairs (`Tk`, overflow `TK`) and discretionary hyphens (`T+`, `T-`,
//! read as soft hyphens). The line breaking value `TG` and the Japanese layout rules `Xu` (`Tu`) are
//! not kept: a visible text object read while one is set gives a warning. Type set in rendering modes 4 to 7 is a mask (§5.7): the
//! text object clips the objects of its clipping group. Final-form operators (the
//! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the
//! encoding pairs of the current font's `TZ`, then by the file's `TE` encoding unless that `TZ`'s
@@ -59,6 +62,14 @@ const MASK_NOT_CLIPPED: &str = "type used as a mask in linked areas, wraparound
/// The warning when `TV` changes after a text object's first character: the object keeps the
/// direction of that character.
const DIRECTION_CHANGE_LEFT_OUT: &str = "type that changes writing direction inside a text object opens in the direction of its first character";
/// The warning when a visible text object is read while a line breaking value (`TG`) is set.
const LINE_BREAKING_LEFT_OUT: &str = "the Line Breaking setting of legacy type was left out";
/// The warning when a visible text object is read while Japanese layout rules (`Xu`, `Tu`) are set.
const JAPANESE_LAYOUT_LEFT_OUT: &str = "the Japanese layout rules of legacy type were left out";
/// The manual kerning range `text.setRangeStyle` takes, in 1/1000 em.
const KERNING_RANGE: (f64, f64) = (-1000.0, 10_000.0);
/// The soft hyphen a discretionary hyphen (`T+`, `T-`) is read as.
const SOFT_HYPHEN: char = '\u{ad}';
/// A text path (`Tp` … `TP`).
#[derive(Debug, Default)]
@@ -124,6 +135,9 @@ pub(super) struct LegacyText {
vertical: bool,
/// A later character was set in the other direction.
direction_changed: bool,
/// A manual kerning value (`Tk`, `TK`) read at the start of a line, in 1/1000 em: the space
/// before the next character, which starts the line.
kern_before: Option<f64>,
/// The state when it began (lock, visibility), and whether it began on a `%_` line.
gs: GState,
hidden: bool,
@@ -148,6 +162,40 @@ impl LegacyText {
}
}
/// Add `text` in `style` to `runs`: to the last run when it has that style, else as a new run.
fn push_run(runs: &mut Vec<TextRun>, text: String, style: CharStyle) {
if text.is_empty() {
return;
}
match runs.last_mut() {
Some(last) if last.inline.is_none() && last.style == style => last.text.push_str(&text),
_ => runs.push(TextRun::new(text, style)),
}
}
/// Give the last character of `runs` the manual kerning `kerning` (None: automatic), in a run of
/// its own unless its run has one character, which joins the run before it when their styles
/// match. False when there is no character or the last one ends a paragraph: the kerning is at
/// the start of a line.
fn set_last_kerning(runs: &mut Vec<TextRun>, kerning: Option<f64>) -> bool {
let Some(last) = runs.last_mut().filter(|r| r.inline.is_none()) else { return false };
let Some(c) = last.text.chars().next_back().filter(|&c| c != '\n') else { return false };
if last.style.kerning == kerning {
return true;
}
if last.text.len() > c.len_utf8() {
last.text.pop();
let style = CharStyle { kerning, ..last.style.clone() };
runs.push(TextRun::new(c.to_string(), style));
return true;
}
last.style.kerning = kerning;
if let Some(one) = runs.pop() {
push_run(runs, one.text, one.style);
}
true
}
/// Are `a` and `b` the same, leaving their tab stops out?
fn same_but_tabs(a: &mut ParaStyle, b: &mut ParaStyle) -> bool {
let (a_tabs, b_tabs) = (std::mem::take(&mut a.tabs), std::mem::take(&mut b.tabs));
@@ -203,6 +251,10 @@ pub(super) struct TypeState {
vertical: bool,
/// `TY`: a Kumi block recorded for later use, which horizontal type keeps as its mark.
kumi_recorded: bool,
/// A line breaking value (`TG`) was read: VectorCraft has no setting for it.
line_breaking: bool,
/// Japanese layout rules (`Xu`, `Tu`) were read: VectorCraft has no setting for them.
japanese_layout: bool,
/// The encoding strings are in, by code (`TE`); None where it says nothing.
encoding: Vec<Option<char>>,
/// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`, or `TZ`'s).
@@ -232,6 +284,8 @@ impl Default for TypeState {
render: 0,
vertical: false,
kumi_recorded: false,
line_breaking: false,
japanese_layout: false,
encoding: vec![None; 256],
fonts: vec![],
font_encodings: vec![],
@@ -684,6 +738,23 @@ impl Reader<'_> {
st.tabs_version = st.tabs_version.wrapping_add(1);
}
}
// `languageID XL` (§22.6), the hyphenation language: 0 U.S. English (the default
// language, none), then U.K. English, French, German, Spanish, Dutch, Italian, Swedish,
// Norwegian, Finnish, Danish and Hungarian, as the Character panel's language tags.
"XL" => {
const TAGS: [&str; 11] = ["en-GB", "fr", "de", "es", "nl", "it", "sv", "nb", "fi", "da", "hu"];
match n0 {
Some(0.0) => st.style.language = None,
Some(id) if id.fract() == 0.0 && (1.0..=11.0).contains(&id) => {
st.style.language = TAGS.get(id as usize - 1).map(|t| t.to_string());
}
_ => {}
}
}
// `linebreak TG` and `prop cjkLayout cjkRoman cjkCjk Xu` (`Tu` the same, §22.6). Either
// one is set only when its operands are numbers.
"TG" => st.line_breaking |= n0.is_some(),
"Xu" | "Tu" => st.japanese_layout |= nums::<4>(vals).is_some(),
_ => {}
}
}
@@ -691,14 +762,59 @@ impl Reader<'_> {
/// `(…) Tx` (`Tj`, overflow `TX`): characters in the current style and paint.
pub(super) fn text_body(&mut self, w: &str, vals: &[V]) {
let Some(bytes) = vals.iter().rev().find_map(|v| if let V::Str(s) = v { Some(s.clone()) } else { None }) else { return };
if self.text.is_none() {
return;
}
let decoded = self.type_state.decode(&bytes);
self.add_chars(w == "TX", decoded);
}
/// `autoKern kernValue Tk` (`TK` in overflow text): the space between the character before it
/// and the character after it. With `autoKern` 0 the pair takes `kernValue` in 1/1000 em as
/// manual kerning, kept to the range `text.setRangeStyle` takes; with 1 the pair takes the
/// automatic kerning. The value is the kerning after the character before it; at the start of
/// a line it is the space before the character after it. Operands that are missing, are not
/// numbers, or a flag other than 0 and 1 leave the type as it was, and so does a `Tk` outside a
/// text object.
pub(super) fn text_kern(&mut self, vals: &[V]) {
let Some([auto, value]) = nums::<2>(vals) else { return };
let Some(auto) = flag(auto) else { return };
let Some(t) = self.text.as_mut() else { return };
let kerning = (!auto).then(|| value.clamp(KERNING_RANGE.0, KERNING_RANGE.1));
let line_start = t.pending_break.is_some() || !set_last_kerning(&mut t.runs, kerning);
if line_start {
t.kern_before = kerning;
}
}
/// `T+` (a discretionary hyphen that doesn't print) or `T-` (`printed`: the character before it
/// is a discretionary hyphen that prints, §15.4.10.1): a soft hyphen, which shows as a hyphen
/// only where a line breaks at it. A printed hyphen character (`-` or U+2010) before `T-`
/// becomes the soft hyphen; else one is added.
pub(super) fn discretionary_hyphen(&mut self, printed: bool) {
let Some(t) = self.text.as_mut() else { return };
if printed
&& t.pending_break.is_none()
&& let Some(last) = t.runs.last_mut()
&& last.inline.is_none()
&& last.text.ends_with(['-', '\u{2010}'])
{
last.text.pop();
last.text.push(SOFT_HYPHEN);
return;
}
self.add_chars(false, SOFT_HYPHEN.to_string());
}
/// Characters in the current style and paint (`overflow`: read by `TX`).
fn add_chars(&mut self, overflow: bool, decoded: String) {
let st = &mut self.type_state;
let Some(t) = self.text.as_mut() else { return };
let decoded = st.decode(&bytes);
if decoded.is_empty() {
return;
}
// Overflow text ending the story with a paragraph break (`(\r) TX`) adds no paragraph.
if w == "TX" && decoded == "\n" {
if overflow && decoded == "\n" {
if t.pending_break.is_none() {
let para = (!t.para_taken).then(|| (st.para.clone(), st.tabs_version));
t.pending_break = Some(PendingBreak { vertical: st.vertical, para });
@@ -744,6 +860,8 @@ impl Reader<'_> {
text.push('\n');
t.para_taken = false;
}
// Where the characters start in `text`, after a break read before them.
let at = text.len();
for c in decoded.chars() {
if c != '\n' && !t.para_taken {
t.begin_para(&mut st.para, st.tabs_version);
@@ -757,10 +875,19 @@ impl Reader<'_> {
t.para_taken = false;
}
}
match t.runs.last_mut() {
Some(last) if last.style == style => last.text.push_str(&text),
_ => t.runs.push(TextRun::new(text, style)),
// Kerning read at the start of the line is the space before its first character; a
// paragraph break there leaves no character for it.
let first = decoded.chars().next().filter(|&c| c != '\n');
if let (Some(k), Some(c)) = (t.kern_before.take(), first) {
let end = at + c.len_utf8();
let (rest, after) = (text.split_off(end), CharStyle { kerning_before: k, ..style.clone() });
let own = text.split_off(at);
push_run(&mut t.runs, text, style.clone());
push_run(&mut t.runs, own, after);
push_run(&mut t.runs, rest, style);
return;
}
push_run(&mut t.runs, text, style);
}
/// `TO`: the text object ends. Area type with several linked areas becomes one frame for each
@@ -792,6 +919,15 @@ impl Reader<'_> {
if t.direction_changed {
self.warn(DIRECTION_CHANGE_LEFT_OUT);
}
// A copy on `%_` lines is not the type the document shows.
if !(t.hidden || hidden) {
if self.type_state.line_breaking {
self.warn(LINE_BREAKING_LEFT_OUT);
}
if self.type_state.japanese_layout {
self.warn(JAPANESE_LAYOUT_LEFT_OUT);
}
}
let mut paras = std::mem::take(&mut t.paras);
if paras.is_empty() {
paras.push(ParaRun { style: self.type_state.para.clone(), count: 1, tabs_version: 0 });
+6 -3
View File
@@ -78,7 +78,8 @@
//!
//! - Graphs (version 7 specification §17): `%_Gs`, the graph's data and settings on `%_` lines,
//! its drawn art as ordinary groups, paths and type (each object followed by `%_… Go`), `%_GS`.
//! The drawn art is read; the data and settings are left out, with a note.
//! The drawn art is read as it is. Its group keeps the data and settings when they read whole
//! ([`graph`]); otherwise they are left out, with a note.
//!
//! - Swatches: the palette (`%AI5_BeginPalette`), read by [`super::palette`], replaces the
//! default swatches.
@@ -133,6 +134,7 @@ mod art;
mod containers;
mod directives;
mod document;
mod graph;
mod masks;
mod on_path;
mod ops;
@@ -146,12 +148,13 @@ pub use document::{
symbols, variables,
};
pub(crate) use document::{slot_frame, slot_of};
use graph::Graph;
pub(crate) use ops::{read_art_style, read_style_list, style_moves_with};
#[cfg(test)]
pub(crate) use raster::with_image_limits;
pub(crate) use types::MAX_NODES;
pub use types::PlacedPage;
use types::{BLEND_BUDGET, BrushArtColors, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
use types::{BLEND_BUDGET, BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
#[cfg(test)]
pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED};
pub(super) use types::{blend_mode, blend_name};
@@ -670,7 +673,7 @@ struct Reader<'a> {
brushes_kept: BrushesKept,
/// Brush objects that weren't read.
brushes_unread: usize,
/// The graph being read (see [`Reader::graph_record`]).
/// The graph being read (see [`graph`]).
graph: Option<Graph>,
/// The multi-layer mask being read (`Mb` … `MB`), which goes on past a layer's end.
multi_mask: Option<masks::MultiMask>,
+3 -1
View File
@@ -1165,7 +1165,9 @@ impl<'a> Reader<'a> {
}
pub(super) fn finish(mut self) -> Result<Structure, String> {
if self.graph.take().is_some() {
if self.graph.is_some() {
self.graph_plain();
self.graph = None;
self.warn(super::types::GRAPH_UNENDED);
}
// Envelopes whose plugin never closed them keep their drawn art.
+681
View File
@@ -0,0 +1,681 @@
//! A graph's records (version 7 specification §17 and appendix A) and the live graph they give.
//!
//! A graph is `%_Gs`, its functional records on `%_` lines (`Gb`, `Gy`, `Gd`, any `Gj`, three
//! `Ga` … `GA` axes, any `Gw`, `Gz`, `Gc` cells and `GC`), any `version Gt` … `GT` customizations, its
//! drawn art in one group (objects followed by `%_… Go`), then `%_GS`. The drawn art is always
//! read as it is. The group also keeps the graph's data and settings ([`GraphSpec`]) when every
//! record has the shape and values appendix A gives and the model holds each setting, the table
//! has data, the art draws the plot's left and bottom edges, and each series' group is tagged, is
//! one of the graph's own groups and paints its paths with one fill and one stroke, which the
//! graph keeps as the series' paint.
//! Any other graph stays plain art, with a note.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use kurbo::{PathSeg, Point};
use vectorcraft_doc::{Appearance, GraphKind, GraphSpec, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, SeriesPaint, TickLength};
use super::types::{GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, Kind};
use super::{Affine, AppearanceItem, BlendMode, Node, NodeId, NodeKind, Paint, Reader, Rect, V, obj};
/// Most cells of a graph's table, its label row and column included.
const MAX_CELLS: usize = 2_600_000;
/// Longest cell string (appendix A, `Gc`).
const MAX_CELL_TEXT: usize = 255;
/// Most characters of an axis label's text before or after its numbers (appendix A, `Ga`, `GA`).
const MAX_AFFIX: usize = 9;
/// Most tick marks per division a graph draws.
const MAX_TICK_MARKS: usize = 20;
/// Most divisions of a value axis with set values.
const MAX_DIVISIONS: f64 = 100.0;
/// How far an axis line may be from the plot's edge, in points.
const EDGE: f64 = 0.01;
/// The axes in the order the records give them: bottom, left, right.
const AXES: [i64; 3] = [1, 2, 4];
/// The `Go` targets appendix A lists.
const TARGETS: [i64; 11] = [1, 2, 4, 5, 6, 8, 9, 10, 15, 20, 22];
/// The version of a graph's customizations (appendix A, `Gt`).
const CUSTOM_VERSION: i64 = 2;
/// `Go`'s target for one series, including its legend.
const SERIES: i64 = 2;
/// A graph being read (`%_Gs` … `%_GS`).
#[derive(Debug)]
pub(super) struct Graph {
/// Between `Gt` and `GT`, where the graph's settings may use paint and type operators on `%_`
/// lines too.
pub(super) settings: bool,
/// How many frames were open at its `Gs`: a layer that ends with fewer ends the graph.
pub(super) frames: usize,
/// How many objects the innermost frame held at `Gs`: the drawn art is the one after them.
siblings: usize,
/// The records read so far, while they can still give a live graph.
live: Option<Box<Records>>,
}
/// Where the records are, in the order appendix A gives.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum Stage {
#[default]
Bounds,
Style,
Dialog,
/// Before the `Ga` of axis `n`.
Axis(usize),
/// Before the `GA` of axis `n`.
AxisEnd(usize),
Widths,
Cells,
/// After `GC`: customizations, then the drawn art.
Done,
/// Between `Gt` and `GT`.
Custom,
}
/// One axis: `whichAxis beforeString Ga` and `useManualValues tickMarkType minimumValue maximumValue
/// betweenValue smallTicksPerValue drawMarksBetweenLabels afterString GA`.
#[derive(Debug, Default)]
struct Axis {
before: Vec<u8>,
manual: bool,
tick: TickLength,
min: f64,
max: f64,
between: f64,
small: usize,
between_labels: bool,
after: Vec<u8>,
}
/// A cell of the table (`Gc`).
#[derive(Debug)]
enum Cell {
Num(f64),
Text(Vec<u8>),
}
/// The records of a graph read so far.
#[derive(Debug, Default)]
struct Records {
stage: Stage,
spec: GraphSpec,
axes: [Axis; 3],
/// `Gw`: the first column and how many widths.
widths: Vec<(usize, usize)>,
/// `Gz`: rows, columns, first data row and first data column.
size: Option<[usize; 4]>,
cells: Vec<Cell>,
/// The groups `Go` tags as one series, and the column each names.
series: Vec<(NodeId, usize)>,
}
/// A whole number.
fn int(v: &V) -> Option<i64> {
v.num().filter(|x| x.is_finite() && x.fract() == 0.0 && x.abs() < 1e15).map(|x| x as i64)
}
/// 0 or 1.
fn flag(v: &V) -> Option<bool> {
match int(v)? {
0 => Some(false),
1 => Some(true),
_ => None,
}
}
fn finite(v: &V) -> Option<f64> {
v.num().filter(|x| x.is_finite())
}
/// A count from 0 to `max`.
fn count(v: &V, max: usize) -> Option<usize> {
usize::try_from(int(v)?).ok().filter(|n| *n <= max)
}
/// `tickMarkType`: 13 none, 14 short, 15 the length of the plot.
fn tick(v: &V) -> Option<TickLength> {
match int(v)? {
13 => Some(TickLength::None),
14 => Some(TickLength::Short),
15 => Some(TickLength::Full),
_ => None,
}
}
/// `graphType`: 5 grouped column, 6 stacked column, 7 line, 10 area. Pie (8) and scatter (9) graphs
/// keep settings the records don't give the model, and other values are not graph types.
fn kind(v: &V) -> Option<GraphKind> {
match int(v)? {
5 => Some(GraphKind::Column),
6 => Some(GraphKind::StackedColumn),
7 => Some(GraphKind::Line),
10 => Some(GraphKind::Area),
_ => None,
}
}
/// A percentage of the available width, 1 to 1000.
fn percent(v: &V) -> Option<f64> {
finite(v).filter(|p| (1.0..=1000.0).contains(p))
}
/// The tick count and values of an axis: with set values (`useManualValues` 1), the divisions
/// between its lowest and highest value, a whole number of `betweenValue` steps from the lowest up.
fn values(a: &Axis) -> Option<(usize, Option<f64>, Option<f64>)> {
if !a.manual {
return Some((0, None, None));
}
let n = (a.max - a.min) / a.between;
let whole = n.round();
let exact = (n - whole).abs() <= 1e-6 * whole.max(1.0);
(a.between > 0.0 && a.max > a.min && exact && (1.0..=MAX_DIVISIONS).contains(&whole)).then_some((whole as usize, Some(a.min), Some(a.max)))
}
impl Records {
/// Take the record `w` with its operands `vals`; `None` when its shape, values or place aren't
/// those appendix A gives, or the model doesn't hold a value it sets. `to_doc` takes art space
/// to the document.
fn step(&mut self, w: &str, vals: &[V], to_doc: Affine) -> Option<()> {
match (w, self.stage) {
("Gb", Stage::Bounds) => {
let [l, t, r, b] = vals else { return None };
let [l, t, r, b] = [finite(l)?, finite(t)?, finite(r)?, finite(b)?];
let plot = to_doc.transform_rect_bbox(Rect::new(l, b, r, t));
let sound = r > l && t > b && plot.width() > 0.0 && plot.height() > 0.0 && plot.width().is_finite() && plot.height().is_finite();
sound.then_some(())?;
self.spec.rect = plot;
self.stage = Stage::Style;
}
("Gy", Stage::Style) => {
self.style(vals)?;
self.stage = Stage::Dialog;
}
("Gd", Stage::Dialog) => {
let [col_width, precision, series_order, both_axes, bar, group, edge] = vals else { return None };
count(col_width, 20).filter(|w| *w >= 3)?;
count(precision, 10)?;
// `useBothAxis` copies one axis' values to the other, which the model doesn't do.
(!flag(both_axes)?).then_some(())?;
self.spec.first_column_in_front = flag(series_order)?;
self.spec.column_width = percent(bar)?;
self.spec.cluster_width = percent(group)?;
self.spec.edge_to_edge = flag(edge)?;
self.stage = Stage::Axis(0);
}
("Ga", Stage::Axis(n)) if n < AXES.len() => {
let [axis, V::Str(before)] = vals else { return None };
(int(axis)? == *AXES.get(n)?).then_some(())?;
self.axes.get_mut(n)?.before = before.clone();
self.stage = Stage::AxisEnd(n);
}
("GA", Stage::AxisEnd(n)) => {
let [manual, ticks, min, max, between, small, between_labels, V::Str(after)] = vals else { return None };
let a = self.axes.get_mut(n)?;
(a.manual, a.tick) = (flag(manual)?, tick(ticks)?);
(a.min, a.max, a.between) = (finite(min)?, finite(max)?, finite(between)?);
a.small = count(small, 1000)?;
a.between_labels = flag(between_labels)?;
a.after = after.clone();
self.stage = Stage::Axis(n + 1);
}
("Gw", Stage::Axis(3) | Stage::Widths) => {
// `col width1 … widthX numParams Gw`: numParams counts `col` and the 1 to 14 widths.
let (params, rest) = vals.split_last()?;
let params = count(params, 15).filter(|p| *p >= 2 && *p == rest.len())?;
let (col, widths) = rest.split_first()?;
let col = count(col, MAX_CELLS)?;
widths.iter().all(|w| int(w).is_some_and(|w| w == -1 || (3..=20).contains(&w))).then_some(())?;
self.widths.push((col, params - 1));
self.stage = Stage::Widths;
}
("Gz", Stage::Axis(3) | Stage::Widths) => {
let [rows, cols, first_row, first_col] = vals else { return None };
let (rows, cols) = (count(rows, MAX_CELLS)?, count(cols, MAX_CELLS)?);
let (first_row, first_col) = (usize::from(flag(first_row)?), usize::from(flag(first_col)?));
rows.checked_sub(first_row).filter(|c| (1..=MAX_GRAPH_CATEGORIES).contains(c))?;
cols.checked_sub(first_col).filter(|s| (1..=MAX_GRAPH_SERIES).contains(s))?;
rows.checked_mul(cols).filter(|n| *n <= MAX_CELLS)?;
self.widths.iter().all(|(col, n)| col.checked_add(*n).is_some_and(|end| end <= cols)).then_some(())?;
self.size = Some([rows, cols, first_row, first_col]);
self.stage = Stage::Cells;
}
("Gc", Stage::Cells) => {
// One to fifteen values, at most one of them a string.
let strings = vals.iter().filter(|v| matches!(v, V::Str(_))).count();
((1..=15).contains(&vals.len()) && strings <= 1).then_some(())?;
let [rows, cols, ..] = self.size?;
(self.cells.len() + vals.len() <= rows * cols).then_some(())?;
for v in vals {
self.cells.push(match v {
V::Str(s) if s.len() <= MAX_CELL_TEXT => Cell::Text(s.clone()),
_ => Cell::Num(finite(v)?),
});
}
}
("GC", Stage::Cells) if vals.is_empty() => self.stage = Stage::Done,
// `version Gt`, of version 2. Customizations are edits made after the graph was built, which
// the model can't replay: only an empty list keeps the graph live.
("Gt", Stage::Done) => {
let [version] = vals else { return None };
(int(version)? == CUSTOM_VERSION).then_some(())?;
self.stage = Stage::Custom;
}
("GT", Stage::Custom) if vals.is_empty() => self.stage = Stage::Done,
_ => return None,
}
Some(())
}
/// `graphType shadow dataPointOrder pieLegendStyle drawMarks drawLines drawLinesAsShapes
/// drawLegendsAcrossTop lineShapeWidth whichAxis [piePercentage piePctDigits] Gy`.
fn style(&mut self, vals: &[V]) -> Option<()> {
let (base, pie) = match vals.len() {
10 => (vals, None),
12 => vals.split_at_checked(10).map(|(b, p)| (b, Some(p)))?,
_ => return None,
};
let [ty, shadow, order, legend, marks, lines, shapes, across, width, axis] = base else { return None };
self.spec.kind = kind(ty)?;
self.spec.drop_shadow = flag(shadow)?;
self.spec.first_row_in_front = flag(order)?;
// 14: legends as in bar and line graphs; 15 (in wedges) and 16 (none) are pie styles.
(int(legend)? == 14).then_some(())?;
self.spec.legend = true;
self.spec.mark_points = flag(marks)?;
self.spec.connect_points = flag(lines)?;
// Lines drawn as shapes have a width the model doesn't keep.
(!flag(shapes)?).then_some(())?;
self.spec.filled_lines = false;
self.spec.legend_across_top = flag(across)?;
finite(width).filter(|w| (0.0..=100.0).contains(w))?;
// 44: the series are measured against the left axis; 45 (right) isn't kept per series.
(int(axis)? == 44).then_some(())?;
if let Some([percentage, digits]) = pie {
// Pie percentages, which only pie graphs show; shown (1) isn't kept.
(!flag(percentage)?).then_some(())?;
int(digits).filter(|d| *d >= 0)?;
}
Some(())
}
/// The graph's data and settings, its strings read as names in `names`; `None` when the table
/// or an axis holds what the model can't.
fn finish(&self, names: &mut obj::Names) -> Option<GraphSpec> {
let [rows, cols, first_row, first_col] = self.size?;
let mut spec = self.spec.clone();
let text = |names: &mut obj::Names, b: &[u8], max: usize| {
let t = names.quiet(b);
(t.chars().count() <= max && !t.chars().any(char::is_control)).then(|| names.bytes(b))
};
// Axes: the bottom one is the category axis, the left one the value axis; the right one keeps
// its settings for when it is shown.
let [bottom, left, right] = &self.axes;
(bottom.before.is_empty() && bottom.after.is_empty() && !bottom.manual).then_some(())?;
(!left.between_labels && !right.between_labels).then_some(())?;
(spec.category_tick_length, spec.category_tick_marks) = (bottom.tick, bottom.small.max(1));
spec.ticks_between_labels = bottom.between_labels;
(spec.tick_length, spec.tick_marks) = (left.tick, left.small.max(1));
(spec.right_tick_length, spec.right_tick_marks) = (right.tick, right.small.max(1));
(spec.category_tick_marks <= MAX_TICK_MARKS && spec.tick_marks <= MAX_TICK_MARKS && spec.right_tick_marks <= MAX_TICK_MARKS).then_some(())?;
(spec.ticks, spec.axis_min, spec.axis_max) = values(left)?;
(spec.right_ticks, spec.right_axis_min, spec.right_axis_max) = values(right)?;
spec.prefix = text(names, &left.before, MAX_AFFIX)?;
spec.suffix = text(names, &left.after, MAX_AFFIX)?;
spec.right_prefix = text(names, &right.before, MAX_AFFIX)?;
spec.right_suffix = text(names, &right.after, MAX_AFFIX)?;
// The table, row by row; cells left out at its end are empty.
let cell = |r: usize, c: usize| self.cells.get(r * cols + c);
let label = |names: &mut obj::Names, r: usize, c: usize| match cell(r, c) {
None => Some(String::new()),
Some(Cell::Text(t)) => text(names, t, MAX_CELL_TEXT),
Some(Cell::Num(_)) => None,
};
// The corner of a table with both label row and label column holds nothing.
let corner_empty = match cell(0, 0) {
None => true,
Some(Cell::Text(t)) => t.is_empty(),
Some(Cell::Num(_)) => false,
};
if first_row == 1 && first_col == 1 && !corner_empty {
return None;
}
spec.series = if first_row == 1 { (first_col..cols).map(|c| label(names, 0, c)).collect::<Option<_>>()? } else { vec![] };
spec.categories = if first_col == 1 { (first_row..rows).map(|r| label(names, r, 0)).collect::<Option<_>>()? } else { vec![] };
let mut data = Vec::with_capacity(rows - first_row);
for r in first_row..rows {
let row = (first_col..cols)
.map(|c| match cell(r, c) {
None => Some(None),
Some(Cell::Text(t)) if t.is_empty() => Some(None),
Some(Cell::Text(_)) => None,
Some(Cell::Num(v)) => Some(Some(*v)),
})
.collect::<Option<Vec<_>>>()?;
data.push(row);
}
data.iter().flatten().any(Option::is_some).then_some(())?;
spec.set_cells(data);
Some(spec)
}
/// The series index of each group `Go` tagged as one series, by id: every series once, its
/// columns counted in the table or among the series alike. `None` when the tags are missing,
/// repeated or out of range: the series' paint is read from its group.
fn series_tags(&self) -> Option<HashMap<NodeId, u32>> {
let [_, cols, _, first_col] = self.size?;
let n = cols - first_col;
let ids: HashSet<NodeId> = self.series.iter().map(|(id, _)| *id).collect();
(ids.len() == self.series.len() && self.series.len() == n).then_some(())?;
let indexes = |offset: usize| -> Option<HashMap<NodeId, u32>> {
let mut seen = HashSet::new();
let tags: HashMap<NodeId, u32> = self
.series
.iter()
.map(|(id, col)| {
let s = col.checked_sub(offset).filter(|s| *s < n && seen.insert(*s))?;
Some((*id, u32::try_from(s).ok()?))
})
.collect::<Option<_>>()?;
Some(tags)
};
// With a label column, the columns read as the table's or as the series' are told apart by the
// set they make; without one, they are the same.
match (indexes(0), indexes(first_col)) {
(Some(a), Some(b)) if a == b => Some(a),
(Some(a), None) | (None, Some(a)) => Some(a),
_ => None,
}
}
}
/// Whether `art` draws the plot `plot`'s left edge and its bottom edge (the document's y runs down)
/// as straight stroked lines: the value axis and the category axis, drawn on the plot's edges.
fn draws_axes(art: &Node, plot: Rect) -> bool {
let near = |a: Point, b: Point| (a - b).hypot() <= EDGE;
let on = |s: &PathSeg, a: Point, b: Point| match s {
PathSeg::Line(l) => (near(l.p0, a) && near(l.p1, b)) || (near(l.p0, b) && near(l.p1, a)),
_ => false,
};
let (top_left, bottom_left, bottom_right) = (Point::new(plot.x0, plot.y0), Point::new(plot.x0, plot.y1), Point::new(plot.x1, plot.y1));
let (mut left, mut bottom) = (false, false);
let mut stack = vec![art];
while let Some(n) = stack.pop() {
// Only shown objects draw the axes, and a path only with a stroke.
if !n.visible || n.opacity <= 0.0 || (left && bottom) {
continue;
}
let stroked = n.appearance.items.iter().any(|it| !it.is_fill() && it.visible() && it.opacity() > 0.0 && !it.paint().is_none());
if let NodeKind::Path { path, .. } = &n.kind
&& stroked
{
for s in path.to_bezpath().segments() {
left |= on(&s, top_left, bottom_left);
bottom |= on(&s, bottom_left, bottom_right);
}
}
stack.extend(n.children().into_iter().flatten().map(|c| &**c));
}
left && bottom
}
/// Give the groups among `n`'s children that `tags` holds their series index.
fn tag_series(n: &mut Node, tags: &HashMap<NodeId, u32>) {
for c in n.children_mut().into_iter().flatten() {
if let Some(i) = tags.get(&c.id) {
Arc::make_mut(c).extras_mut().series_index = Some(*i);
}
}
}
/// Whether every node `tags` holds is a group among `n`'s children: the graph draws its series
/// groups again as its own children.
fn tags_groups(n: &Node, tags: &HashMap<NodeId, u32>) -> bool {
let found = n.children().into_iter().flatten().filter(|c| tags.contains_key(&c.id) && matches!(c.kind, NodeKind::Group { .. })).count();
found == tags.len()
}
/// The paint of the shown fill (`fill`) or stroke of `p`, with a stroke's weight; `None` when it
/// has none. `Err` when it has more than one, or that fill or stroke has an opacity, a blend mode
/// or effects of its own, which a series' paint doesn't hold.
fn shown(p: &Node, fill: bool) -> Result<Option<(Paint, f64)>, ()> {
let mut items = p.appearance.items.iter().filter(|it| it.is_fill() == fill && it.visible());
let Some(item) = items.next() else { return Ok(None) };
if items.next().is_some() || item.opacity() != 1.0 || item.blend() != BlendMode::Normal || !item.effects().is_empty() {
return Err(());
}
if item.paint().is_none() {
return Ok(None);
}
let width = match item {
AppearanceItem::Stroke(s) => s.width,
AppearanceItem::Fill(_) => 0.0,
};
Ok(Some((item.paint().clone(), width)))
}
/// Whether `n` is shown, fully opaque, in Normal mode, not isolated and without an opacity mask:
/// the graph draws its series groups and their marks so.
fn as_drawn(n: &Node) -> bool {
n.visible && n.opacity == 1.0 && n.blend == BlendMode::Normal && !n.isolate && n.extras().mask.is_none()
}
/// Each series' fill and stroke, read from its group (`tags`), which holds paths only, one at
/// least: the paths with a fill share it, and every path has the same stroke or none. Only a line
/// graph (`line`) has paths without a fill: its lines. `None` when they differ, or the group, its
/// own appearance or a path is drawn otherwise than [`as_drawn`].
fn series_paints(art: &Node, tags: &HashMap<NodeId, u32>, line: bool) -> Option<Vec<SeriesPaint>> {
let mut paints = vec![SeriesPaint::default(); tags.len()];
for group in art.children().into_iter().flatten() {
let Some(slot) = tags.get(&group.id).and_then(|i| paints.get_mut(usize::try_from(*i).ok()?)) else { continue };
(as_drawn(group) && *group.appearance == Appearance::default()).then_some(())?;
let paths: Vec<&Arc<Node>> = group.children().into_iter().flatten().collect();
(!paths.is_empty() && paths.iter().all(|p| matches!(p.kind, NodeKind::Path { .. }))).then_some(())?;
let (mut fills, mut strokes) = (vec![], vec![]);
for p in &paths {
as_drawn(p).then_some(())?;
fills.extend(shown(p, true).ok()?);
strokes.push(shown(p, false).ok()?);
}
let fill = fills.first().map(|(paint, _)| paint.clone());
fills.iter().all(|(paint, _)| Some(paint) == fill.as_ref()).then_some(())?;
(line || fills.len() == paths.len()).then_some(())?;
let stroke = strokes.first().cloned().flatten();
strokes.iter().all(|s| *s == stroke).then_some(())?;
slot.fill = fill;
(slot.stroke, slot.stroke_width) = match stroke {
Some((paint, width)) => (Some(paint), Some(width)),
None => (Some(Paint::None), None),
};
}
Some(paints)
}
impl<'a> Reader<'a> {
/// A graph's records: `%_Gs` starts the graph on a layer, `GS` ends it, and its data and settings
/// (the operators in [`GRAPH_OPS`], and any operator on a `%_` line between `Gt` and `GT`) are
/// taken with their operands `vals`. Its drawn art, and anything else, is read as usual. `true`
/// when `w` was one of them. `ended`: whether a group and a mesh had just ended before `w`, which
/// a `Go` tag after them leaves so.
pub(super) fn graph_record(&mut self, w: &str, vals: &[V], hidden: bool, ended: (bool, bool)) -> bool {
let depth = self.frames.len();
let Some(g) = self.graph.as_mut() else {
// Outside a graph, its operators stay ones the reader doesn't know.
if w == "Gs" && hidden && !self.frames.is_empty() {
let siblings = self.frames.last().map_or(0, |f| f.children.len());
// A graph is live only where its art is in the document's space, in a layer or a group.
let placed = self.pattern.is_none()
&& self.symbol.is_none()
&& vals.is_empty()
&& matches!(self.frames.last().map(|f| &f.kind), Some(Kind::Layer(_) | Kind::Group | Kind::Clip));
self.graph = Some(Graph { settings: false, frames: depth, siblings, live: placed.then(Box::default) });
return true;
}
return false;
};
// The frame the graph started in closed: its art isn't where it was.
if depth < g.frames {
self.graph_plain();
}
let Some(g) = self.graph.as_mut() else { return false };
let stage = g.live.as_ref().map(|r| r.stage);
match w {
// A graph doesn't start inside another: the one being read goes on.
"Gs" => {
self.graph_plain();
self.warn(GRAPH_UNENDED);
}
"GS" => self.graph_end(vals.is_empty() && hidden),
"Gt" | "GT" => {
g.settings = w == "Gt";
self.graph_step(w, vals, hidden);
}
"Go" => {
self.graph_tag(vals, hidden);
(self.group_ended, self.mesh_ended) = ended;
}
_ if GRAPH_OPS.contains(&w) => self.graph_step(w, vals, hidden),
_ if hidden && g.settings => self.graph_plain(),
_ => {
// Before its table ends, a graph has only its records.
if !matches!(stage, None | Some(Stage::Done)) {
self.graph_plain();
}
return false;
}
}
true
}
/// The graph being read can't be live: its art stays plain, with a note.
pub(super) fn graph_plain(&mut self) {
if let Some(g) = self.graph.as_mut() {
g.live = None;
}
self.warn(GRAPH_PLAIN);
}
/// Take a functional record or customization on a `%_` line.
fn graph_step(&mut self, w: &str, vals: &[V], hidden: bool) {
if self.graph.as_ref().is_none_or(|g| g.live.is_none()) {
return;
}
let to_doc = if w == "Gb" { self.space() } else { Affine::IDENTITY };
let ok = hidden && self.graph.as_mut().and_then(|g| g.live.as_mut()).and_then(|r| r.step(w, vals, to_doc)).is_some();
if !ok {
self.graph_plain();
}
}
/// `target column row whichAxis Go` after an object of the drawn art: a group tagged as one
/// series is kept with the column it names.
fn graph_tag(&mut self, vals: &[V], hidden: bool) {
let depth = self.frames.len();
let last = self
.after_object
.then(|| self.frames.last().and_then(|f| f.children.last()))
.flatten()
.map(|n| (n.id, matches!(n.kind, NodeKind::Group { .. })));
let Some(g) = self.graph.as_mut() else { return };
let inside = depth > g.frames;
let Some(r) = g.live.as_mut() else { return };
let tag = match vals {
[target, column, row, axis] if hidden && r.stage == Stage::Done => {
let (row, axis) = (int(row), int(axis));
// A series is the whole column, measured on the left axis (2) or with no axis given (0):
// the model keeps no series on a row or on the right axis.
let whole_column = row == Some(0) && matches!(axis, Some(0 | 2));
int(target).filter(|t| TARGETS.contains(t) && row.is_some() && axis.is_some()).zip(int(column)).map(|(t, c)| (t, c, whole_column))
}
_ => None,
};
let ok = match (tag, last) {
(Some((SERIES, column, true)), Some((id, true))) if inside => usize::try_from(column).ok().map(|c| r.series.push((id, c))).is_some(),
(Some((SERIES, ..)), _) => false,
(Some(_), Some(_)) => true,
_ => false,
};
if !ok {
self.graph_plain();
}
}
/// `GS`: the graph ends. Its drawn art is the one object its frame gained, a group; it keeps the
/// graph's data and settings when they read whole (`whole`) and the art is registered on its plot.
fn graph_end(&mut self, whole: bool) {
let Some(g) = self.graph.take() else { return };
let depth = self.frames.len();
let live = g.live.filter(|r| whole && r.stage == Stage::Done && depth == g.frames);
let spec = live.as_ref().and_then(|r| r.finish(&mut self.names).zip(r.series_tags()));
let attached = spec.is_some_and(|(mut spec, tags)| {
let Some(art) = self.frames.last_mut().filter(|f| f.children.len() == g.siblings + 1).and_then(|f| f.children.last_mut()) else {
return false;
};
if !matches!(art.kind, NodeKind::Group { clip: false, .. }) || !tags_groups(art, &tags) || !draws_axes(art, spec.rect) {
return false;
}
let Some(placed) = art.geometric_bounds().filter(|b| b.width() > 0.0 && b.height() > 0.0) else { return false };
let r = spec.rect;
if r.x0 < placed.x0 - EDGE || r.y0 < placed.y0 - EDGE || r.x1 > placed.x1 + EDGE || r.y1 > placed.y1 + EDGE {
return false;
}
let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false };
spec.series_paints = paints;
spec.placed = Some(placed);
tag_series(art, &tags);
art.extras_mut().graph = Some(Box::new(spec));
true
});
if !attached {
self.warn(GRAPH_PLAIN);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_color::Color;
use vectorcraft_geom::shapes;
/// A graph's art: one series group (id 2) holding one mark painted `ap`, the group changed by
/// `group`.
fn art(ap: Appearance, group: impl Fn(&mut Node)) -> Node {
let mark = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), ap));
let mut series = Node::group(NodeId(2), vec![mark]);
group(&mut series);
Node::group(NodeId(1), vec![Arc::new(series)])
}
/// A series whose mark has two fills has no one paint, so the graph can't draw it again.
#[test]
fn a_series_mark_with_two_fills_has_no_series_paint() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let one = Appearance::basic(red.clone(), Paint::None, 0.0);
let mut two = one.clone();
two.items.extend(one.items.iter().find(|i| i.is_fill()).cloned());
let tags = HashMap::from([(NodeId(2), 0)]);
let kept = series_paints(&art(one, |_| {}), &tags, false).expect("one fill");
assert_eq!((kept[0].fill.as_ref(), kept[0].stroke.as_ref()), (Some(&red), Some(&Paint::None)));
assert!(series_paints(&art(two, |_| {}), &tags, false).is_none());
}
/// A series group that is hidden, see-through or in another blending mode is not drawn again so.
#[test]
fn a_series_group_drawn_otherwise_has_no_series_paint() {
let ap = || Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
let tags = HashMap::from([(NodeId(2), 0)]);
assert!(series_paints(&art(ap(), |g| g.visible = false), &tags, false).is_none(), "hidden");
assert!(series_paints(&art(ap(), |g| g.opacity = 0.5), &tags, false).is_none(), "50% opaque");
assert!(series_paints(&art(ap(), |g| g.blend = BlendMode::Multiply), &tags, false).is_none(), "Multiply");
}
}
+34 -45
View File
@@ -1,12 +1,9 @@
use super::containers::close;
use super::document::slot_of;
use super::types::{
BLENDS, FLIP, Frame, GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG,
line_width,
};
use super::types::{BLENDS, FLIP, Frame, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG, line_width};
use super::{
Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, Graph, HashMap,
HashSet, Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint,
Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, HashMap, HashSet,
Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint,
};
impl<'a> Reader<'a> {
@@ -69,6 +66,7 @@ impl<'a> Reader<'a> {
/// `LB`: a graph started in this layer that hasn't ended doesn't go on past it; the layer ends.
fn layer_end(&mut self) -> Result<(), String> {
if self.graph.as_ref().is_some_and(|g| g.frames >= self.frames.len()) {
self.graph_plain();
self.graph = None;
self.warn(GRAPH_UNENDED);
}
@@ -158,7 +156,7 @@ impl<'a> Reader<'a> {
let mesh_ended = std::mem::take(&mut self.mesh_ended);
let vals = self.operands();
let vals = self.take_head(vals);
if self.graph_record(w, hidden) {
if self.graph_record(w, &vals, hidden, (group_ended, mesh_ended)) {
return Ok(());
}
// Only `Bh` reads an undefined number. Anywhere else it would reach a point or a size, so
@@ -383,17 +381,20 @@ impl<'a> Reader<'a> {
// `(text) justified TS`, special characters (§22.6): the reader adds its characters like `Tx`.
"Tx" | "Tj" | "TX" | "TS" => self.text_body(w, &vals),
"Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" | "TV" | "Tv" | "Ty" | "TY" | "Tg" | "Xb"
| "Xe" | "XB" => {
| "Xe" | "XB" | "XL" | "TG" | "Xu" | "Tu" => {
self.text_attr(w, &vals);
}
// Attributes the reader doesn't keep (kerning pairs, line breaking and Japanese layout
// rules) and final-form positions (§15.3).
"Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TG" | "Tu" | "Xu" => {}
// A kerning pair (`Tk`, `TK` in overflow text, §15.4.6.1) and discretionary hyphens
// (`T+`, `T-`, §15.4.10.1).
"Tk" | "TK" => self.text_kern(&vals),
"T+" => self.discretionary_hyphen(false),
"T-" => self.discretionary_hyphen(true),
// Final-form positions (§15.4.7: `Tc Tw Tm Td T* TR`, printing only), which the type's
// layout computes again.
"Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" => {}
// `TM` (pop text matrix) and `Te` (end render), listed in §22.6, keep nothing either; the
// reader takes `Te` with any number of operands.
"TM" | "Te" => {}
// The hyphenation language (`XL`), which the reader doesn't keep either (§22).
"XL" => {}
"TE" => self.te(&vals),
"TZ" => self.tz(&vals),
// An image whose samples follow in comment lines (read at `%AI5_EndRaster`).
@@ -425,33 +426,6 @@ impl<'a> Reader<'a> {
Ok(())
}
/// A graph's records (version 7 specification §17 and appendix A): `%_Gs` starts the graph on
/// a layer, `GS` ends it, and its data and settings (the operators in [`GRAPH_OPS`], and any
/// operator on a `%_` line between `Gt` and `GT`) are left out with their operands. Its drawn
/// art, and anything else, is read as usual. `true` when `w` was one of them.
fn graph_record(&mut self, w: &str, hidden: bool) -> bool {
let Some(g) = self.graph.as_mut() else {
// Outside a graph, its operators stay ones the reader doesn't know.
if w == "Gs" && hidden && !self.frames.is_empty() {
self.graph = Some(Graph { settings: false, frames: self.frames.len() });
self.warn(GRAPH_PLAIN);
return true;
}
return false;
};
match w {
// A graph doesn't start inside another: the one being read goes on.
"Gs" => self.warn(GRAPH_UNENDED),
"GS" => self.graph = None,
"Gt" => g.settings = true,
"GT" => g.settings = false,
_ if GRAPH_OPS.contains(&w) => {}
_ if hidden && g.settings => {}
_ => return false,
}
true
}
/// `… Lb`: a layer's options, `visible preview unlocked printing dimmed`, then the colour index
/// and its RGB. The colour index is at 5 with fewer than ten operands, 6 with ten to twelve
/// (`masks` before it) and 7 with thirteen or more (one more flag before it). Four places after
@@ -585,9 +559,9 @@ impl<'a> Reader<'a> {
return;
}
self.image_tail = false;
// An object's tags (`XT`) follow it one after another, and an image's follow the `XH` that
// ends its data.
if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB" | "XT" | "XH") {
// An object's tags (`XT`, and a graph's `Go`) follow it one after another, and an image's
// follow the `XH` that ends its data.
if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB" | "XT" | "XH" | "Go") {
return;
}
self.after_object = false;
@@ -1102,6 +1076,15 @@ fn no_guides(n: &Node, depth: usize) -> bool {
depth <= MAX_DEPTH && !n.is_guide() && n.children().into_iter().flatten().all(|c| no_guides(c, depth + 1))
}
/// Is `n` a compound path with a guide member whose bounds reach past the bounds of its members that
/// aren't guides, or with guide members only? Any other object counts as no.
fn guides_reach_past(n: &Node) -> bool {
let NodeKind::Compound { children, .. } = &n.kind else { return false };
let bounds =
|guides: bool| children.iter().filter(|c| c.is_guide() == guides).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds()));
bounds(true).is_some_and(|g| bounds(false).is_none_or(|o| o.union(g) != o))
}
/// The largest Twist angle, in degrees either way, read as a live effect on an object that isn't a
/// path or compound path with straight segments: VectorCraft's own limit. An object with a larger
/// Twist keeps the file's drawn look.
@@ -1115,7 +1098,8 @@ const MAX_STRAIGHT_TWIST: f64 = 180.0;
/// Is `object` one that style `st`, whose effect moves the outline, is read on? It and everything
/// in it [`moves_alike`], and the style paints no gradient. Twist is read only when nothing is
/// stroked and its angle is a number: up to [`MAX_STRAIGHT_TWIST`] degrees either way on a path or
/// compound path with straight segments, or up to [`MAX_TWIST`] degrees either way on another object
/// compound path with straight segments (only at 0° when its guide members reach past its other
/// members, see [`guides_reach_past`]), or up to [`MAX_TWIST`] degrees either way on another object
/// with no guide in it. Transform that scales, turns or reflects is read only when nothing is stroked
/// (its reference point lies on the bounds without strokes).
fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
@@ -1128,7 +1112,12 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool {
&& st.effects.iter().all(|e| match e.id.as_str() {
"distort.twist" => {
let within = |limit: f64| e.params["angle"].as_f64().is_some_and(|a| a.abs() <= limit);
!stroked && if straight(object) { within(MAX_STRAIGHT_TWIST) } else { no_guides(object, 0) && within(MAX_TWIST) }
!stroked
&& if straight(object) {
within(MAX_STRAIGHT_TWIST) && (e.params["angle"].as_f64() == Some(0.0) || !guides_reach_past(object))
} else {
no_guides(object, 0) && within(MAX_TWIST)
}
}
"distort.transform" => {
let p = &e.params;
+3 -13
View File
@@ -436,8 +436,8 @@ pub const NON_NATIVE_ART_UNREAD: &str = "non-native art (a placed PDF's content)
/// The name of the group a `/ForeignObject`'s art comes in as.
pub const NON_NATIVE_ART: &str = "Non-native art";
/// The note for a file with a graph (`%_Gs` … `%_GS`): its drawn art comes in, its data and
/// settings don't.
/// The note for a file with a graph (`%_Gs` … `%_GS`) whose data and settings can't be kept: its
/// drawn art comes in as plain art.
pub const GRAPH_PLAIN: &str = "graphs come in as plain art, without their data or settings";
/// The note for a graph that starts inside another or doesn't end before its layer does: the art
@@ -445,18 +445,8 @@ pub const GRAPH_PLAIN: &str = "graphs come in as plain art, without their data o
pub const GRAPH_UNENDED: &str = "a graph's records don't end where they should: its art was read as it is";
/// A graph's records (the version 7 specification's chapter 17 and appendix A): two-letter
/// operators starting with `G`, read and left out with their operands.
/// operators starting with `G`, read with their operands.
pub(super) const GRAPH_OPS: &[&str] = &[
"G1", "G+", "Ga", "GA", "Gb", "Gc", "GC", "Gd", "GD", "Ge", "Gf", "Gg", "Gi", "Gj", "Gl", "Gm", "Go", "Gp", "Gr", "Gs", "GS", "Gt", "GT", "Gv",
"Gw", "GX", "Gx", "Gy", "Gz",
];
/// A graph being read (`%_Gs` … `%_GS`).
#[derive(Debug)]
pub(super) struct Graph {
/// Between `Gt` and `GT`, where the graph's settings may use paint and type operators on `%_`
/// lines too.
pub(super) settings: bool,
/// How many frames were open at its `Gs`: a layer that ends with fewer ends the graph.
pub(super) frames: usize,
}
+378 -1
View File
@@ -4284,6 +4284,119 @@ fn legacy_end_render_and_text_matrix_pop_read() {
}
}
/// The text, manual kerning and space before each run of a legacy-format file's first text object.
fn legacy_kerning(art: &str) -> Vec<(String, Option<f64>, f64)> {
legacy_texts(art)[0].runs.iter().map(|r| (r.text.clone(), r.style.kerning, r.style.kerning_before)).collect()
}
/// `autoKern kernValue Tk` (§15.4.6.1) spaces the character before it from the one after it: with
/// `autoKern` 0 by `kernValue` (1/1000 em, kept to -1000 to 10,000) as the manual kerning after the
/// character before it, with 1 by the automatic kerning; `TK` does the same in overflow text. At
/// the start of a line it is the space before the line's first character.
#[test]
fn legacy_manual_pair_kerning_is_kept() {
let s = |x: &str| x.to_string();
let runs = legacy_kerning(&point_type("0 TA\n(A) Tx\n0 -80 Tk", "V"));
assert_eq!(runs, [(s("A"), Some(-80.0), 0.0), (s("V"), Some(0.0), 0.0)]);
// Inside a run, the character before it takes the value alone.
let runs = legacy_kerning(&point_type("(WAVE) Tx\n0 50 Tk", "S"));
assert_eq!(runs, [(s("WAV"), None, 0.0), (s("E"), Some(50.0), 0.0), (s("S"), None, 0.0)]);
// `autoKern` 1 gives the pair the automatic kerning, whatever its value.
let runs = legacy_kerning(&point_type("0 TA\n(AV) Tx\n1 -50 Tk", "A"));
assert_eq!(runs, [(s("A"), Some(0.0), 0.0), (s("V"), None, 0.0), (s("A"), Some(0.0), 0.0)]);
// Pairs with the same value in a row stay one run.
let runs = legacy_kerning(&point_type("0 TA\n(A) Tx\n0 50 Tk\n(B) Tx\n0 50 Tk", "C"));
assert_eq!(runs, [(s("AB"), Some(50.0), 0.0), (s("C"), Some(0.0), 0.0)]);
// At the start of the text and of a paragraph, the space before the line's first character.
let runs = legacy_kerning(&point_type("0 -30 Tk", "Hi"));
assert_eq!(runs, [(s("H"), None, -30.0), (s("i"), None, 0.0)]);
let runs = legacy_kerning(&point_type("(a\\r) Tx\n0 40 Tk", "b"));
assert_eq!(runs, [(s("a\n"), None, 0.0), (s("b"), None, 40.0)]);
let runs = legacy_kerning(&point_type("(a) Tx\n(\\r) TX\n0 40 TK", "b"));
assert_eq!(runs, [(s("a\n"), None, 0.0), (s("b"), None, 40.0)]);
// In overflow text.
let runs = legacy_kerning(&point_type("(ab) Tx\n0 25 TK", "c").replace("(c) Tx", "(c) TX"));
assert_eq!(runs, [(s("a"), None, 0.0), (s("b"), Some(25.0), 0.0), (s("c"), None, 0.0)]);
// Kept to the range `text.setRangeStyle` takes.
let runs = legacy_kerning(&point_type("(a) Tx\n0 -5000 Tk\n(b) Tx\n0 20000 Tk", "c"));
assert_eq!(runs, [(s("a"), Some(-1000.0), 0.0), (s("b"), Some(10_000.0), 0.0), (s("c"), None, 0.0)]);
// The pair is spaced as the kerning says.
let x = |art: &str| legacy_origins(&legacy_texts(art)[0])[1].0;
let (plain, kerned) = (x(&point_type("0 TA\n(A) Tx", "V")), x(&point_type("0 TA\n(A) Tx\n0 -80 Tk", "V")));
assert!((plain - kerned - 0.96).abs() < 1e-6, "{plain} {kerned}");
}
/// A `Tk` whose operands are missing or are not numbers, or whose flag is not 0 or 1, and a `Tk`
/// outside a text object leave the type as it was.
#[test]
fn legacy_pair_kerning_with_bad_operands_leaves_the_type_as_it_was() {
let want = legacy_kerning(&point_type("(H) Tx", "i"));
for bad in ["0 Tk", "Tk", "/x 50 Tk", "0 /x Tk", "2 50 Tk", "0.5 50 Tk", "(0) 50 Tk"] {
assert_eq!(legacy_kerning(&point_type(&format!("(H) Tx\n{bad}"), "i")), want, "{bad}");
}
let outside = legacy_kerning(&format!("0 50 Tk\n{}", point_type("(H) Tx", "i")));
assert_eq!(outside, want);
}
/// `T+` (a discretionary hyphen, §15.4.10.1) is a soft hyphen where it stands, in overflow text
/// too; `T-` makes the printed hyphen before it a soft hyphen, or adds one. Outside a text object
/// they add nothing.
#[test]
fn legacy_discretionary_hyphens_are_soft_hyphens() {
for (art, text) in [
(point_type("(co) Tx\nT+", "operate"), "co\u{ad}operate"),
(point_type("(co-) Tx\nT-", "operate"), "co\u{ad}operate"),
(point_type("(co) Tx\nT-", "operate"), "co\u{ad}operate"),
(point_type("(co) Tx\nT+", "operate").replace("(operate) Tx", "(operate) TX"), "co\u{ad}operate"),
(format!("T+\nT-\n{}", point_type("", "co")), "co"),
] {
let texts = legacy_texts(&art);
assert_eq!(texts[0].plain_text(), text, "{art}");
}
}
/// `languageID XL` (§22.6) is the characters' language, 0 (U.S. English) the default; it lasts into
/// the next text object, and an ID that is not 0 to 11 leaves the language as it was.
#[test]
fn legacy_hyphenation_language_is_kept() {
let lang = |t: &vectorcraft_doc::TextObject| t.runs.iter().map(|r| r.style.language.clone()).collect::<Vec<_>>();
let texts = legacy_texts(&format!("{}{}", point_type("%_ 3 XL\n(a) Tx\n%_ 0 XL\n(b) Tx\n%_ 8 XL", "c"), point_type("", "d")));
assert_eq!(lang(&texts[0]), [Some("de".to_string()), None, Some("nb".to_string())]);
assert_eq!(lang(&texts[1]), [Some("nb".to_string())]);
for bad in ["12 XL", "-1 XL", "1.5 XL", "/x XL", "XL"] {
let texts = legacy_texts(&point_type(&format!("2 XL\n{bad}"), "a"));
assert_eq!(lang(&texts[0]), [Some("fr".to_string())], "{bad}");
}
}
/// The line breaking value (`TG`) and the Japanese layout rules (`Xu`, `Tu`, §22.6) are not kept:
/// a visible text object read while one is set gives a warning, once for each in a file. A copy of
/// a text object on `%_` lines gives none, and the final-form positions (§15.4.7) give none.
#[test]
fn legacy_line_breaking_and_japanese_layout_rules_are_warned_once() {
const LINE_BREAKING: &str = "the Line Breaking setting of legacy type was left out";
const JAPANESE_LAYOUT: &str = "the Japanese layout rules of legacy type were left out";
let r = legacy_read(&format!("{}{}", point_type("50 TG\n0 1 120 150 Xu", "a"), point_type("60 TG", "b")));
assert_eq!(r.warnings, [LINE_BREAKING, JAPANESE_LAYOUT]);
assert_eq!(legacy_read(&point_type("0 1 120 150 Tu", "a")).warnings, [JAPANESE_LAYOUT]);
let hidden: String = point_type("50 TG", "a").lines().map(|l| format!("%_{l}\n")).collect();
assert_eq!(legacy_read(&hidden).warnings, Vec::<String>::new());
let final_form = point_type("1 0 0 1 10 50 Tm\n0 0 Td\nT*\n0 Tc\n0 Tw\n1 0 0 1 0 0 TR\nTe\nTM", "Hi");
let r = legacy_read(&final_form);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert_eq!(art_texts(&r.doc)[0].plain_text(), "Hi");
}
/// `TG`, `Xu` and `Tu` with missing or non-numeric operands set nothing, so they give no warning.
#[test]
fn legacy_line_breaking_and_japanese_layout_rules_with_bad_operands_are_not_warned() {
for attrs in ["TG", "(a) TG", "1 120 150 Xu", "0 1 (a) 150 Xu", "Tu", "0 1 120 (a) Tu"] {
let r = legacy_read(&point_type(attrs, "a"));
assert!(r.warnings.is_empty(), "{attrs}: {:?}", r.warnings);
assert_eq!(art_texts(&r.doc)[0].plain_text(), "a", "{attrs}");
}
}
/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum
/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges
/// `text.setFormat` takes.
@@ -7183,7 +7296,11 @@ fn twist_is_read_on_curves_compound_paths_and_groups_with_nothing_stroked_up_to_
("a twisted group", read(&twist(90.0, None), &distort_group()), 2),
("a group with a hidden member", read(&twist(45.0, None), &hidden_member), 2),
("a curve twisted a quarter turn back", read(&twist(-90.0, BLUE_FILL), &curved), 0),
("a straight compound path with a guide, as before", read(&twist(45.0, BLUE_FILL), &with_guide(&rect_path(20.0, 20.0, 60.0, 50.0))), 2),
(
"a straight compound path with a guide inside it, as before",
read(&twist(45.0, BLUE_FILL), &with_guide(&rect_path(0.0, 0.0, 60.0, 50.0))),
2,
),
] {
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings);
let a = art(&r.doc);
@@ -7250,6 +7367,48 @@ fn twist_is_read_on_straight_paths_and_compound_paths_up_to_half_a_turn() {
}
}
#[test]
fn twist_on_a_straight_compound_path_keeps_the_drawn_look_where_a_guide_reaches_past_its_other_members() {
// GUARDS: a straight compound path whose guide members reach past its other members was read
// with a live Twist measured from bounds that take in those guides, which draws differently from
// the art saved with it.
// The object, `hidden` painted with its style, under its drawn look.
let object = |hidden: &str| {
format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0), hidden.replace('\n', "\n%_"))
};
// A compound path of a square and the guide from `from` to `to`.
let with_guide = |from: (f64, f64), to: (f64, f64)| {
object(&format!("*u\n{}f\n{} {} m\n{} {} L\n(N) *\n*U\n", rect_path(20.0, 20.0, 60.0, 50.0), from.0, from.1, to.0, to.1))
};
let twist = |angle: f64| distort_styles("Adobe Twirl", &format!("{angle} /Real (angle) ,\n"), BLUE_FILL);
let read = |angle: f64, art_: &str| read_ok(&format!("{}{}", twist(angle), layer(art_)));
for (what, r) in [
("a guide inside the square", read(45.0, &with_guide((25.0, 25.0), (35.0, 35.0)))),
("a guide on the square's corners", read(180.0, &with_guide((20.0, 20.0), (60.0, 50.0)))),
("a guide inside the square, half a turn back", read(-180.0, &with_guide((30.0, 40.0), (50.0, 30.0)))),
("a guide outside the square, not turned", read(0.0, &with_guide((5.0, 0.0), (15.0, 10.0)))),
] {
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings);
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{what}: {a:#?}");
assert_eq!(a[0].children().map_or(0, |c| c.len()), 2, "{what}: the object, not its look: {a:#?}");
let [e] = a[0].appearance.effects.as_slice() else { panic!("{what}: {:?}", a[0].appearance) };
assert_eq!(e.id, "distort.twist", "{what}");
}
for (what, r) in [
("a guide outside the square", read(45.0, &with_guide((5.0, 0.0), (15.0, 10.0)))),
("a guide reaching past the square's right side", read(45.0, &with_guide((30.0, 30.0), (70.0, 40.0)))),
("a guide reaching past the square's top, half a turn", read(180.0, &with_guide((30.0, 30.0), (40.0, 51.0)))),
("a guide around the square, a quarter turn back", read(-90.0, &with_guide((0.0, 0.0), (80.0, 70.0)))),
("a compound path of guides only", read(45.0, &object("*u\n25 25 m\n35 35 L\n(N) *\n40 25 m\n50 35 L\n(N) *\n*U\n"))),
] {
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{what}: {a:#?}");
assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}");
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings);
}
}
#[test]
fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() {
// GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none.
@@ -10434,6 +10593,7 @@ fn type_with_an_art_brush_keeps_its_drawn_look() {
}
use read::{GRAPH_PLAIN, GRAPH_UNENDED};
use vectorcraft_doc::{GraphKind, TickLength};
/// Editing data in the legacy format (version 7 specification, chapter 2): `%AI5_FileFormat 2.0`,
/// the art size and the template box in the header, then `body`.
@@ -10575,6 +10735,223 @@ fn a_graphs_records_take_their_operands() {
assert_eq!(r.warnings, [GRAPH_PLAIN]);
}
/// A graph's style record (`Gy`) for a grouped column graph: no shadow, legends as in column
/// graphs, lines without marks, measured against the left axis.
const LIVE_STYLE: &str = "%_5 0 0 14 0 1 0 0 6 44 Gy\n";
/// A graph's dialog record (`Gd`): columns 90% wide in clusters 80% wide.
const LIVE_DIALOG: &str = "%_10 2 0 0 90 80 0 Gd\n";
/// A graph's axes, bottom, left and right: the bottom one with no tick marks, between its labels;
/// the left one labeled `$` … ` units`, with two tick marks a division.
const LIVE_AXES: &str = "%_1 () Ga\n%_0 13 0 0 0 0 1 () GA\n%_2 ($) Ga\n%_0 14 0 0 0 2 0 ( units) GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n";
/// A graph's table: series East and West, categories Q1 to Q3, and an empty cell (West in Q2).
const LIVE_TABLE: &str = "%_4 3 1 1 Gz\n%_() Gc (East) Gc (West) Gc\n%_(Q1) Gc 5 3 (Q2) Gc 7 () Gc (Q3) Gc 4 6 Gc GC\n";
/// A column of a graph's series at `x`, tagged as one data bar.
fn series_bar(x: f64) -> String {
format!("0 0 0 1 k\n{}f\n%_4 1 0 0 Go\n", rect_path(x, 100.0, x + 20.0, 150.0))
}
/// The first series' mark in [`live_art`].
fn series_mark() -> String {
format!("0 0 0 1 k\n{}f\n", rect_path(110.0, 100.0, 130.0, 150.0))
}
/// [`series_mark`] filled and stroked, then an outline stroked alike with no fill.
fn series_mark_and_outline() -> String {
format!("0 0 0 1 k\n0 0 0 1 K\n{}B\n{}S\n", rect_path(110.0, 100.0, 130.0, 150.0), rect_path(112.0, 100.0, 118.0, 120.0))
}
/// The drawn art of the graph [`live_graph`] gives: two series groups, each tagged as one series by
/// its table column, and the axes on the plot's left and bottom edges.
fn live_art() -> String {
format!(
"u\n{}U\n%_2 1 0 0 Go\nu\n{}U\n%_2 2 0 0 Go\nu\n0 0 0 1 K\n100 200 m\n100 100 L\n300 100 L\nS\nU\n%_9 0 0 2 Go\n",
series_bar(110.0),
series_bar(140.0)
)
}
/// A graph whose records read whole, written from the version 7 specification's appendix A, on the
/// plot 100 100 300 200 (art space).
fn live_graph() -> String {
format!("%_Gs\n%_100 200 300 100 Gb\n{LIVE_STYLE}{LIVE_DIALOG}{LIVE_AXES}{LIVE_TABLE}u\n{}U\n%_GS\n", live_art())
}
/// The graphs in `doc`'s art, and the series groups tagged in them.
fn live_graphs(doc: &Document) -> (Vec<Node>, usize) {
let (mut graphs, mut tagged) = (vec![], 0);
doc.walk(|n| {
if n.extras().graph.is_some() {
graphs.push(n.clone());
}
tagged += usize::from(n.extras().series_index.is_some());
});
(graphs, tagged)
}
fn same_rect(a: Rect, b: Rect) -> bool {
(a.x0 - b.x0).abs() + (a.y0 - b.y0).abs() + (a.x1 - b.x1).abs() + (a.y1 - b.y1).abs() < 1e-9
}
/// A graph whose records read whole keeps its data and settings on its group, which holds its
/// drawn art as it is, each series group tagged with its index.
#[test]
fn a_graph_whose_records_read_whole_keeps_its_data_and_settings() {
let r = read(stream7(&layer7("Graph", &live_graph())).as_bytes()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let a = art(&r.doc);
assert_eq!(a.len(), 1);
let g = a[0].extras().graph.clone().expect("a live graph");
assert_eq!(g.kind, GraphKind::Column);
assert_eq!(g.series, ["East", "West"]);
assert_eq!(g.categories, ["Q1", "Q2", "Q3"]);
assert_eq!(g.cells(), [[Some(5.0), Some(3.0)], [Some(7.0), None], [Some(4.0), Some(6.0)]]);
assert_eq!((g.column_width, g.cluster_width), (90.0, 80.0));
assert_eq!((g.prefix.as_str(), g.suffix.as_str(), g.tick_length, g.tick_marks), ("$", " units", TickLength::Short, 2));
assert_eq!((g.category_tick_length, g.ticks_between_labels), (TickLength::None, true));
assert_eq!((g.ticks, g.axis_min, g.axis_max), (0, None, None));
assert!(g.legend && !g.legend_across_top && !g.mark_points && g.connect_points && !g.drop_shadow && !g.edge_to_edge, "{g:?}");
// The drawn art: two series groups and the axes, as written.
let kids = a[0].children().unwrap();
assert_eq!(kids.len(), 3);
let index: Vec<_> = kids.iter().map(|k| k.extras().series_index).collect();
assert_eq!(index, [Some(0), Some(1), None]);
assert!(kids[..2].iter().all(|k| k.children().is_some_and(|c| c.len() == 1)));
// Each series keeps its marks' fill, and no stroke, for when the graph is drawn again.
assert_eq!(g.series_paints.len(), 2);
let fill = kids[0].children().unwrap()[0].appearance.items.iter().find(|i| i.is_fill()).map(|i| i.paint().clone());
assert!(g.series_paints.iter().all(|p| p.fill == fill && p.stroke.as_ref().is_some_and(|s| s.is_none())), "{:?}", g.series_paints);
let axes = kids[2].children().unwrap()[0].geometric_bounds().unwrap();
assert!(same_rect(g.rect, axes), "the plot is where the axes are: {:?} {axes:?}", g.rect);
assert_eq!(g.placed, a[0].geometric_bounds());
}
/// The graph types the records give: 5 grouped column, 6 stacked column, 7 line, 10 area; and the
/// style and dialog settings, each kept as the graph's.
#[test]
fn a_graphs_type_and_settings_come_from_its_records() {
let live = |style: &str, dialog: &str, axes: &str| {
let text = live_graph().replace(LIVE_STYLE, style).replace(LIVE_DIALOG, dialog).replace(LIVE_AXES, axes);
let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap();
assert!(r.warnings.is_empty(), "{style}{dialog}: {:?}", r.warnings);
art(&r.doc)[0].extras().graph.clone().expect("a live graph")
};
for (ty, kind) in [(5, GraphKind::Column), (6, GraphKind::StackedColumn), (7, GraphKind::Line), (10, GraphKind::Area)] {
let g = live(&format!("%_{ty} 0 0 14 0 1 0 0 6 44 Gy\n"), LIVE_DIALOG, LIVE_AXES);
assert_eq!(g.kind, kind, "{ty}");
}
let axes = LIVE_AXES.replace("%_0 14 0 0 0 2 0 ( units) GA", "%_1 15 0 100 25 0 0 () GA");
let g = live("%_7 1 1 14 1 0 0 1 6 44 0 2 Gy\n", "%_10 2 1 0 120 50 1 Gd\n", &axes);
assert!(g.drop_shadow && g.first_row_in_front && g.mark_points && !g.connect_points && g.legend_across_top, "{g:?}");
assert!(g.first_column_in_front && g.edge_to_edge, "{g:?}");
assert_eq!((g.column_width, g.cluster_width), (120.0, 50.0));
assert_eq!((g.ticks, g.axis_min, g.axis_max, g.tick_length, g.tick_marks), (4, Some(0.0), Some(100.0), TickLength::Full, 1));
// A line graph's series draws its line unfilled beside its filled marks.
let text = live_graph().replace(LIVE_STYLE, "%_7 0 0 14 0 1 0 0 6 44 Gy\n").replacen(&series_mark(), &series_mark_and_outline(), 1);
let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert!(art(&r.doc)[0].extras().graph.is_some());
// An empty list of customizations, of the version appendix A gives (2), sets nothing.
let text = live_graph().replace("GC\n", "GC\n%_2 Gt\n%_GT\n");
let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert!(art(&r.doc)[0].extras().graph.is_some());
}
/// A graph keeps its drawn art and stays plain, with one note, when a record has a shape or value
/// appendix A doesn't give, sets what the model doesn't keep, or the table, the series tags or the
/// art don't fit the graph.
#[test]
fn graphs_the_model_cant_keep_stay_plain_art() {
let cases: Vec<(&str, String)> = vec![
("an eleventh style value", live_graph().replace(LIVE_STYLE, "%_5 0 0 14 0 1 0 0 6 44 0 Gy\n")),
("eleven dialog values", live_graph().replace(LIVE_DIALOG, "%_10 2 0 0 90 80 0 0 0 0 0 Gd\n")),
("a fourth axis", live_graph().replace(LIVE_AXES, &format!("{LIVE_AXES}%_8 () Ga\n%_0 14 0 0 0 0 0 () GA\n"))),
("ten axis values", live_graph().replace("%_0 14 0 0 0 0 0 () GA", "%_0 14 0 0 0 0 0 () 0 0 GA")),
("a pie graph", live_graph().replace("%_5 0 0 14", "%_8 0 0 14")),
("a scatter graph", live_graph().replace("%_5 0 0 14", "%_9 0 0 14")),
("type 11", live_graph().replace("%_5 0 0 14", "%_11 0 0 14")),
("legends in wedges", live_graph().replace("%_5 0 0 14", "%_5 0 0 15")),
("the right axis", live_graph().replace("6 44 Gy", "6 45 Gy")),
("lines as shapes", live_graph().replace("%_5 0 0 14 0 1 0", "%_5 0 0 14 0 1 1")),
("both axes alike", live_graph().replace(LIVE_DIALOG, "%_10 2 0 1 90 80 0 Gd\n")),
("a subscription", live_graph().replace(LIVE_DIALOG, &format!("{LIVE_DIALOG}%_0 0 1 1 1 Gj\n"))),
("a customization", live_graph().replace("GC\n", "GC\n%_2 Gt\n%_(Bars) GD\n%_GT\n")),
("customizations without their version", live_graph().replace("GC\n", "GC\n%_Gt\n%_GT\n")),
("customizations of another version", live_graph().replace("GC\n", "GC\n%_3 Gt\n%_GT\n")),
("bounds upside down", live_graph().replace("%_100 200 300 100 Gb", "%_100 100 300 200 Gb")),
("a plot the axes aren't on", live_graph().replace("%_100 200 300 100 Gb", "%_50 200 300 100 Gb")),
("a text data cell", live_graph().replace("7 () Gc", "(seven) Gc () Gc")),
("a table of empty cells", live_graph().replace(LIVE_TABLE, "%_4 3 1 1 Gz\n%_() Gc (East) Gc (West) Gc\n%_GC\n")),
("a cell past the table", live_graph().replace("4 6 Gc GC", "4 6 1 Gc GC")),
("too many categories", live_graph().replace("%_4 3 1 1 Gz", "%_10002 3 1 1 Gz")),
("a table too large", live_graph().replace("%_4 3 1 1 Gz", "%_4000000000 4000000000 1 1 Gz")),
("a number as a label", live_graph().replace("(West) Gc", "2025 Gc")),
("a series untagged", live_graph().replace("%_2 2 0 0 Go", "%_4 2 0 0 Go")),
("a series tagged twice", live_graph().replace("%_2 2 0 0 Go", "%_2 1 0 0 Go")),
("a path tagged as a series", live_graph().replacen("%_4 1 0 0 Go", "%_2 1 0 0 Go", 1)),
("a target the specification doesn't list", live_graph().replace("%_9 0 0 2 Go", "%_3 0 0 2 Go")),
("art before its group", live_graph().replace("GC\nu\n", &format!("GC\n{}f\nu\n", rect_path(0.0, 0.0, 5.0, 5.0)))),
("a record on a line that shows", live_graph().replace("%_10 2 0 0 90 80 0 Gd", "10 2 0 0 90 80 0 Gd")),
("series groups inside another group", live_graph().replace("GC\nu\n", "GC\nu\nu\n").replace("U\n%_GS", "U\nU\n%_GS")),
(
"two fills in one series",
live_graph().replacen(
"f\n%_4 1 0 0 Go\nU\n",
&format!("f\n%_4 1 0 0 Go\n0 0 0 0.5 k\n{}f\nU\n", rect_path(112.0, 100.0, 118.0, 120.0)),
1,
),
),
("axes filled, not stroked", live_graph().replace("300 100 L\nS\n", "300 100 L\nf\n")),
("a series tagged on a row", live_graph().replace("%_2 2 0 0 Go", "%_2 2 1 0 Go")),
("a series tagged on the right axis", live_graph().replace("%_2 2 0 0 Go", "%_2 2 0 4 Go")),
("an unfilled mark in a column series", live_graph().replacen(&series_mark(), &series_mark_and_outline(), 1)),
("a series' mark in a group of its own", live_graph().replacen(&series_mark(), &format!("u\n{}U\n", series_mark()), 1)),
(
"an untagged graph of one series",
live_graph()
.replace(LIVE_TABLE, "%_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n")
.replace("%_2 2 0 0 Go", "%_4 1 0 0 Go")
.replace("%_2 1 0 0 Go", "%_4 1 0 0 Go"),
),
];
for (what, text) in cases {
let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(r.warnings, [GRAPH_PLAIN], "{what}");
assert_eq!(live_graphs(&r.doc), (vec![], 0), "{what}");
let mut kept = false;
r.doc.walk(|n| kept |= n.children().is_some_and(|c| c.len() == 3));
assert!(kept, "{what}: the drawn art is kept");
}
}
/// A graph in a group or a clipping group keeps its data on its own group, not the container's; of
/// two graphs in one layer, each is kept or left plain on its own, and the note is given once.
#[test]
fn graphs_are_kept_one_by_one_wherever_they_are() {
let clip = format!("q\n{}W n\n{}Q\n", rect_path(0.0, 0.0, 400.0, 400.0), live_graph());
for (what, text) in [("in a group", format!("u\n{}U\n", live_graph())), ("in a clipping group", clip)] {
let r = read(stream7(&layer7("Graph", &text)).as_bytes()).unwrap();
assert!(r.warnings.is_empty(), "{what}: {:?}", r.warnings);
let outer = &art(&r.doc)[0];
assert!(outer.extras().graph.is_none(), "{what}");
let (graphs, tagged) = live_graphs(&r.doc);
assert_eq!((graphs.len(), tagged), (1, 2), "{what}");
assert!(outer.children().unwrap().iter().any(|c| c.id == graphs[0].id), "{what}: the graph's own group");
}
let pie = live_graph().replace("%_5 0 0 14", "%_8 0 0 14");
let body = format!("{}{pie}{}", live_graph(), live_graph());
let r = read(stream7(&layer7("Graph", &body)).as_bytes()).unwrap();
assert_eq!(r.warnings, [GRAPH_PLAIN]);
let a = art(&r.doc);
assert_eq!(a.len(), 3);
let live: Vec<bool> = a.iter().map(|n| n.extras().graph.is_some()).collect();
assert_eq!(live, [true, false, true]);
}
/// Editing data in the legacy format (`%AI5_FileFormat 2.0`, ten `Lb` operands), then `body`.
fn mask_stream7(body: &str) -> String {
format!(
+12 -8
View File
@@ -208,15 +208,15 @@ fn a_postscript_ai_with_a_multi_layer_mask_opens_with_its_layers() {
assert!(r.warnings.iter().any(|w| w.contains("clipping group in each layer")), "{:?}", r.warnings);
}
/// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation and
/// tab-ruler attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition) and `Th`
/// (hyphen control). The reader drops `XL` and keeps the tab definition as the paragraph's tab
/// stops rather than failing the file the way it did before (the symptom seen on Illustrator 6/8
/// EPS files whose `Adobe_level2_AI5` program can't be run).
/// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation, tab-ruler
/// and kerning attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition), `Th`
/// (hyphen control), `Tk` (a manual kerning pair) and `T+` (a discretionary hyphen). The reader
/// keeps the language, the tab definition as the paragraph's tab stops, the pair's kerning and the
/// soft hyphen.
#[test]
fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() {
let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 9 Tf\n\
%_ 0 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(hi) Tx\nTO\n";
%_ 3 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(h) Tx\n0 -40 Tk\n(i) Tx\nT+\n(ho) Tx\nTO\n";
// The operators sit on a visible layer (so they'd be reported as unknown, not quietly skipped
// on a hidden one), beside the square so the layer is never empty.
let src = NAMED_PROLOG.replace("S\nLB\n%AI5_EndLayer--\n%AI5_BeginLayer", &format!("S\n{text}LB\n%AI5_EndLayer--\n%AI5_BeginLayer"));
@@ -228,10 +228,14 @@ fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() {
let mut texts = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
texts.push(t.para_at(0).clone());
texts.push((**t).clone());
}
});
let [p] = texts.as_slice() else { panic!("{texts:?}") };
let [t] = texts.as_slice() else { panic!("{texts:?}") };
assert_eq!(t.plain_text(), "hi\u{ad}ho");
let runs: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.kerning, r.style.language.as_deref())).collect();
assert_eq!(runs, [("h", Some(-40.0), Some("de")), ("i\u{ad}ho", None, Some("de"))]);
let p = t.para_at(0);
assert!(!p.hyphenate);
assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 2, 25));
let tabs: Vec<_> = p.tabs.iter().map(|t| (t.position, t.align)).collect();
+5 -2
View File
@@ -33,7 +33,9 @@
//! - Type (§15): point type, area type and type on a path as text objects, `type To`, `a b c d tx
//! ty startPt Tp` (the text matrix; the frame or path in art space between it and `TP`), each
//! run's paint style, `Tr` (fill, stroke, both or neither), `/_font size ascent descent Tf`,
//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), `TO`. Standard
//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), with manual
//! kerning as `0 value Tk` after each character that has it and before a paragraph's first
//! character that has space before it (§15.4.6.1) and soft hyphens as `T+` (§15.4.10.1), `TO`. Standard
//! Vertical Roman Alignment is written as `1 Tv` and `0 Tv`, and Tate-chu-yoko in horizontal
//! type as a Kumi block recorded for later use, `1 TY` … `0 TY` (§15.3.4); neither operator is
//! written for type that has neither mark. Only the
@@ -99,7 +101,7 @@ const HEX_LINE: usize = 60;
pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)";
pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines";
pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)";
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, manual kerning, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)";
pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)";
pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)";
@@ -122,6 +124,7 @@ const STROKES: &str =
"strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines";
const IMAGE_ALPHA: &str = "transparent image pixels are written over white";
const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art";
const GRAPHS: &str = "graphs are written as their art, without their data or settings";
/// The warning for an image left out because it can't be decoded: the note raster exports give
/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`).
const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture";
-1
View File
@@ -120,7 +120,6 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool {
let run_lost = |s: &CharStyle| {
s.underline
|| s.strikethrough
|| s.kerning.is_some_and(|k| k != 0.0)
|| s.optical_kerning
|| s.small_caps.is_some()
|| s.position != CharPosition::Normal
+1
View File
@@ -107,6 +107,7 @@ VCLegacy begin
/To {pop} bd /Tp {7 {pop} repeat} bd /TP {} bd /TO {} bd
/Tr {pop} bd /Tf {pop pop pop pop} bd /Ts {pop} bd /Tz {pop pop} bd /Tt {pop} bd /TA {pop} bd
/Tl {pop pop} bd /Ta {pop} bd /Ti {pop pop pop} bd /Tx {pop} bd /Tv {pop} bd /TY {pop} bd
/Tk {pop pop} bd /T+ {} bd
% The page trailer (3): annotatepage marks nothing.
/annotatepage {} bd
end
+68 -6
View File
@@ -1494,12 +1494,12 @@ fn type_on_a_path_alignment_and_end_bracket_are_warned_as_left_out() {
assert!(warned(&|t| t.kind = TextKind::OnPath { path: two(false), start: 0.25, end: None }));
}
/// Kerning other than Auto or 0, optical kerning, Optical Margin Alignment, System Layout,
/// fractional widths off and an area type frame with a second subpath are not held by a legacy
/// `.ai` text object: type with any of them is written as text, with the warning that they are
/// left out.
/// Optical kerning, Optical Margin Alignment, System Layout, fractional widths off and an area
/// type frame with a second subpath are not held by a legacy `.ai` text object: type with any of
/// them is written as text, with the warning that they are left out. Manual kerning is held
/// (`Tk`), with no warning.
#[test]
fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
fn optical_kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
use vectorcraft_doc::{TextKind, TextObject};
let warned = |edit: &dyn Fn(&mut TextObject)| {
let mut doc = typed();
@@ -1513,7 +1513,8 @@ fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
};
assert!(!warned(&|_| {}));
assert!(!warned(&|t| t.runs[0].style.kerning = Some(0.0)));
assert!(warned(&|t| t.runs[0].style.kerning = Some(50.0)));
assert!(!warned(&|t| t.runs[0].style.kerning = Some(50.0)));
assert!(!warned(&|t| t.runs[0].style.kerning_before = 50.0));
assert!(warned(&|t| t.runs[0].style.optical_kerning = true));
assert!(warned(&|t| t.optical_margin = true));
assert!(warned(&|t| t.system_layout = true));
@@ -1526,6 +1527,67 @@ fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
assert!(warned(&|t| t.kind = TextKind::Area { frame: PathData::new(vec![square(10.0), square(120.0)]) }));
}
/// Manual kerning is written as `0 value Tk` after each character that has it, the space before a
/// paragraph's first character as `Tk` before it, and a soft hyphen as a discretionary hyphen
/// (`T+`, §15.4.6.1 and §15.4.10.1); each reads back on the same characters.
#[test]
fn manual_kerning_and_soft_hyphens_are_written_and_read_back() {
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
let plain = style(12.0, Paint::solid(Color::BLACK));
let kerned = CharStyle { kerning: Some(-80.0), ..plain.clone() };
let before = CharStyle { kerning_before: 40.0, ..plain.clone() };
let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "AV", kerned.clone());
for (text, st) in [("A co\u{ad}op\n", &plain), ("W", &before), ("ord", &plain), ("d\u{ad}", &kerned)] {
t.runs.push(TextRun::new(text, st.clone()));
}
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = write(&doc);
assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
let text = String::from_utf8(out.bytes.clone()).unwrap();
assert!(text.contains("(A) Tx\n0 -80 Tk\n(V) Tx\n0 -80 Tk\n"), "{text}");
assert!(text.contains("(A co) Tx\nT+\n(op\\r) Tx\n"), "{text}");
assert!(text.contains("0 40 Tk\n(W) Tx\n"), "{text}");
// A soft hyphen with manual kerning keeps it too.
assert!(text.contains("(d) Tx\n0 -80 Tk\nT+\n0 -80 Tk\n"), "{text}");
let read = texts(&crate::import(&out.bytes).unwrap().document);
let runs: Vec<(String, Option<f64>, f64)> = read[0].1.runs.iter().map(|r| (r.text.clone(), r.style.kerning, r.style.kerning_before)).collect();
let s = |x: &str| x.to_string();
assert_eq!(
runs,
[
(s("AV"), Some(-80.0), 0.0),
(s("A co\u{ad}op\n"), None, 0.0),
(s("W"), None, 40.0),
(s("ord"), None, 0.0),
(s("d\u{ad}"), Some(-80.0), 0.0)
]
);
}
/// Manual kerning of 0 is written as `0 0 Tk` and reads back as manual kerning, not as the
/// automatic kerning of a pair with no `Tk`.
#[test]
fn manual_kerning_of_zero_is_written_and_read_back() {
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
let plain = style(12.0, Paint::solid(Color::BLACK));
let zero = CharStyle { kerning: Some(0.0), ..plain.clone() };
let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "AV", zero);
t.runs.push(TextRun::new("To", plain));
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = write(&doc);
let text = String::from_utf8(out.bytes.clone()).unwrap();
assert!(text.contains("(A) Tx\n0 0 Tk\n(V) Tx\n0 0 Tk\n"), "{text}");
let read = texts(&crate::import(&out.bytes).unwrap().document);
let runs: Vec<(String, Option<f64>)> = read[0].1.runs.iter().map(|r| (r.text.clone(), r.style.kerning)).collect();
assert_eq!(runs, [("AV".to_string(), Some(0.0)), ("To".to_string(), None)]);
}
/// Type whose font size measures the cap height is written at the em size it is drawn at, with
/// no warning: 14 pt measuring a 0.7 em cap height reads back as 20 pt type.
#[test]
+49 -4
View File
@@ -9,7 +9,7 @@ use super::{
ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind,
TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
};
use super::{CONIC, CONIC_WEDGES, DIAMOND, HUE_STOPS, SPREAD, SPREAD_CAPPED};
use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPPED};
pub(super) struct Writer<'a> {
doc: &'a Document,
@@ -254,6 +254,9 @@ impl<'a> Writer<'a> {
if n.name.as_deref().is_some_and(|s| !s.is_empty()) && !n.is_layer() {
self.warn(NAMES);
}
if n.extras().graph.is_some() {
self.warn(GRAPHS);
}
let locked = locked || n.locked;
match &n.kind {
NodeKind::Layer { children, clip, .. } => {
@@ -843,6 +846,8 @@ impl<'a> Writer<'a> {
self.line("TP");
let mut para = 0usize;
let mut para_start = true;
// No character of the current paragraph has been written.
let mut line_start = true;
for run in &t.runs {
let text = if run.style.all_caps { run.text.to_uppercase() } else { run.text.clone() };
let mut pieces = text.split('\n').peekable();
@@ -856,14 +861,38 @@ impl<'a> Writer<'a> {
para_start = false;
}
self.char_style(&run.style, t.para_at(para));
let mut bytes: Vec<u8> = piece.chars().filter_map(latin::encode).collect();
// The space before a line's first character, kerning before it (§15.4.6.1).
if line_start && !piece.is_empty() && run.style.kerning_before != 0.0 {
self.kern(run.style.kerning_before);
}
line_start = false;
// Manual kerning after each character (0 included, which differs from automatic
// kerning), a soft hyphen as a discretionary hyphen (§15.4.10.1).
let kerning = run.style.kerning;
let mut bytes = vec![];
for c in piece.chars() {
if c == '\u{ad}' {
self.text_string(&mut bytes);
self.line("T+");
if let Some(k) = kerning {
self.kern(k);
}
continue;
}
let Some(b) = latin::encode(c) else { continue };
bytes.push(b);
if let Some(k) = kerning {
self.text_string(&mut bytes);
self.kern(k);
}
}
if ends_paragraph {
bytes.push(b'\r');
para += 1;
para_start = true;
line_start = true;
}
self.body.push_str(&ps::bytes(&bytes));
self.line(" Tx");
self.text_string(&mut bytes);
}
}
if self.kumi {
@@ -873,6 +902,22 @@ impl<'a> Writer<'a> {
self.line("TO");
}
/// `bytes` as a string of characters, `(…) Tx`, when there are any; `bytes` is left empty.
fn text_string(&mut self, bytes: &mut Vec<u8>) {
if !bytes.is_empty() {
self.body.push_str(&ps::bytes(bytes));
self.line(" Tx");
bytes.clear();
}
}
/// Manual kerning of `k` 1/1000 em between the characters before and after it: `0 k Tk`.
fn kern(&mut self, k: f64) {
self.body.push_str("0 ");
ps::push_num(&mut self.body, finite(k, 0.0));
self.line(" Tk");
}
/// A paragraph's attributes: alignment `Ta` and indents `Ti` (first line's, left, right).
fn paragraph(&mut self, p: &ParaStyle) {
let align = match p.justify {
+5 -46
View File
@@ -352,64 +352,23 @@ fn read_data(ps: &[u8], name: &str) -> Option<Vec<u8>> {
None
}
/// The magic number of an EPS file with a binary header (a preview).
const DOS_MAGIC: [u8; 4] = [0xC5, 0xD0, 0xD3, 0xC6];
/// The binary header's size.
const DOS_HEADER: usize = 30;
pub use craft_eps::{DOS_HEADER, DOS_MAGIC, Sections, is_eps};
/// `ps` behind a binary header, followed by the TIFF preview `tiff`.
fn dos_eps(ps: &[u8], tiff: &[u8]) -> Result<Vec<u8>, String> {
let big = || "the file is too large for an EPS preview header (4 GB): choose no preview".to_string();
let ps_len = u32::try_from(ps.len()).map_err(|_| big())?;
let tiff_at = u32::try_from(DOS_HEADER + ps.len()).map_err(|_| big())?;
let tiff_len = u32::try_from(tiff.len()).map_err(|_| big())?;
tiff_at.checked_add(tiff_len).ok_or_else(big)?;
let mut out = Vec::with_capacity(DOS_HEADER + ps.len() + tiff.len());
out.extend(DOS_MAGIC);
out.extend((DOS_HEADER as u32).to_le_bytes());
out.extend(ps_len.to_le_bytes());
// No metafile preview.
out.extend(0u32.to_le_bytes());
out.extend(0u32.to_le_bytes());
out.extend(tiff_at.to_le_bytes());
out.extend(tiff_len.to_le_bytes());
// No checksum.
out.extend(0xFFFFu16.to_le_bytes());
out.extend(ps);
out.extend(tiff);
Ok(out)
craft_eps::wrap(ps, Some(tiff), None).map_err(|e| e.to_string())
}
/// The sections of an EPS file: its PostScript and its TIFF preview (binary header), or the whole
/// file as PostScript. `None` when a binary header points outside the file.
pub fn sections(bytes: &[u8]) -> Option<(&[u8], Option<&[u8]>)> {
if !bytes.starts_with(&DOS_MAGIC) {
return Some((bytes, None));
}
let word = |at: usize| bytes.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(|b| u32::from_le_bytes(b) as usize);
let part = |at: usize| {
let (start, len) = (word(at)?, word(at + 4)?);
bytes.get(start..start.checked_add(len)?)
};
let ps = part(4)?;
let tiff = match word(24) {
Some(0) | None => None,
Some(_) => Some(part(20)?),
};
Some((ps, tiff))
let s = craft_eps::sections(bytes).ok()?;
Some((s.postscript, s.tiff))
}
/// The Windows metafile preview behind an EPS file's binary header, if it has one.
pub fn metafile_preview(bytes: &[u8]) -> Option<&[u8]> {
if !bytes.starts_with(&DOS_MAGIC) {
return None;
}
let word = |at: usize| bytes.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(|b| u32::from_le_bytes(b) as usize);
let (start, len) = (word(12)?, word(16)?);
if start == 0 || len == 0 {
return None;
}
bytes.get(start..start.checked_add(len)?)
craft_eps::sections(bytes).ok()?.metafile
}
/// The native document an EPS file written by [`export`] carries, if any.
+2 -92
View File
@@ -21,9 +21,6 @@ VCdict begin
end
";
/// Longest line of encoded data (DSC readers take up to 255 characters).
const LINE: usize = 76;
/// `v` as PostScript writes it: at most four decimals, no trailing zeros (0 when not finite).
pub(crate) fn num(v: f64) -> String {
let mut s = String::new();
@@ -180,54 +177,7 @@ pub(crate) fn clip_op(rule: FillRule) -> &'static str {
/// `bytes` in ASCII85 with its `~>` end, in lines of about [`LINE`] characters, none starting
/// with `%` (DSC readers would take it for a comment).
pub(crate) fn ascii85(bytes: &[u8]) -> String {
let mut raw = String::with_capacity(bytes.len() * 5 / 4 + 8);
let (chunks, rest) = bytes.as_chunks::<4>();
for c in chunks {
let v = u32::from_be_bytes(*c);
if v == 0 {
raw.push('z');
} else {
push85(&mut raw, v, 5);
}
}
if !rest.is_empty() {
let mut c = [0u8; 4];
for (d, s) in c.iter_mut().zip(rest) {
*d = *s;
}
push85(&mut raw, u32::from_be_bytes(c), rest.len() + 1);
}
raw.push_str("~>");
let mut out = String::with_capacity(raw.len() + raw.len() / LINE + 2);
if raw.starts_with('%') {
// Whitespace is ignored by readers, and keeps the first line from starting with `%`.
out.push(' ');
}
let mut col = 0;
for ch in raw.chars() {
if col >= LINE && ch != '%' {
out.push('\n');
col = 0;
}
out.push(ch);
col += 1;
}
out.push('\n');
out
}
/// The first `n` base-85 digits of `v`.
fn push85(s: &mut String, mut v: u32, n: usize) {
let mut d = [0u8; 5];
for slot in d.iter_mut().rev() {
*slot = (v % 85) as u8 + b'!';
v /= 85;
}
for b in d.iter().take(n) {
s.push(char::from(*b));
}
}
pub(crate) use craft_eps::ascii85::encode as ascii85;
/// Most bytes [`ascii85_decode`] makes: what one filter or data section may hold.
pub(crate) const MAX_ASCII85: usize = 1 << 28;
@@ -241,47 +191,7 @@ pub(crate) fn ascii85_decode(text: &str) -> Option<Vec<u8>> {
/// [`ascii85_decode`] of at most `max` bytes: `z` is four bytes for one, so the length of the
/// text doesn't bound what it becomes (#1715).
pub(crate) fn ascii85_decode_within(text: &str, max: usize) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity((text.len() / 5 * 4).min(max));
let mut group = [0u8; 5];
let mut n = 0;
let mut chars = text.bytes().filter(|b| !b.is_ascii_whitespace()).peekable();
while let Some(b) = chars.next() {
if out.len() > max {
return None;
}
match b {
b'~' => {
if chars.next() != Some(b'>') {
return None;
}
if n == 1 {
return None;
}
if n > 1 {
let padded: Vec<u8> = group.iter().take(n).copied().chain(std::iter::repeat(b'u')).take(5).collect();
let v = value85(&padded)?;
out.extend(v.to_be_bytes().iter().take(n - 1));
}
return (out.len() <= max).then_some(out);
}
b'z' if n == 0 => out.extend([0; 4]),
b'!'..=b'u' => {
*group.get_mut(n)? = b;
n += 1;
if n == 5 {
out.extend(value85(&group)?.to_be_bytes());
n = 0;
}
}
_ => return None,
}
}
None
}
/// The value of five base-85 digits; `None` past `u32::MAX`.
fn value85(digits: &[u8]) -> Option<u32> {
digits.iter().try_fold(0u32, |acc, d| acc.checked_mul(85)?.checked_add(u32::from(d.checked_sub(b'!')?)))
craft_eps::ascii85::decode(text.as_bytes(), max)
}
/// Run-length encoding (PackBits: what PostScript's `RunLengthDecode` reads), shared with TIFF.
File diff suppressed because one or more lines are too long
+23 -9
View File
@@ -4,7 +4,7 @@ use super::entry::{
UNNAMED_CHARACTERS_NOTE, max_objects,
};
use super::reshaped;
use super::state::{Builder, Frame, FrameKind, GlyphRun, Saved, bounds, grouped, line_width, mean_scale, paints, round3, stroke_layer};
use super::state::{Builder, Frame, FrameKind, GlyphRun, Saved, bounds, grouped, line_width, mean_scale, paints, round3, same_stroke, stroke_layer};
use super::{
Affine, Appearance, AppearanceItem, Arc, BezPath, BfString, BlendMode, CacheKey, Color, Colors, Families, FillLayer, FillRule, FunctionBudget,
FunctionPaint, HashMap, HashSet, ImageBlob, ImageObject, Knockout, Look, MaskSpec, MaskType, Native, Node, NodeId, NodeKind, OpacityMask, Paint,
@@ -445,15 +445,23 @@ impl<'p> Builder<'p> {
if let Some((t, opacity, facts)) = line.finish() {
if checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink) {
outlined = true;
if self.mask.is_some() {
self.flush_glyphs();
self.flush_masked();
}
for g in glyphs {
let same = self.glyphs.as_ref().is_some_and(|r| {
r.paint == g.paint
&& r.opacity == g.opacity
&& r.overprint == g.overprint
&& r.stroke.is_some() == g.stroke.is_some()
&& r.stroke.as_ref().map(|s| s.line_width) == g.stroke.as_ref().map(|s| s.line_width)
&& (r.scale - g.scale).abs() < 1e-9
});
// Glyphs the file fills one by one composite where they overlap: only opaque
// ones, drawn alike down to the stroke, and not under a soft mask (which
// would be applied once to all of them), share a path.
let same = g.opacity >= 0.999
&& self.mask.is_none()
&& self.glyphs.as_ref().is_some_and(|r| {
r.paint == g.paint
&& r.opacity == g.opacity
&& r.overprint == g.overprint
&& same_stroke(r.stroke.as_ref(), g.stroke.as_ref())
&& (r.scale - g.scale).abs() < 1e-9
});
match &mut self.glyphs {
Some(r) if same => r.path.extend(g.path.iter()),
_ => {
@@ -461,6 +469,12 @@ impl<'p> Builder<'p> {
self.glyphs = Some(g);
}
}
// Under a soft mask each glyph is masked on its own: the art queued for the
// mask is drained at each glyph, or one group of them all takes it once.
if self.mask.is_some() {
self.flush_glyphs();
self.flush_masked();
}
}
self.warn(RESHAPED_TEXT_NOTE);
} else {
+17
View File
@@ -235,6 +235,23 @@ pub(super) fn line_width(p: &StrokeProps, scale: f64) -> f64 {
if p.line_width == 0.0 { HAIRLINE } else { p.line_width as f64 * scale }
}
/// Do strokes `a` and `b` draw alike: both unstroked, or the same width, caps, joins, miter limit
/// and dashes ([`stroke_layer`] takes all of them)?
pub(super) fn same_stroke(a: Option<&StrokeProps>, b: Option<&StrokeProps>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => {
a.line_width == b.line_width
&& a.line_cap == b.line_cap
&& a.line_join == b.line_join
&& a.miter_limit == b.miter_limit
&& a.dash_array == b.dash_array
&& a.dash_offset == b.dash_offset
}
_ => false,
}
}
pub(super) fn stroke_layer(paint: Paint, opacity: f32, p: &StrokeProps, scale: f64) -> StrokeLayer {
let mut st = StrokeLayer::new(paint, line_width(p, scale));
st.opacity = opacity;
+105 -4
View File
@@ -5,6 +5,7 @@
//! ([`vectorcraft_text::test_fonts::matra_font`]): Ka draws Source Sans 3's `a` and the vowel sign
//! I, set before its consonant, draws its `i`.
use kurbo::{Rect, Shape};
use vectorcraft_doc::{Document, NodeKind};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
use vectorcraft_text::FontDb;
@@ -29,6 +30,14 @@ fn glyph(c: char) -> (u32, f64) {
/// and a ToUnicode map naming each glyph's character. `sign_width`: the advance the file gives
/// the vowel sign, in thousandths of an em (`None`: the font's).
fn page(drawn: &[char], sign_width: Option<f64>) -> Vec<u8> {
page_with(|id| format!("[{}] TJ", drawn.iter().map(|&c| id(c)).collect::<String>()), "", &[], sign_width)
}
/// [`page`] showing glyphs with the text operators `ops` makes (after the position of the first
/// glyph) from a function giving a character's glyph id in hex, and `extra` more resources: a
/// graphics state, to set between glyphs or before them, with `objects` it refers to (the first
/// is object `first_extra(1) + 4`).
fn page_with(ops: impl Fn(&dyn Fn(char) -> String) -> String, extra: &str, objects: &[String], sign_width: Option<f64>) -> Vec<u8> {
FontDb::global().add_font(matra_font().expect("the test font builds"));
let program = matra_font().unwrap();
let hex: String = program.iter().map(|b| format!("{b:02X}")).collect::<String>() + ">";
@@ -55,14 +64,13 @@ fn page(drawn: &[char], sign_width: Option<f64>) -> Vec<u8> {
),
),
];
let refs: Vec<&str> = objs.iter().map(String::as_str).collect();
let refs: Vec<&str> = objs.iter().chain(objects).map(String::as_str).collect();
let resources = format!(
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /MatratestSans-Regular /Encoding /Identity-H /DescendantFonts [{} 0 R] /ToUnicode {} 0 R >> >>",
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /MatratestSans-Regular /Encoding /Identity-H /DescendantFonts [{} 0 R] /ToUnicode {} 0 R >> >> {extra}",
n + 2,
n + 3
);
let shown: String = drawn.iter().map(|&c| format!("{:04X}", glyph(c).0)).collect();
let content = format!("BT /F1 40 Tf 20 100 Td <{shown}> Tj ET");
let content = format!("BT /F1 40 Tf 20 100 Td {} ET", ops(&|c| format!("<{:04X}>", glyph(c).0)));
pdf_with(&[PdfPage { resources, ..PdfPage::new(300.0, 200.0, &content) }], &refs, None)
}
@@ -117,3 +125,96 @@ fn a_mark_without_an_advance_stays_with_its_line() {
assert_eq!(texts(&report.document), [""; 0], "the mark is no type of its own");
assert_eq!(outlines(&report.document), 1, "both glyphs, as one path");
}
/// The file's glyphs are outlines of one path when drawn alike, and a path each when a stroke
/// property other than the width (here the dash) differs between them: the first glyph's would
/// otherwise be drawn on all.
#[test]
fn outlined_glyphs_stroked_differently_stay_apart() {
// Stroked (`1 Tr`) at the same width, one glyph solid and the next dashed.
let alike = page_with(|id| format!("1 Tr 2 w {} Tj {} Tj {} Tj", id(KA), id(SIGN_I), id(KA)), "", &[], None);
let apart = page_with(|id| format!("1 Tr 2 w {} Tj [3 2] 0 d {} Tj [] 0 d {} Tj", id(KA), id(SIGN_I), id(KA)), "", &[], None);
assert_eq!(outlines(&open(&alike).document), 1, "drawn alike: one path");
assert_eq!(outlines(&open(&apart).document), 3, "solid, dashed, solid: a path each");
}
/// Translucent glyphs the file fills one by one composite where they overlap, which one fill of
/// their joined outlines does not do: each keeps a path of its own.
#[test]
fn outlined_translucent_glyphs_stay_apart() {
let bytes = page_with(|id| format!("/G gs {} Tj {} Tj {} Tj", id(KA), id(SIGN_I), id(KA)), "/ExtGState << /G << /ca 0.5 >> >>", &[], None);
let report = open(&bytes);
assert_eq!(texts(&report.document), [""; 0]);
assert_eq!(outlines(&report.document), 3, "a path each");
}
/// Glyphs the file draws under a soft mask are not joined into one path: the mask would be applied
/// once to the whole, where the file applies it to each glyph.
#[test]
fn outlined_glyphs_under_a_soft_mask_stay_apart() {
// A luminosity mask (object `first_extra(1) + 4`) of mid gray over the page.
let group = stream("/Type /XObject /Subtype /Form /BBox [0 0 300 200] /Group << /S /Transparency /CS /DeviceGray >>", "0.5 g 0 0 300 200 re f");
let mask = format!("/ExtGState << /M << /SMask << /S /Luminosity /G {} 0 R >> >> >>", first_extra(1) + 4);
let bytes = page_with(|id| format!("/M gs {} Tj {} Tj {} Tj", id(KA), id(SIGN_I), id(KA)), &mask, &[group], None);
let report = open(&bytes);
assert_eq!(texts(&report.document), [""; 0]);
assert_eq!(outlines(&report.document), 3, "a path each");
}
/// What the glyph outlines of `d` draw: how many path elements, and the box round them all.
fn outline_geometry(d: &Document) -> (usize, Rect) {
let (mut elements, mut bounds) = (0, None::<Rect>);
d.walk(|n| {
if is_glyph_outlines(n)
&& let Some(p) = n.path_data()
{
let path = p.to_bezpath();
elements += path.elements().len();
let b = path.bounding_box();
bounds = Some(bounds.map_or(b, |u| u.union(b)));
}
});
(elements, bounds.unwrap_or(Rect::ZERO))
}
/// A line kept as outlines draws the glyphs where they are drawn when the file is opened as
/// outlines: none dropped or moved.
#[test]
fn kept_glyphs_are_where_the_file_draws_them() {
for (drawn, sign_width) in [(vec![KA, SIGN_I, KA], None), (vec![KA, SIGN_I], Some(0.0))] {
let bytes = page(&drawn, sign_width);
let kept = open(&bytes);
let all = import_with_report(&bytes, &ImportOptions { text_as: TextAs::Outlines, ..Default::default() }).unwrap();
assert_eq!(texts(&kept.document), [""; 0], "the line is kept as outlines");
let (kept, all) = (outline_geometry(&kept.document), outline_geometry(&all.document));
assert!(all.0 > 0, "the glyphs have outlines");
assert_eq!(kept.0, all.0, "every outline element is kept");
for (a, b) in [(kept.1.x0, all.1.x0), (kept.1.y0, all.1.y0), (kept.1.x1, all.1.x1), (kept.1.y1, all.1.y1)] {
assert!((a - b).abs() < 1e-6, "{:?} vs {:?}", kept.1, all.1);
}
}
}
/// How many glyph outlines carry a soft mask of their own.
fn masked_outlines(d: &Document) -> usize {
let mut n = 0;
d.walk(|node| n += usize::from(is_glyph_outlines(node) && node.extras().mask.is_some()));
n
}
/// A mask that isn't constant (dark on the left, light on the right) is a mask of its own on each
/// glyph, not one on a group of them: glyphs that overlap composite one by one, as the file draws
/// them.
#[test]
fn outlined_glyphs_under_a_varying_soft_mask_are_masked_one_by_one() {
let group = stream(
"/Type /XObject /Subtype /Form /BBox [0 0 300 200] /Group << /S /Transparency /CS /DeviceGray >>",
"0.2 g 0 0 150 200 re f 0.9 g 150 0 150 200 re f",
);
let mask = format!("/ExtGState << /M << /SMask << /S /Luminosity /G {} 0 R >> >> >>", first_extra(1) + 4);
let bytes = page_with(|id| format!("/M gs {} Tj {} Tj {} Tj", id(KA), id(SIGN_I), id(KA)), &mask, &[group], None);
let report = open(&bytes);
assert_eq!(texts(&report.document), [""; 0]);
assert_eq!(outlines(&report.document), 3, "a path each");
assert_eq!(masked_outlines(&report.document), 3, "each path has its own mask");
}
+24 -1
View File
@@ -107,7 +107,12 @@ impl BrushCache {
vectorcraft_brush::serde_json::to_string(v).unwrap_or_default().hash(&mut h);
h.finish()
});
self.lib = vectorcraft_brush::library(doc).into_iter().map(|b| (b.name.clone(), Arc::new(b))).collect();
// Of two brushes with one name, a stroke that names it draws with the first, as
// `vectorcraft_brush::find` and the exports take it.
self.lib.clear();
for b in vectorcraft_brush::library(doc) {
self.lib.entry(b.name.clone()).or_insert_with(|| Arc::new(b));
}
}
/// [`Self::key`] for the brush library `doc` holds (checked once a frame, `stamp`).
@@ -388,6 +393,24 @@ mod tests {
assert!(!dark(a.pixel(100, 58)) && dark(b.pixel(100, 58)));
}
/// Of two brushes with one name, a stroke that names it draws with the first.
#[test]
fn a_stroke_draws_with_the_first_of_two_brushes_with_its_name() {
use vectorcraft_brush::{Brush, BrushKind, Calligraphic};
let nib = |size: f64| Brush { name: "Twin".into(), kind: BrushKind::Calligraphic(Calligraphic { size, ..Default::default() }) };
let doc = |lib: &[Brush]| {
let mut d = doc_with_line(Some("Twin"), 1.0);
vectorcraft_brush::store(&mut d, lib);
d
};
let (thin, wide) = (nib(1.0), nib(20.0));
let first = render(&mut Renderer::new(), &doc(std::slice::from_ref(&thin))).pixels;
let second = render(&mut Renderer::new(), &doc(std::slice::from_ref(&wide))).pixels;
assert_ne!(first, second, "the two nibs paint differently");
let both = render(&mut Renderer::new(), &doc(&[thin, wide])).pixels;
assert!(both == first, "the stroke draws with the first brush named Twin");
}
#[test]
fn stained_symbol_instance() {
let mut d = Document::new(100.0, 100.0);
+1
View File
@@ -9,6 +9,7 @@ description = "VectorCraft SVG import and export"
workspace = true
[dependencies]
craft-svg = { workspace = true }
# Which paths stored in documents may be opened.
craft-docpath = { workspace = true }
vectorcraft-geom = { workspace = true }
+3 -83
View File
@@ -2,90 +2,10 @@
//! replaces every `&name;` with the entity's text as it reads, with no total limit: a short file
//! that repeats a large entity in an attribute allocates far more than it holds.
use std::collections::HashMap;
/// The most text the references to entities may expand to in all (bytes).
const MAX_EXPANDED: usize = 16 << 20;
/// How deep entities that refer to entities are followed (the reader's own limit is lower).
const MAX_NESTING: u32 = 16;
/// The longest entity name a reference is looked for with ([`references`]).
const MAX_NAME: usize = 256;
/// The internal general entities declared in `svg`: name → every value declared for it. Text that
/// only looks like a declaration (in a comment, or in another entity's value) is kept too: the
/// largest value counts, so it can only make the estimate larger.
fn declared(svg: &str) -> HashMap<&str, Vec<&str>> {
let mut map: HashMap<&str, Vec<&str>> = HashMap::new();
for (at, _) in svg.match_indices("<!ENTITY") {
let rest = svg.get(at + "<!ENTITY".len()..).unwrap_or("").trim_start();
// A parameter entity (`%`) isn't referenced as `&name;`.
if rest.starts_with('%') {
continue;
}
let Some(end) = rest.find(char::is_whitespace) else { continue };
let (name, rest) = rest.split_at(end);
let rest = rest.trim_start();
let Some(quote) = rest.chars().next().filter(|q| matches!(q, '"' | '\'')) else { continue };
let Some(value) = rest.get(1..).and_then(|r| r.split_once(quote)).map(|(v, _)| v) else { continue };
map.entry(name).or_default().push(value);
}
map
}
/// The names of the `&name;` references in `text`.
fn references(text: &str) -> impl Iterator<Item = &str> {
text.match_indices('&').filter_map(|(at, _)| {
let rest = text.get(at + 1..)?;
// Look no further than the longest name: a file of `&`s without `;` would be read quadratically.
let end = rest.bytes().take(MAX_NAME + 1).position(|b| b == b';')?;
let name = rest.get(..end)?;
(!name.is_empty() && name.len() <= MAX_NAME && !name.starts_with('#') && !name.contains(char::is_whitespace)).then_some(name)
})
}
/// What entity `name` expands to (bytes), references in its value followed.
fn expanded<'a>(name: &'a str, entities: &HashMap<&'a str, Vec<&'a str>>, memo: &mut HashMap<&'a str, usize>, depth: u32) -> usize {
if let Some(n) = memo.get(name) {
return *n;
}
let Some(values) = entities.get(name) else { return 0 };
if depth >= MAX_NESTING {
return usize::MAX;
}
let mut most = 0usize;
for value in values {
let mut total = value.len();
for inner in references(value) {
total = total.saturating_add(expanded(inner, entities, memo, depth + 1));
}
most = most.max(total);
}
memo.insert(name, most);
most
}
/// Whether the references to the entities `svg` declares expand to more than [`MAX_EXPANDED`]
/// Whether the references to the entities `svg` declares expand to more than the limit
/// bytes in all. False for a file that declares none.
pub(crate) fn expansion_too_large(svg: &str) -> bool {
let entities = declared(svg);
if entities.is_empty() {
return false;
}
// A reference to a longer name isn't looked for: refuse such a declaration instead.
if entities.keys().any(|name| name.len() > MAX_NAME) {
return true;
}
let mut memo = HashMap::new();
let mut total = 0usize;
for name in references(svg) {
total = total.saturating_add(expanded(name, &entities, &mut memo, 0));
if total > MAX_EXPANDED {
return true;
}
}
false
craft_svg::guard::entities_expand_past(svg, craft_svg::guard::MAX_ENTITY_EXPANSION)
}
#[cfg(test)]
@@ -118,7 +38,7 @@ mod tests {
assert!(expansion_too_large(&commented));
let in_value = format!("<!DOCTYPE svg [<!ENTITY c \"<!ENTITY a 'x'>\"><!ENTITY a \"{big}\">]><svg id=\"{refs}\"/>");
assert!(expansion_too_large(&in_value));
let long = "n".repeat(MAX_NAME + 1);
let long = "n".repeat(257);
let long_name = format!("<!DOCTYPE svg [<!ENTITY {long} \"x\">]><svg id=\"&{long};\"/>");
assert!(expansion_too_large(&long_name));
}
+19 -64
View File
@@ -458,21 +458,17 @@ pub(crate) fn body_hash(parts: &[&str]) -> String {
/// Does `bytes` start like gzip data (an SVGZ file)?
pub fn is_svgz(bytes: &[u8]) -> bool {
bytes.starts_with(&[0x1f, 0x8b])
craft_svg::sniff::is_svgz(bytes)
}
/// Compress SVG text as SVGZ (gzip).
pub fn compress(svg: &str) -> Vec<u8> {
compress_bytes(svg.as_bytes())
craft_svg::svgz::compress(svg.as_bytes())
}
/// Compress an SVG file (in any encoding, see [`Output::bytes`]) as SVGZ (gzip).
pub fn compress_bytes(svg: &[u8]) -> Vec<u8> {
use std::io::Write as _;
let mut gz = flate2::write::GzEncoder::new(Vec::with_capacity(svg.len() / 4), flate2::Compression::default());
// Writing to a Vec cannot fail.
let _ = gz.write_all(svg);
gz.finish().unwrap_or_default()
craft_svg::svgz::compress(svg)
}
/// Most bytes an SVGZ file may unpack to (a guard against decompression bombs).
@@ -487,29 +483,26 @@ pub fn text_of(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>, SvgError> {
/// [`text_of`], SVGZ bytes unpacking within what `unpacked`, the bytes SVGZ data unpacked to so
/// far, leaves of [`MAX_SVGZ`]. What they unpack to is added to it, whether or not it decodes.
pub(crate) fn text_within<'a>(bytes: &'a [u8], unpacked: &std::sync::atomic::AtomicU64) -> Result<std::borrow::Cow<'a, str>, SvgError> {
use std::io::Read as _;
use std::sync::atomic::Ordering;
if !is_svgz(bytes) {
return match decode(bytes)? {
Decoded::Utf8(skip) => std::str::from_utf8(bytes.get(skip..).unwrap_or_default()).map(Into::into).map_err(|_| not_utf8()),
Decoded::Text(t) => Ok(t.into()),
};
return craft_svg::svgz::decode(bytes).map_err(|_| not_utf8());
}
let most = MAX_SVGZ.saturating_sub(unpacked.load(Ordering::Relaxed));
let mut raw = Vec::new();
let read = flate2::read::GzDecoder::new(bytes).take(most.saturating_add(1)).read_to_end(&mut raw);
// Read before a failure is kept: it was unpacked too.
unpacked.fetch_add(raw.len() as u64, Ordering::Relaxed);
read.map_err(|e| SvgError::Parse(format!("not a valid SVGZ file: {e}")))?;
if raw.len() as u64 > most {
return Err(SvgError::TooBig(format!("the SVGZ file unpacks to more than {} MB", most >> 20)));
}
match decode(&raw)? {
Decoded::Utf8(skip) => {
raw.drain(..skip);
String::from_utf8(raw).map(Into::into).map_err(|_| not_utf8())
let most = usize::try_from(MAX_SVGZ.saturating_sub(unpacked.load(Ordering::Relaxed))).unwrap_or(usize::MAX);
match craft_svg::svgz::inflate(bytes, most) {
Ok(raw) => {
unpacked.fetch_add(raw.len() as u64, Ordering::Relaxed);
craft_svg::svgz::decode(&raw)
.map(|t| std::borrow::Cow::Owned(t.into_owned()))
.map_err(|_| not_utf8())
}
Decoded::Text(t) => Ok(t.into()),
Err(craft_svg::svgz::Error::TooLarge(_)) => {
Err(SvgError::TooBig(format!("the SVGZ file unpacks to more than {} MB", most >> 20)))
}
Err(craft_svg::svgz::Error::Corrupt(e)) => {
Err(SvgError::Parse(format!("not a valid SVGZ file: {e}")))
}
Err(craft_svg::svgz::Error::Encoding) => Err(not_utf8()),
Err(e) => Err(SvgError::Parse(e.to_string())),
}
}
@@ -517,44 +510,6 @@ fn not_utf8() -> SvgError {
SvgError::Parse("SVG is not UTF-8, UTF-16 or ISO 8859-1".into())
}
/// How SVG bytes are read.
enum Decoded {
/// UTF-8 after this many bytes (a byte order mark).
Utf8(usize),
/// Text decoded from another encoding.
Text(String),
}
/// The encoding of SVG bytes: a byte order mark (UTF-8 or UTF-16), else the XML declaration's
/// (ISO 8859-1 by its names; anything else is read as UTF-8).
fn decode(bytes: &[u8]) -> Result<Decoded, SvgError> {
let utf16 = |rest: &[u8], unit: fn([u8; 2]) -> u16| {
let (units, odd) = rest.as_chunks::<2>();
if !odd.is_empty() {
return Err(not_utf8());
}
char::decode_utf16(units.iter().map(|u| unit(*u))).collect::<Result<String, _>>().map(Decoded::Text).map_err(|_| not_utf8())
};
match bytes {
[0xef, 0xbb, 0xbf, ..] => Ok(Decoded::Utf8(3)),
[0xfe, 0xff, rest @ ..] => utf16(rest, u16::from_be_bytes),
[0xff, 0xfe, rest @ ..] => utf16(rest, u16::from_le_bytes),
_ if declared_latin1(bytes) => Ok(Decoded::Text(bytes.iter().map(|b| char::from(*b)).collect())),
_ => Ok(Decoded::Utf8(0)),
}
}
/// Does the XML declaration at the start of `bytes` name ISO 8859-1?
fn declared_latin1(bytes: &[u8]) -> bool {
let head = bytes.get(..bytes.len().min(200)).unwrap_or_default();
let Some(decl) = head.strip_prefix(b"<?xml").and_then(|d| d.split(|b| *b == b'>').next()) else { return false };
let decl = String::from_utf8_lossy(decl).to_ascii_lowercase();
let Some(at) = decl.find("encoding") else { return false };
let value = decl.get(at + "encoding".len()..).unwrap_or("").trim_start().trim_start_matches('=').trim_start();
let name = value.trim_start_matches(['"', '\'']).split(['"', '\'', ' ', '?']).next().unwrap_or("");
matches!(name, "iso-8859-1" | "iso8859-1" | "iso_8859-1" | "latin1" | "latin-1" | "l1")
}
/// Import an SVG document.
pub fn import(svg: &str) -> Result<Document, SvgError> {
import_with_report(svg).map(|(d, _)| d)
+166 -35
View File
@@ -203,18 +203,78 @@ const MAX_EDGE_PAIRS: usize = 1 << 14;
/// within the band and its x range there.
type Slant = (Point, Point, (f64, f64), (f64, f64));
/// The line through two points.
type Line = (Point, Point);
/// The x of the line through `p` and `q` (not horizontal) at `y`.
fn line_x(p: Point, q: Point, y: f64) -> f64 {
p.x + (y - p.y) / (q.y - p.y) * (q.x - p.x)
}
/// The x ranges within a band at which the edges `slants` bound the frame. Edges that lie along one
/// line and overlap there (contours that meet along an edge, however each one divides it) count by
/// parity: a stretch of the line that an even number of them cover has the frame on both sides.
/// At most [`MAX_EDGE_PAIRS`] pairs are compared; edges left unpaired still count as boundaries,
/// which can make a line shorter at a seam but never puts it outside the frame. The flag is false
/// when the limit left edges unpaired.
fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
/// `a + b` as its rounded value and the rounding error, which sum to it exactly.
fn two_sum(a: f64, b: f64) -> (f64, f64) {
let s = a + b;
let v = s - a;
(s, (a - (s - v)) + (b - v))
}
/// `a * b` as its rounded value and the rounding error, which sum to it exactly (unless the error
/// is too small for a normal f64).
fn two_product(a: f64, b: f64) -> (f64, f64) {
let p = a * b;
(p, a.mul_add(b, -p))
}
/// Does `r` lie exactly on the line through `p` and `q`? The cross product `(q - p) × (r - p)` is
/// summed without rounding: two points apart by a single unit in the last place are never on one
/// line.
fn on_line_exactly(p: Point, q: Point, r: Point) -> bool {
let left = (q.x - p.x) * (r.y - p.y);
let right = (q.y - p.y) * (r.x - p.x);
// Rounding moves the product difference by less than this, so a larger one is not zero.
if (left - right).abs() > 4.0 * f64::EPSILON * (left.abs() + right.abs()) {
return false;
}
let (dx, dy, ex, ey) = (two_sum(q.x, -p.x), two_sum(q.y, -p.y), two_sum(r.x, -p.x), two_sum(r.y, -p.y));
let mut terms = [0.0; 16];
for (k, (a, b)) in [dx.0, dx.1].into_iter().flat_map(|a| [ey.0, ey.1].map(|b| (a, b))).enumerate() {
(terms[2 * k], terms[2 * k + 1]) = two_product(a, b);
}
for (k, (a, b)) in [dy.0, dy.1].into_iter().flat_map(|a| [ex.0, ex.1].map(|b| (a, b))).enumerate() {
(terms[8 + 2 * k], terms[9 + 2 * k]) = two_product(-a, b);
}
// The terms added into an expansion: parts of increasing size that don't overlap, whose sum is
// the exact sum of the terms and which keeps no zero part, so it is empty only when that sum is
// zero.
let (mut parts, mut len) = ([0.0; 16], 0);
for t in terms {
let (mut sum, mut kept) = (t, 0);
for i in 0..len {
let (s, err) = two_sum(sum, parts[i]);
if err != 0.0 {
parts[kept] = err;
kept += 1;
}
sum = s;
}
if sum != 0.0 {
parts[kept] = sum;
kept += 1;
}
len = kept;
}
len == 0
}
/// The x ranges within a band at which the edges `slants` bound the frame, and the line each edge
/// lies along (the same two points for every edge it is paired with). Edges that lie exactly along
/// one line and overlap there (contours that meet along an edge, however each one divides it) count
/// by parity: a stretch of the line that an even number of them cover has the frame on both sides.
/// Edges that are parallel but apart, however little, are not paired. At most [`MAX_EDGE_PAIRS`]
/// pairs are compared; edges left unpaired still count as boundaries, which can make a line shorter
/// at a seam but never puts it outside the frame. The flag is false when the limit left edges
/// unpaired. `slants` is reordered, and the lines follow its new order.
fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool, Vec<Line>) {
fn root(parent: &mut [usize], mut i: usize) -> usize {
while parent[i] != i {
parent[i] = parent[parent[i]];
@@ -227,17 +287,16 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
let mut parent: Vec<usize> = (0..slants.len()).collect();
let mut pairs = 0;
'edges: for (i, &(p, q, _, (_, x1))) in slants.iter().enumerate() {
// Ends on the line up to rounding (a few units in the last place of the coordinates)
// count as on it.
// The x ranges of edges along one line, each found from its own ends, can differ by
// rounding (a few units in the last place of the coordinates).
let scale = p.x.abs().max(p.y.abs()).max(q.x.abs()).max(q.y.abs()).max(1.0);
let (d, tol) = (q - p, 4.0 * f64::EPSILON * scale);
let on_line = |r: Point| d.cross(r - p).abs() <= tol * d.hypot();
let tol = 4.0 * f64::EPSILON * scale;
for (j, &(r, s, ..)) in slants.iter().enumerate().skip(i + 1).take_while(|(_, o)| o.3.0 <= x1 + tol) {
pairs += 1;
if pairs > MAX_EDGE_PAIRS {
break 'edges;
}
if on_line(r) && on_line(s) {
if on_line_exactly(p, q, r) && on_line_exactly(p, q, s) {
let (a, b) = (root(&mut parent, i), root(&mut parent, j));
parent[a] = b;
}
@@ -246,6 +305,7 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
let mut groups: Vec<(usize, usize)> = (0..slants.len()).map(|i| (root(&mut parent, i), i)).collect();
groups.sort_unstable();
let mut out = Vec::new();
let mut lines: Vec<Line> = slants.iter().map(|s| (s.0, s.1)).collect();
for run in groups.chunk_by(|a, b| a.0 == b.0) {
if let [(_, i)] = run {
out.push(slants[*i].3);
@@ -253,6 +313,9 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
}
// The stretches an odd number of the edges cover: pairs of their sorted y ends.
let (p, q, ..) = slants[run[0].1];
for &(_, i) in run {
lines[i] = (p, q);
}
let mut ys: Vec<f64> = run.iter().flat_map(|&(_, i)| [slants[i].2.0, slants[i].2.1]).collect();
ys.sort_by(f64::total_cmp);
for c in ys.as_chunks::<2>().0.iter().filter(|c| c[1] > c[0]) {
@@ -260,7 +323,7 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
out.push((s.min(t), s.max(t)));
}
}
(out, pairs <= MAX_EDGE_PAIRS)
(out, pairs <= MAX_EDGE_PAIRS, lines)
}
/// The most pieces a line's band is cut into to keep it inside an Invert Wrap shape grown by its
@@ -301,29 +364,21 @@ fn band_edges(polys: &[Vec<Point>], top: f64, bottom: f64) -> (Vec<(f64, f64, f6
/// of edges cover).
fn band_intervals(polys: &[Vec<Point>], top: f64, bottom: f64) -> Vec<(f64, f64)> {
let (top, bottom) = (top.min(bottom), top.max(bottom));
// Contours that meet along an edge cross the middle of the band at the same x, up to a few
// units of rounding: the intervals on either side of it join (an edge that bounds the
// shape there is still subtracted below). A vertical edge crosses the middle at its own x with
// no rounding, so a gap at one is never taken for a seam.
let y = (top + bottom) * 0.5;
let mut upright: Vec<f64> = polys
.iter()
.flat_map(|poly| poly.iter().zip(poly.iter().cycle().skip(1)))
.filter(|(a, b)| a.x == b.x && (a.y <= y) != (b.y <= y))
.map(|(a, _)| a.x)
.collect();
upright.sort_by(f64::total_cmp);
let upright = |x: f64| upright.binary_search_by(|v| v.total_cmp(&x)).is_ok();
let mut mid = poly_intervals(polys, y);
let (edges, _, mut xs) = band_boundaries(polys, top, bottom);
// The edges of contours that meet along an edge cross the middle of the band at the same x,
// since each is crossed on the line through the same two points: the intervals on either side
// join there (an edge that bounds the shape there is still subtracted). Intervals with any gap
// between them stay apart.
xs.sort_by(f64::total_cmp);
let mut mid: Vec<(f64, f64)> = xs.as_chunks::<2>().0.iter().map(|c| (c[0], c[1])).collect();
mid.dedup_by(|next, prev| {
let gap = next.0 - prev.1;
let seam = gap <= 8.0 * f64::EPSILON * prev.1.abs().max(next.0.abs()).max(1.0) && (gap <= 0.0 || !(upright(prev.1) || upright(next.0)));
let seam = next.0 <= prev.1;
if seam {
prev.1 = prev.1.max(next.1);
}
seam
});
subtract_intervals(&mid, &band_boundaries(polys, top, bottom).0)
subtract_intervals(&mid, &edges)
}
/// The x at which `polys` (even-odd) is inside somewhere in the band `top..bottom`, sorted and
@@ -336,7 +391,7 @@ fn band_intervals(polys: &[Vec<Point>], top: f64, bottom: f64) -> Vec<(f64, f64)
fn band_cover(polys: &[Vec<Point>], top: f64, bottom: f64, admit: bool) -> Vec<(f64, f64)> {
let (top, bottom) = (top.min(bottom), top.max(bottom));
let mut iv = poly_intervals(polys, (top + bottom) * 0.5);
let (edges, paired) = band_boundaries(polys, top, bottom);
let (edges, paired, _) = band_boundaries(polys, top, bottom);
if paired || !admit {
iv.extend(edges);
}
@@ -366,10 +421,20 @@ fn band_cover_closed(polys: &[Vec<Point>], top: f64, bottom: f64) -> Vec<(f64, f
/// Every x at which an edge of `polys` bounds the shape within the band `top..bottom`
/// (`top <= bottom`), sorted and disjoint, leaving out edges that only touch the top or bottom of
/// the band, stretches of edges that an even number of edges cover, and vertical edges. The flag is
/// false when [`MAX_EDGE_PAIRS`] left edges unpaired, which can only add to the result.
fn band_boundaries(polys: &[Vec<Point>], top: f64, bottom: f64) -> (Vec<(f64, f64)>, bool) {
/// false when [`MAX_EDGE_PAIRS`] left edges unpaired, which can only add to the result. Last, the x
/// at which the edges cross the middle of the band (even-odd, as [`poly_intervals`] finds them),
/// unsorted, each found along the line [`slant_boundaries`] gives its edge.
fn band_boundaries(polys: &[Vec<Point>], top: f64, bottom: f64) -> (Vec<(f64, f64)>, bool, Vec<f64>) {
let (mut flats, mut slants) = band_edges(polys, top, bottom);
let (mut edges, paired) = slant_boundaries(&mut slants);
let (mut edges, paired, lines) = slant_boundaries(&mut slants);
let y = (top + bottom) * 0.5;
let mut xs: Vec<f64> = slants.iter().zip(&lines).filter(|((p, q, ..), _)| p.y <= y && y < q.y).map(|(_, &(p, q))| line_x(p, q, y)).collect();
// When the middle is the band's bottom (a band of no height), the edges that start there cross
// it but are not in the band: they cross it at their lower end.
if y == bottom {
let starts = polys.iter().flat_map(|poly| poly.iter().zip(poly.iter().cycle().skip(1)));
xs.extend(starts.filter(|(a, b)| a.y != b.y && a.y.min(b.y) == y).map(|(a, b)| if a.y < b.y { a.x } else { b.x }));
}
// The x covered by an odd number of the horizontal edges at one height: pairs of their
// sorted ends.
flats.sort_by(|p, q| p.0.total_cmp(&q.0));
@@ -381,7 +446,7 @@ fn band_boundaries(polys: &[Vec<Point>], top: f64, bottom: f64) -> (Vec<(f64, f6
// A vertical edge covers a single x: where it bounds the shape, the band's middle already
// ends at it or an edge of some width meets it, so it is left out (vertical seams join).
edges.retain(|e| e.1 > e.0);
(union_intervals(edges), paired)
(union_intervals(edges), paired, xs)
}
/// The largest magnitude a text wrap offset may have (points), the bound the Text Wrap commands
@@ -895,6 +960,72 @@ fn lines_cross_an_edge_two_contours_share() {
assert_spans(&cells[0].spans(40.0, 60.0), &[(x, x + 50.0), (x + 50.0 + 1e-7, x + 100.0)]);
}
/// Slanted edges of two contours four units in the last place apart, or one, near the edge of the
/// canvas are not one edge: the line stops at each and keeps the gap between them.
#[cfg(test)]
#[test]
fn separate_slanted_contours_keep_a_four_ulp_gap_near_canvas_limit() {
let x = 3_999_000.0;
let ulp = 2f64.powi(-31);
assert_eq!((x + ulp).to_bits(), x.to_bits() + 1);
for gap in [4.0 * ulp, ulp] {
let frame = closed(&[
&[(x - 100.0, 0.0), (x, 0.0), (x + 10.0, 10.0), (x - 90.0, 10.0)],
&[(x + gap, 0.0), (x + 100.0 + gap, 0.0), (x + 110.0 + gap, 10.0), (x + 10.0 + gap, 10.0)],
]);
let cells = Region::cells(&frame, &LayoutOptions::default(), &[]);
let spans = cells[0].spans(1.0, 9.0);
assert_spans(&spans, &[(x - 91.0, x + 1.0), (x + 9.0 + gap, x + 101.0 + gap)]);
assert!(spans[0].1 < spans[1].0, "gap {gap}: {spans:?}");
}
}
/// Contours that share a slanted edge near the edge of the canvas, whole or divided by an anchor
/// exactly on it, hold lines across it. So do contours whose shared edge is divided where the
/// crossing found from the divided edge's own ends rounds to another x than the whole edge's.
#[cfg(test)]
#[test]
fn shared_slanted_edge_still_joins_near_canvas_limit() {
let x = 3_999_000.0;
let left: &[(f64, f64)] = &[(x - 100.0, 0.0), (x, 0.0), (x + 10.0, 10.0), (x - 90.0, 10.0)];
let whole: &[(f64, f64)] = &[(x, 0.0), (x + 100.0, 0.0), (x + 110.0, 10.0), (x + 10.0, 10.0)];
let divided: &[(f64, f64)] = &[(x, 0.0), (x + 100.0, 0.0), (x + 110.0, 10.0), (x + 10.0, 10.0), (x + 2.5, 2.5)];
for right in [whole, divided] {
let cells = Region::cells(&closed(&[left, right]), &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(1.0, 9.0), &[(x - 91.0, x + 101.0)]);
}
// (0.75, 1.75) lies exactly on the edge from (0, 0) to (3, 7).
let left: &[(f64, f64)] = &[(-100.0, 0.0), (0.0, 0.0), (3.0, 7.0), (-97.0, 7.0)];
let right: &[(f64, f64)] = &[(0.0, 0.0), (100.0, 0.0), (103.0, 7.0), (3.0, 7.0), (0.75, 1.75)];
let (top, bottom) = (1.404, 2.404);
let y = (top + bottom) * 0.5;
assert_ne!(line_x(Point::new(0.0, 0.0), Point::new(3.0, 7.0), y), line_x(Point::new(0.75, 1.75), Point::new(3.0, 7.0), y));
let cells = Region::cells(&closed(&[left, right]), &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(top, bottom), &[(-100.0 + 3.0 * bottom / 7.0, 100.0 + 3.0 * top / 7.0)]);
}
/// Area type in two slanted contours four units in the last place apart near the edge of the canvas
/// sets no line across the gap between them.
#[cfg(test)]
#[test]
fn area_type_sets_no_line_across_a_four_ulp_gap_between_slanted_contours() {
let x = 3_999_000.0;
let gap = 4.0 * 2f64.powi(-31);
let frame = closed(&[
&[(x - 200.0, 0.0), (x, 0.0), (x + 100.0, 100.0), (x - 100.0, 100.0)],
&[(x + gap, 0.0), (x + 200.0 + gap, 0.0), (x + 300.0 + gap, 100.0), (x + 100.0 + gap, 100.0)],
]);
let style = vectorcraft_doc::CharStyle { size: 10.0, ..vectorcraft_doc::CharStyle::default() };
let mut t = crate::TextObject::point(Point::ZERO, &"word ".repeat(400), style);
t.kind = vectorcraft_doc::TextKind::Area { frame: PathData::from_bezpath(&frame) };
let laid = crate::layout(crate::FontDb::global(), &t);
assert!(!laid.lines.is_empty());
// Each contour is 200 pt wide at any height; the two together are twice that.
for line in &laid.lines {
assert!(line.x1 - line.x0 < 200.0, "{} to {}", line.x0, line.x1);
}
}
/// A frame of 200 thin slanted strips, whose edges in the band overlap in x far more than
/// [`MAX_EDGE_PAIRS`] times, holds no line in the band (no strip holds a vertical line across it).
#[cfg(test)]
+43 -19
View File
@@ -143,6 +143,38 @@ fn step_swatch(list: &[&Swatch], fill: &Paint, last: Option<usize>, forward: boo
}
}
/// Is no Shift, Alt, Cmd or Ctrl held? The arrows step swatches only then.
fn plain(mods: Mods) -> bool {
!(mods.shift || mods.alt || mods.cmd || mods.ctrl)
}
/// The color swatch the Right (`forward`) or Left arrow key picks for the current `paint`, with its
/// index in [`color_swatches`] (see [`step_swatch`]); None when the document has no color swatch.
fn pick_swatch(doc: &Document, paint: &Paint, last: Option<usize>, forward: bool) -> Option<(usize, String)> {
let list = color_swatches(doc);
step_swatch(&list, paint, last, forward).and_then(|i| Some((i, list.get(i)?.name.clone())))
}
/// The cursor swatch preview for the current `paint` with the pointer at `at`: the swatch before
/// it, `paint` itself (ringed, while it is a solid color) and the swatch after it, side by side above
/// the pointer. With `matched_only`, the swatches beside it show only while `paint` is one of the
/// color swatches; otherwise the last and the first swatch stand beside a color that is none of them.
fn swatch_chips(cx: &ToolContext, at: Point, paint: &Paint, last: Option<usize>, matched_only: bool) -> Vec<Overlay> {
let list = color_swatches(cx.doc);
let rgba = |p: &Paint| match p {
Paint::Solid { color, .. } => Some(color.to_rgba8(1.0)),
_ => None,
};
let beside = !matched_only || swatch_index(&list, paint, last).is_some();
let chip = |forward| beside.then(|| step_swatch(&list, paint, last, forward)).flatten().and_then(|i| rgba(&list.get(i)?.paint));
let (before, after) = (chip(false), chip(true));
let y = at.y - cx.tol(22.0);
[(before, -16.0, false), (rgba(paint), 0.0, true), (after, 16.0, false)]
.into_iter()
.filter_map(|(color, dx, selected)| Some(Overlay::Swatch { p: Point::new(at.x + cx.tol(dx), y), color: color?, selected }))
.collect()
}
/// Shape Builder tool: drag across regions to merge them. Holding Alt (Option) switches to erase
/// mode while it is held: the pointer shows a minus, what a click or drag would delete highlights in
/// red, and the gesture deletes the regions it touches, the pieces of open paths and the edges
@@ -425,20 +457,7 @@ impl ShapeBuilderTool {
/// The cursor swatch preview: the swatch before the current fill, the current fill (ringed)
/// and the swatch after it, side by side above the pointer.
fn swatch_chips(&self, cx: &ToolContext) -> Vec<Overlay> {
let Some(at) = self.at else { return vec![] };
let list = color_swatches(cx.doc);
let fill = &cx.paint.fill;
let rgba = |p: &Paint| match p {
Paint::Solid { color, .. } => Some(color.to_rgba8(1.0)),
_ => None,
};
let chip = |forward| step_swatch(&list, fill, self.picked, forward).and_then(|i| rgba(&list.get(i)?.paint));
let (before, after) = (chip(false), chip(true));
let y = at.y - cx.tol(22.0);
[(before, -16.0, false), (rgba(fill), 0.0, true), (after, 16.0, false)]
.into_iter()
.filter_map(|(color, dx, selected)| Some(Overlay::Swatch { p: Point::new(at.x + cx.tol(dx), y), color: color?, selected }))
.collect()
self.at.map(|at| swatch_chips(cx, at, &cx.paint.fill, self.picked, false)).unwrap_or_default()
}
}
@@ -712,9 +731,15 @@ impl Tool for ShapeBuilderTool {
(self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) || (self.dragging && key == ToolKey::Escape)
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
/// The arrows pick swatches only without modifiers; Shift, Alt and Cmd/Ctrl arrows keep their
/// shortcuts.
fn claims_key_with(&self, cx: &ToolContext, key: ToolKey, mods: Mods) -> bool {
self.claims_key(cx, key) && (key == ToolKey::Escape || plain(mods))
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {
// While a merge is being computed, the arrows leave the current fill it takes as it was.
if !self.claims_key(cx, key) || self.editing() {
if !self.claims_key_with(cx, key, mods) || self.editing() {
return vec![];
}
if key == ToolKey::Escape {
@@ -726,13 +751,12 @@ impl Tool for ShapeBuilderTool {
(self.marquee, self.hover, self.far) = (None, None, false);
return vec![];
}
let list = color_swatches(cx.doc);
let Some((i, s)) = step_swatch(&list, &cx.paint.fill, self.picked, key == ToolKey::Right).and_then(|i| Some((i, list.get(i)?))) else {
let Some((i, name)) = pick_swatch(cx.doc, &cx.paint.fill, self.picked, key == ToolKey::Right) else {
return vec![];
};
self.picked = Some(i);
// The current fill only (no `ids`): the selected art keeps its own.
vec![Action::Exec("paint.setFill".into(), json!({ "swatch": s.name, "ids": [] }))]
vec![Action::Exec("paint.setFill".into(), json!({ "swatch": name, "ids": [] }))]
}
fn options(&self) -> Value {
+77 -8
View File
@@ -3,7 +3,7 @@ use super::lookup::{is_live_paint, live_paint_at, live_paint_at_where, visible_e
use super::map::{HIGHLIGHT_RED, sorted_roots};
use super::{
Action, Arc, BezPath, CLICK_TOL_PX, Cursor, Document, EDGE_NAME, FACE_NAME, FillRule, Mods, Node, NodeId, Overlay, Point, PointerEvent,
PointerKind, Rect, Tool, ToolContext, ToolKey, Value, json, json_ids, path_contains,
PointerKind, Rect, Tool, ToolContext, ToolKey, Value, color_swatches, json, json_ids, path_contains, pick_swatch, plain, swatch_chips,
};
// ---------- Live Paint Bucket ----------
@@ -171,6 +171,14 @@ enum LpPaint {
/// click paints nothing. With Highlight off, the face or edge under the pointer is not
/// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints
/// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper.
///
/// The Left and Right arrow keys without Shift, Alt or Cmd/Ctrl set the active paint (the fill,
/// or the stroke when the Stroke proxy is in front) to the color swatch before or after it in the
/// Swatches panel, wrapping around; from a color that is no swatch, Right picks the first swatch
/// and Left the last. The selected art keeps its paint. With `cursorSwatchPreview` (on), the
/// active paint shows as a chip above the pointer between the swatches before and after it,
/// except during a fill drag or with Alt held; a solid color that is no swatch shows alone, and a
/// paint that is not a solid color shows no chip.
pub struct LivePaintBucketTool {
pub(super) cache: RegionCache,
pub(super) hover: LpHover,
@@ -183,6 +191,11 @@ pub struct LivePaintBucketTool {
highlight: bool,
color: [u8; 3],
width: f64,
/// Cursor Swatch Preview.
preview: bool,
/// The index in [`color_swatches`] of the swatch the arrow keys picked last for the fill and for
/// the stroke.
picked: [Option<usize>; 2],
}
/// Maximum points in one Live Paint fill path chunk.
@@ -200,11 +213,24 @@ impl Default for LivePaintBucketTool {
highlight: true,
color: HIGHLIGHT_RED,
width: LP_BUCKET_WIDTH,
preview: true,
picked: [None; 2],
}
}
}
impl LivePaintBucketTool {
/// The active paint the arrow keys step and the preview shows: the fill, or the stroke when the
/// Stroke proxy is in front.
fn active_paint<'a>(cx: &'a ToolContext) -> &'a vectorcraft_color::Paint {
if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }
}
/// The slot of [`Self::picked`] for the active paint.
fn picked_slot(cx: &ToolContext) -> usize {
usize::from(!cx.fill_active)
}
fn begin_fill(&mut self, params: Value, p: Point) -> Vec<Action> {
self.fill_drag = Some((params.clone(), vec![vec![p]]));
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), params)]
@@ -377,6 +403,8 @@ impl Tool for LivePaintBucketTool {
}
PointerKind::Drag => self.drag_fill(p),
PointerKind::Up => {
// The swatch preview shows again at the release point.
self.at = Some((p, ev.mods.shift, ev.mods.alt));
let mut acts = self.drag_fill(p);
if self.fill_drag.take().is_some() {
acts.push(Action::Commit);
@@ -387,24 +415,63 @@ impl Tool for LivePaintBucketTool {
}
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape && self.fill_drag.take().is_some() { vec![Action::Cancel] } else { vec![] }
/// Escape during a fill drag cancels it. Left and Right pick the color swatch before or after
/// the active paint, while no drag is on.
fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape {
return if self.fill_drag.take().is_some() { vec![Action::Cancel] } else { vec![] };
}
if !self.claims_key_with(cx, key, mods) {
return vec![];
}
let slot = Self::picked_slot(cx);
let Some((i, name)) = pick_swatch(cx.doc, Self::active_paint(cx), self.picked[slot], key == ToolKey::Right) else {
return vec![];
};
self.picked[slot] = Some(i);
// The active paint only (no `ids`): the selected art keeps its own.
let cmd = if cx.fill_active { "paint.setFill" } else { "paint.setStroke" };
vec![Action::Exec(cmd.into(), json!({ "swatch": name, "ids": [] }))]
}
fn busy(&self) -> bool {
self.fill_drag.is_some()
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
key == ToolKey::Escape && self.busy()
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
match key {
ToolKey::Escape => self.busy(),
ToolKey::Left | ToolKey::Right => !self.busy() && !color_swatches(cx.doc).is_empty(),
_ => false,
}
}
/// The arrows pick swatches only without modifiers; Shift, Alt and Cmd/Ctrl arrows keep their
/// shortcuts.
fn claims_key_with(&self, cx: &ToolContext, key: ToolKey, mods: Mods) -> bool {
self.claims_key(cx, key) && (key == ToolKey::Escape || plain(mods))
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
if self.fill_drag.take().is_some() { vec![Action::Commit] } else { vec![] }
}
fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {
lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32)
/// The pointer hovers nothing for the tool: its highlight and its swatch preview go.
fn hover_ended(&mut self, _cx: &ToolContext) {
self.hover = LpHover::None;
self.at = None;
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32);
// No chips during a fill drag, or while Alt makes the tool sample with the eyedropper.
if self.preview
&& !self.busy()
&& let Some((at, _, false)) = self.at
{
out.extend(swatch_chips(cx, at, Self::active_paint(cx), self.picked[Self::picked_slot(cx)], true));
}
out
}
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
@@ -416,6 +483,7 @@ impl Tool for LivePaintBucketTool {
json!({
"paintFills": self.fills,
"paintStrokes": self.strokes,
"cursorSwatchPreview": self.preview,
"highlight": self.highlight,
"color": format!("#{r:02x}{g:02x}{b:02x}"),
"width": self.width,
@@ -426,6 +494,7 @@ impl Tool for LivePaintBucketTool {
match key {
"paintFills" => self.fills = v.as_bool().unwrap_or(self.fills),
"paintStrokes" => self.strokes = v.as_bool().unwrap_or(self.strokes),
"cursorSwatchPreview" => self.preview = v.as_bool().unwrap_or(self.preview),
"highlight" => self.highlight = v.as_bool().unwrap_or(self.highlight),
"color" => self.color = lp_color(v).unwrap_or(self.color),
"width" => {
@@ -612,7 +681,7 @@ pub(super) fn lp_rgb_color(v: &Value) -> bool {
/// value it cannot read.
pub fn check_live_paint_options(tool: &str, values: &serde_json::Map<String, Value>) -> Result<(), String> {
let switches: &[&str] = match tool {
"livePaintBucket" => &["paintFills", "paintStrokes", "highlight"],
"livePaintBucket" => &["paintFills", "paintStrokes", "cursorSwatchPreview", "highlight"],
"livePaintSelection" => &["selectFills", "selectStrokes"],
_ => return Ok(()),
};
+50 -2
View File
@@ -1087,6 +1087,42 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() {
assert_eq!(id, "livePaint.strokeEdge");
}
/// After a fill drag, the cursor swatch preview shows at the release point, not where the pointer
/// last moved before the press.
#[test]
fn bucket_swatch_preview_follows_the_release_point() {
let (d, ..) = live_group_doc();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
let chip_x = |t: &LivePaintBucketTool| {
t.overlays(&cx).iter().find_map(|o| if let Overlay::Swatch { p, selected: true, .. } = o { Some(p.x) } else { None })
};
t.pointer(&cx, &ev(PointerKind::Move, 25.0, 25.0));
assert_eq!(chip_x(&t), Some(25.0));
t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0));
t.pointer(&cx, &ev(PointerKind::Drag, 50.0, 25.0));
assert_eq!(chip_x(&t), None, "no chips during the drag");
t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0));
assert_eq!(chip_x(&t), Some(75.0));
}
/// When the pointer leaves the canvas, the Live Paint Bucket's swatch preview and highlight go.
#[test]
fn bucket_hover_ended_drops_the_swatch_preview_and_highlight() {
let (d, ..) = live_group_doc();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
let ov = t.overlays(&cx);
assert!(ov.iter().any(|o| matches!(o, Overlay::Swatch { .. })) && ov.iter().any(|o| matches!(o, Overlay::Path { .. })), "{ov:?}");
t.hover_ended(&cx);
assert!(t.overlays(&cx).is_empty());
}
#[test]
fn bucket_options_choose_what_a_click_paints() {
let (d, gid, ..) = live_group_doc();
@@ -1113,7 +1149,12 @@ fn bucket_options_choose_what_a_click_paints() {
};
let (face, edge) = (Some(Rect::new(50.0, 0.0, 100.0, 50.0)), Some(Rect::new(50.0, 0.0, 50.0, 50.0)));
let mut t = LivePaintBucketTool::default();
assert_eq!(t.options(), json!({"paintFills": true, "paintStrokes": false, "highlight": true, "color": "#ff2a2a", "width": 4.0}));
assert_eq!(
t.options(),
json!({"paintFills": true, "paintStrokes": false, "cursorSwatchPreview": true, "highlight": true, "color": "#ff2a2a", "width": 4.0})
);
// The highlight alone, without the swatch chips.
t.set_option("cursorSwatchPreview", &json!(false));
// Paint Fills alone: 1 pt from the edge, a click fills the face and Shift-click strokes the edge.
assert_eq!((click(&mut t, 51.0, Mods::default()), hovered(&mut t, 51.0, Mods::default())), (fill(51.0), face));
assert_eq!((click(&mut t, 51.0, shift), hovered(&mut t, 51.0, shift)), (stroke(51.0), edge));
@@ -1231,6 +1272,7 @@ fn bucket_fills_a_region_of_a_selection_that_mixes_a_group_and_paths() {
s.set([g]);
let live = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.set_option("cursorSwatchPreview", &json!(false));
t.pointer(&live, &ev(PointerKind::Move, pos.x, pos.y));
t.poll(&live, true);
assert!(t.overlays(&live).is_empty());
@@ -1245,6 +1287,7 @@ fn bucket_strokes_alone_paints_and_highlights_no_region_of_the_selection() {
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.set_option("cursorSwatchPreview", &json!(false));
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0));
t.poll(&cx, true);
assert!(!t.overlays(&cx).is_empty(), "Paint Fills highlights the region");
@@ -1263,6 +1306,7 @@ fn bucket_options_set_the_highlight() {
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.set_option("cursorSwatchPreview", &json!(false));
let highlight = |t: &mut LivePaintBucketTool| {
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
match t.overlays(&cx).as_slice() {
@@ -1299,6 +1343,7 @@ fn bucket_highlights_an_edge_thinner_than_a_face() {
let p = paint();
let cx = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.set_option("cursorSwatchPreview", &json!(false));
let width = |t: &mut LivePaintBucketTool, x: f64, shift: bool| {
t.pointer(&cx, &ev(PointerKind::Move, x, 25.0).with_mods(Mods { shift, ..Default::default() }));
match t.overlays(&cx).as_slice() {
@@ -1517,7 +1562,7 @@ fn bucket_hover_builds_a_large_map_on_another_thread() {
poll_until_ready(&mut t, &cx);
assert!(matches!(t.hover, LpHover::Region(_)), "{:?}", t.hover);
assert_eq!((t.cache.builds, t.cache.background), (1, 1));
assert_eq!(t.overlays(&cx).len(), 1);
assert_eq!(t.overlays(&cx).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 1);
}
#[test]
@@ -1883,6 +1928,7 @@ fn live_paint_edges_outside_the_faces_come_from_the_nearest_visible_group() {
};
assert_eq!(lp_click(&mut sel, &cx, ev(PointerKind::Down, x, y).with_mods(alt)), vec![picked]);
let mut bucket = LivePaintBucketTool::default();
bucket.set_option("cursorSwatchPreview", &json!(false));
bucket.pointer(&cx, &ev(PointerKind::Move, x, y).with_mods(shift));
assert_eq!(edge_x(&bucket.overlays(&cx)), want.map(|w| w.2));
let stroked = want.map(|(g, ..)| Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, y], "tolerance": 4.0 })));
@@ -1926,6 +1972,7 @@ fn live_paint_tools_skip_hidden_edges() {
};
assert_eq!(lp_click(&mut sel, &cx, ev(PointerKind::Down, x, 50.0).with_mods(alt)), vec![picked], "x {x}");
let mut bucket = LivePaintBucketTool::default();
bucket.set_option("cursorSwatchPreview", &json!(false));
bucket.pointer(&cx, &ev(PointerKind::Move, x, 50.0).with_mods(shift));
assert_eq!(edge_x(&bucket.overlays(&cx)), want.map(|w| w.2), "x {x}");
let stroked = want.map(|(g, ..)| Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, 50.0], "tolerance": 4.0 })));
@@ -1953,6 +2000,7 @@ fn live_paint_tools_skip_hidden_faces() {
};
// Where the faces overlap, both tools take the back group's face under the hidden one.
let mut bucket = LivePaintBucketTool::default();
bucket.set_option("cursorSwatchPreview", &json!(false));
bucket.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0));
assert_eq!(part(&bucket.overlays(&cx)), Some(Rect::new(0.0, 0.0, 100.0, 100.0)));
let fill = Action::Preview("livePaint.fill".into(), json!({ "group": back.0, "point": [75.0, 50.0] }));
+5
View File
@@ -182,6 +182,11 @@ pub trait Tool: Send {
fn claims_key(&self, _cx: &ToolContext, _key: ToolKey) -> bool {
false
}
/// [`Self::claims_key`] for a press with `mods` held. By default the modifiers do not matter;
/// a tool that takes a key only without modifiers leaves the modified presses to the shortcuts.
fn claims_key_with(&self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> bool {
self.claims_key(cx, key)
}
/// Has the tool started something that Escape ends while no button is pressed (a path being
/// drawn, the Blend tool's first pick)? That Escape ends nothing else, such as isolation mode or
/// a rotated view.
+1 -1
View File
@@ -46,7 +46,7 @@ const ROWS: &[Row] = &[
// Live Paint Selection Tool Options (`builder::LivePaintSelectionTool`).
(&["livePaintSelection"], None, &["selectFills", "selectStrokes", "color", "width"]),
// Live Paint Bucket Options (`builder::LivePaintBucketTool`).
(&["livePaintBucket"], None, &["paintFills", "paintStrokes", "highlight", "color", "width"]),
(&["livePaintBucket"], None, &["paintFills", "paintStrokes", "cursorSwatchPreview", "highlight", "color", "width"]),
(&["polygon"], None, &["sides"]),
(&["star"], None, &["points"]),
(&["freeTransform"], None, &["constrain"]),
+472
View File
@@ -0,0 +1,472 @@
//! The 8 x 8 block edges of a block-coded image (a JPEG, or a copy of one saved in another format)
//! smoothed away before it is traced.
//!
//! A JPEG codes each 8 x 8 block on its own and rounds each block's brightness in coarse steps, which
//! leaves a small step at every block edge. Where an area's tone changes slowly, as a dark ground does,
//! those steps decide which of two palette colors a whole block gets, and the trace follows the block
//! edges as a staircase. The block grid is found in the image itself: the mean step between
//! neighboring pixels peaks at one position in every eight, across and down, at every block edge and
//! not only at every other one (a pattern of 16 px squares has that too). Where it does, the step
//! at each block edge is spread evenly over the eight pixels around it when it is small and those
//! pixels hold no edge. Larger steps are left as they are. How large a step is smoothed, and whether
//! each row keeps part of its own step, depends on the trace's mode and number of colors (see
//! [`Strength`]). The deblocking filters of ITU-T H.263
//! Annex J and ISO/IEC 14496-2 (MPEG-4 Part 2) Annex F.3.1 treat block edges the same way: small steps
//! between blocks become ramps, and large ones are kept.
use std::sync::Mutex;
use crate::{Raster, parallel_map, quantize};
/// The block size of a JPEG.
const BLOCK: usize = 8;
/// Steps between neighboring pixels of this many levels or more are edges, left out when the grid is
/// measured. No block-edge step this large is smoothed.
const EDGE: f64 = 16.0;
/// The mean step at the block edges must be this many times the mean step at the other positions,
/// across and down, for the image to count as block-coded.
const PEAK: f64 = 1.5;
/// The smallest limit on the block-edge steps that are smoothed (levels, after the image's own slope
/// is taken out); the limit is under `EDGE` too.
const LEAST: f64 = 2.5;
/// Fixed-point scale of the working copy: sixteenths of a level.
const SCALE: f64 = 16.0;
/// How the block edges are smoothed.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Strength {
/// The largest block-edge step that is smoothed: this many times the extra step the block edges
/// show on average, at least `LEAST` and under `EDGE`.
reach: f64,
/// A block edge with a step of this many levels or more between neighbors in the pixels around
/// it is left as it is.
guard: f64,
/// How far one row's step may differ from its stretch's mean step and still be smoothed, as a
/// share of the limit. The rest of a row's own step is kept.
row_share: f64,
}
/// For a trace in black and white, which thresholds the image without smoothing it first: small
/// steps only, each row with its own.
pub(crate) const BLACK_AND_WHITE: Strength = Strength { reach: 2.0, guard: 8.0, row_share: 0.5 };
/// For a trace of up to 16 colors: each row with its own step.
pub(crate) const FEW_COLORS: Strength = Strength { reach: 8.0, guard: 13.0, row_share: 0.5 };
/// For a trace of more than 16 colors: larger steps, but only each stretch's mean step, so that
/// every row of a stretch moves by the same amount.
pub(crate) const MANY_COLORS: Strength = Strength { reach: 4.0, guard: EDGE, row_share: 0.0 };
/// Where the block edges of a block-coded image are, and how large their steps are.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Grid {
/// A block edge lies between columns `x - 1` and `x` when `x % 8 == across`.
across: usize,
/// A block edge lies between rows `y - 1` and `y` when `y % 8 == down`.
down: usize,
/// The extra step the block edges show on average over the other positions, across or down,
/// whichever is smaller.
extra: f64,
}
/// Positions counted when the grid is measured: two blocks, so that a pattern of 16 px or more
/// (a checkerboard, cells of a picture enlarged 16 times), whose edges fall on every other block
/// edge only, is not taken for blocks.
const SPAN: usize = 2 * BLOCK;
/// For one direction, from the mean step between neighboring opaque pixels at each of 16 positions:
/// the position (of eight) where it peaks at both block edges of the span, the extra step those
/// show over the other positions, and whether there is no step at all at the other positions; `None`
/// when no position stands out.
fn peak(sum: &[f64; SPAN], count: &[u64; SPAN]) -> Option<(usize, f64, bool)> {
if count.contains(&0) {
return None;
}
let mean: Vec<f64> = sum.iter().zip(count).map(|(&s, &n)| s / n as f64).collect();
let pair = |at: usize| (mean.get(at).copied().unwrap_or(0.0), mean.get(at + BLOCK).copied().unwrap_or(0.0));
let at = (0..BLOCK).max_by(|&a, &b| {
let (pa, pb) = (pair(a), pair(b));
pa.0.min(pa.1).total_cmp(&pb.0.min(pb.1))
})?;
let (first, second) = pair(at);
let others = || mean.iter().enumerate().filter(|&(i, _)| i != at && i != at + BLOCK).map(|(_, &m)| m);
let rest = others().sum::<f64>() / (SPAN - 2) as f64;
(first.min(second) > PEAK * rest).then_some((at, (first + second) / 2.0 - rest, others().all(|m| m == 0.0)))
}
/// The block grid of `img`, if it has one.
fn grid(img: &Raster) -> Option<Grid> {
let (w, h) = (img.width as usize, img.height as usize);
if w < 2 * SPAN || h < 2 * SPAN || img.rgba.len() != w * h * 4 {
return None;
}
let px = img.rgba.as_chunks::<4>().0;
let luma = |p: &[u8; 4]| (p[3] == 255).then(|| f64::from(quantize::luma(*p)));
let (mut across, mut down) = (([0.0; SPAN], [0u64; SPAN]), ([0.0; SPAN], [0u64; SPAN]));
for y in 0..h {
for x in 0..w {
let Some(here) = px.get(y * w + x).and_then(luma) else { continue };
let add = |bins: &mut ([f64; SPAN], [u64; SPAN]), at: usize, other: Option<f64>| {
if let Some(step) = other.map(|o| (here - o).abs()).filter(|&s| s < EDGE) {
bins.0[at % SPAN] += step;
bins.1[at % SPAN] += 1;
}
};
if x > 0 {
add(&mut across, x, px.get(y * w + x - 1).and_then(luma));
}
if y > 0 {
add(&mut down, y, px.get((y - 1) * w + x).and_then(luma));
}
}
}
let (across, extra_across, flat_across) = peak(&across.0, &across.1)?;
let (down, extra_down, flat_down) = peak(&down.0, &down.1)?;
// Blocks that are each one flat color, with no step at all inside them, are cells of a picture
// enlarged eight times, which stay as they are.
if flat_across && flat_down {
return None;
}
Some(Grid { across, down, extra: extra_across.min(extra_down) })
}
/// Smooths one stretch of a block edge in `band` (values in sixteenths of a level, 3 channels per
/// pixel): `lines` (1 to 8) lines that cross the edge, the pixel at position `i` (0 to 7; the edge lies between
/// 3 and 4) of line `l` starting at `band[index(l, i)]`, where `opaque(l, i)` says whether it is fully
/// opaque. The stretch's step is the mean over its lines of the step across the edge less the slope
/// on either side. A stretch of opaque pixels whose step is under `limit` on every channel, with no
/// step of `strength.guard` or more between neighbors in its pixels (across, the edge itself aside, or
/// along), has that step spread over the eight pixels of each line: with the line's own difference
/// from it, to at most `strength.row_share` of `limit` either way, each pixel moves by the step times
/// 3.5/8, 2.5/8, 1.5/8 or 0.5/8 by its distance from the edge, so the pixels in the middle of the
/// blocks hardly move.
fn smooth_edge(
band: &mut [i16],
lines: usize,
index: impl Fn(usize, usize) -> usize,
opaque: impl Fn(usize, usize) -> bool,
limit: f64,
strength: Strength,
) {
if lines == 0 || lines > BLOCK || !(0..lines).all(|l| (0..BLOCK).all(|i| opaque(l, i))) {
return;
}
let at = |l: usize, i: usize, k: usize| f64::from(band.get(index(l, i) + k).copied().unwrap_or(0)) / SCALE;
// Each line's step on each channel, and the largest step within the pixels around the edge.
let mut steps = [[0.0; 3]; BLOCK];
let steps = steps.get_mut(..lines).unwrap_or_default();
let mut inner = 0.0f64;
for (l, step) in steps.iter_mut().enumerate() {
for (k, s) in step.iter_mut().enumerate() {
let p: [f64; BLOCK] = std::array::from_fn(|i| at(l, i, k));
*s = (p[4] - p[3]) - ((p[3] - p[2]) + (p[5] - p[4])) / 2.0;
for i in (0..BLOCK - 1).filter(|&i| i != 3) {
inner = inner.max((p[i + 1] - p[i]).abs());
}
// And from this line to the next: a line along the edge is an edge too.
if l + 1 < lines {
for (i, &here) in p.iter().enumerate() {
inner = inner.max((at(l + 1, i, k) - here).abs());
}
}
}
}
let mean: [f64; 3] = std::array::from_fn(|k| steps.iter().map(|s| s[k]).sum::<f64>() / lines as f64);
if inner >= strength.guard || mean.iter().any(|m| m.abs() >= limit) {
return;
}
let own = limit * strength.row_share;
for (l, step) in steps.iter().enumerate() {
for k in 0..3 {
let step = mean[k] + (step[k] - mean[k]).clamp(-own, own);
for i in 0..BLOCK / 2 {
let shift = (step * (3.5 - i as f64) / BLOCK as f64 * SCALE).round() as i16;
if let Some(p) = band.get_mut(index(l, 3 - i) + k) {
*p = p.saturating_add(shift);
}
if let Some(p) = band.get_mut(index(l, 4 + i) + k) {
*p = p.saturating_sub(shift);
}
}
}
}
}
/// Where the stretches of eight lines start along a block edge `len` lines long, when they start at
/// the lines with `l % 8 == at`: the first, from line 0, can be shorter. Each as (first line, count).
fn stretches(len: usize, at: usize) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = if at > 0 { vec![(0, at.min(len))] } else { vec![] };
out.extend((at..len).step_by(BLOCK).map(|s| (s, BLOCK.min(len - s))));
out
}
/// `f` of each of `bands` (with what it needs to know about the band), which it may change, spread
/// over the available cores.
fn each_band<K: Copy + Send, T: Send>(bands: Vec<(K, &mut [T])>, f: impl Fn(K, &mut [T]) + Sync) {
let bands: Vec<Mutex<(K, &mut [T])>> = bands.into_iter().map(Mutex::new).collect();
parallel_map(&bands, |band| {
// Each band is locked by one worker only, so the lock is never held elsewhere.
if let Ok(mut band) = band.lock() {
let (first, values) = &mut *band;
f(*first, values);
}
});
}
/// The first block edge (of positions `at`, `at + 8`, ...) with four pixels before it.
fn first_edge(at: usize) -> usize {
if at >= BLOCK / 2 { at } else { at + BLOCK }
}
/// Smooths the block edges of `v`, rows `top` on of the image (`w` pixels of 3 channels, in
/// sixteenths of a level, from the first row of a stretch of rows to the last row of one), where
/// `opaque(y, x)` is set: the edges between columns `x - 1` and `x` with `x % 8 == across` in stretches
/// of eight rows that start at the rows with `y % 8 == down`, then the edges between rows `e - 1` and
/// `e` for each `e` of `edges` in stretches of eight columns that start at the columns with
/// `x % 8 == across` (see `smooth_edge`).
fn smooth_strip(
v: &mut [i16],
top: usize,
w: usize,
grid: &Grid,
edges: &[usize],
opaque: impl Fn(usize, usize) -> bool,
(limit, strength): (f64, Strength),
) {
let row = w * 3;
if w < BLOCK || row == 0 {
return;
}
for (at, rows) in stretches(v.len() / row, (grid.down + BLOCK - top % BLOCK) % BLOCK) {
let Some(band) = v.get_mut(at * row..(at + rows) * row) else { continue };
for e in (first_edge(grid.across)..=w - BLOCK / 2).step_by(BLOCK) {
smooth_edge(band, rows, |l, i| (l * w + e - BLOCK / 2 + i) * 3, |l, i| opaque(top + at + l, e - BLOCK / 2 + i), limit, strength);
}
}
for &e in edges {
let Some(band) = e.checked_sub(top + BLOCK / 2).and_then(|at| v.get_mut(at * row..(at + BLOCK) * row)) else { continue };
for (left, columns) in stretches(w, grid.across) {
smooth_edge(band, columns, |l, i| (i * w + left + l) * 3, |l, i| opaque(e - BLOCK / 2 + i, left + l), limit, strength);
}
}
}
/// The edges between rows smoothed in one piece of work, with the stretches of rows around them.
const STRIP: usize = 8;
/// `img` with its block edges smoothed away as `strength` says, or `None` when it shows no block grid.
/// The image is worked on in strips of rows, each with the stretches of rows its `STRIP` edges between
/// rows need, so only the copy it returns is as large as the image.
pub(crate) fn deblocked(img: &Raster, strength: Strength) -> Option<Raster> {
let grid = grid(img)?;
let limit = (strength.reach * grid.extra).clamp(LEAST, EDGE);
let (w, h) = (img.width as usize, img.height as usize);
let px = img.rgba.as_chunks::<4>().0;
let opaque = |y: usize, x: usize| px.get(y * w + x).is_some_and(|p| p[3] == 255);
let edges: Vec<usize> = (first_edge(grid.down)..=h.saturating_sub(BLOCK / 2)).step_by(BLOCK).collect();
let groups: Vec<&[usize]> = edges.chunks(STRIP).collect();
// The rows each strip writes: from four rows above its first edge (the top of the image for the
// first strip) to four rows below its last (the bottom of the image for the last strip).
let mut rgba = img.rgba.clone();
let mut bands = vec![];
let mut rest: &mut [u8] = &mut rgba;
let mut above = 0;
for (n, group) in groups.iter().enumerate() {
let below = if n + 1 == groups.len() { h } else { group.last().map_or(h, |e| e + BLOCK / 2) };
let (band, after) = std::mem::take(&mut rest).split_at_mut_checked(below.checked_sub(above)? * w * 4)?;
bands.push(((above, *group), band));
rest = after;
above = below;
}
// The first row of the stretch of rows that holds row `y`, and the row after the stretch.
let stretch = |y: usize| {
let first = if y < grid.down { 0 } else { y - (y - grid.down) % BLOCK };
(first, if y < grid.down { grid.down } else { first + BLOCK }.min(h))
};
each_band(bands, |(above, group), band| {
let below = above + band.len() / (w * 4);
let (first, last) = (stretch(above).0, stretch(below.saturating_sub(1)).1);
let Some(source) = px.get(first * w..last * w) else { return };
let mut v: Vec<i16> = source.iter().flat_map(|p| [p[0], p[1], p[2]].map(|c| i16::from(c) * SCALE as i16)).collect();
smooth_strip(&mut v, first, w, &grid, group, opaque, (limit, strength));
let skip = (above - first) * w;
for (p, c) in band.as_chunks_mut::<4>().0.iter_mut().zip(v.as_chunks::<3>().0.iter().skip(skip)) {
for k in 0..3 {
p[k] = ((i32::from(c[k]) + 8).div_euclid(16)).clamp(0, 255) as u8;
}
}
});
Some(Raster { width: img.width, height: img.height, rgba })
}
#[cfg(test)]
mod tests {
use super::*;
/// A number in -1..1 that looks random, from `x`, `y` and `k`.
fn jitter(x: u32, y: u32, k: u32) -> f64 {
let mut n = x.wrapping_mul(0x9E37_79B1) ^ y.wrapping_mul(0x85EB_CA77) ^ k.wrapping_mul(0xC2B2_AE3D);
n ^= n >> 15;
n = n.wrapping_mul(0x2C1B_3C6D);
n ^= n >> 12;
f64::from(n % 2001) / 1000.0 - 1.0
}
/// A dark ground that brightens slowly to the right, with a level of noise and, when `blocks`,
/// every 8 x 8 block (counted from `(dx, dy)`) moved by up to 2 levels, as a JPEG leaves it.
fn ground(w: u32, h: u32, blocks: bool, dx: u32, dy: u32) -> Raster {
Raster::from_fn(w, h, |x, y| {
let offset = if blocks { 2.0 * jitter((x + dx) / 8, (y + dy) / 8, 9) } else { 0.0 };
let v = 20.0 + 30.0 * f64::from(x) / f64::from(w) + offset + jitter(x, y, 0);
let v = v.round().clamp(0.0, 255.0) as u8;
[v, v, v, 255]
})
}
/// The mean step between neighboring columns at the block edges (`x % 8 == across`) and elsewhere.
fn steps(img: &Raster, across: u32) -> (f64, f64) {
let (mut on, mut off) = ((0.0, 0), (0.0, 0));
for y in 0..img.height {
for x in 1..img.width {
let d = (f64::from(img.pixel(x, y)[0]) - f64::from(img.pixel(x - 1, y)[0])).abs();
let bin = if x % 8 == across { &mut on } else { &mut off };
bin.0 += d;
bin.1 += 1;
}
}
(on.0 / f64::from(on.1), off.0 / f64::from(off.1))
}
#[test]
fn the_block_grid_is_found_where_the_blocks_are() {
let g = grid(&ground(160, 120, true, 0, 0)).unwrap();
assert_eq!((g.across, g.down), (0, 0));
// The same image with 3 columns and 5 rows cut off: its block edges are at x % 8 == 5, y % 8 == 3.
let g = grid(&ground(160, 120, true, 3, 5)).unwrap();
assert_eq!((g.across, g.down), (5, 3));
assert!(g.extra > 0.5, "{}", g.extra);
}
#[test]
fn an_image_without_blocks_is_left_as_it_is() {
assert_eq!(grid(&ground(160, 120, false, 0, 0)), None);
assert!(deblocked(&ground(160, 120, false, 0, 0), FEW_COLORS).is_none());
// A picture of four flat colors enlarged eight times has steps only at its cells' edges, and
// none within them; two of its colors are 6 levels apart.
let colors = [[30, 30, 36, 255], [36, 30, 30, 255], [200, 60, 40, 255], [240, 220, 120, 255]];
let cells = Raster::from_fn(160, 120, |x, y| colors[((jitter(x / 8, y / 8, 1) + 1.0) * 2.0).min(3.0) as usize]);
assert_eq!(grid(&cells), None);
// So does a picture of many shades enlarged eight times, as a photo's would.
let shades = Raster::from_fn(160, 120, |x, y| {
let v = (40.0 + 0.6 * f64::from(x / 8 * 8) + 0.5 * f64::from(y / 8 * 8) + 3.0 * jitter(x / 8, y / 8, 4)).round() as u8;
[v, v.saturating_sub(10), v.saturating_add(10), 255]
});
assert_eq!(grid(&shades), None);
// A noisy checkerboard of 16 px squares 10 levels apart has its steps on every other block edge.
let squares = Raster::from_fn(160, 120, |x, y| {
let v = (20.0 + 10.0 * f64::from((x / 16 + y / 16) % 3) + 4.0 * jitter(x, y, 2)).round() as u8;
[v, v, v, 255]
});
assert_eq!(grid(&squares), None);
// Too small to hold two spans of 16 px each way.
assert_eq!(grid(&ground(31, 120, true, 0, 0)), None);
}
#[test]
fn the_steps_at_block_edges_become_ramps() {
for ((dx, dy), strength) in [((0, 0), FEW_COLORS), ((3, 5), FEW_COLORS), ((0, 0), MANY_COLORS), ((0, 0), BLACK_AND_WHITE)] {
let img = ground(160, 120, true, dx, dy);
let across = (8 - dx % 8) % 8;
let (on, off) = steps(&img, across);
assert!(on > 2.0 * off, "before: {on} at the block edges, {off} elsewhere");
let out = deblocked(&img, strength).unwrap();
let (on, off) = steps(&out, across);
assert!(on < 1.25 * off, "after: {on} at the block edges, {off} elsewhere");
// The ground's own slope stays: 30 levels across the image.
let mean = |r: &Raster, x: u32| (0..r.height).map(|y| f64::from(r.pixel(x, y)[0])).sum::<f64>() / f64::from(r.height);
assert!((mean(&out, 156) - mean(&out, 4) - (mean(&img, 156) - mean(&img, 4))).abs() < 0.5);
}
}
#[test]
fn stretches_cover_every_line_once() {
assert_eq!(stretches(20, 0), [(0, 8), (8, 8), (16, 4)]);
assert_eq!(stretches(20, 3), [(0, 3), (3, 8), (11, 8), (19, 1)]);
assert_eq!(stretches(2, 3), [(0, 2)]);
}
#[test]
fn with_many_colors_every_row_of_a_stretch_moves_alike() {
let img = ground(160, 120, true, 0, 0);
let v: Vec<i16> = img.rgba.chunks(4).flat_map(|p| [p[0], p[1], p[2]].map(|c| i16::from(c) * SCALE as i16)).collect();
// How far each pixel moves when the edges between columns are smoothed.
let shifts = |strength: Strength| -> Vec<i16> {
let mut out = v.clone();
for top in (0..120).step_by(8) {
let band = &mut out[top * 160 * 3..(top + 8) * 160 * 3];
for e in (8..=156).step_by(8) {
smooth_edge(band, 8, |l, i| (l * 160 + e - 4 + i) * 3, |_, _| true, 4.0, strength);
}
}
out.iter().zip(&v).map(|(o, i)| o - i).step_by(3).collect()
};
let (many, few) = (shifts(MANY_COLORS), shifts(FEW_COLORS));
let differ = |s: &[i16]| {
(0..160)
.flat_map(|x| (0..120).step_by(8).map(move |top| (x, top)))
.filter(|&(x, top)| (top..top + 8).any(|y| s[y * 160 + x] != s[top * 160 + x]))
.count()
};
assert!(many.iter().filter(|&&s| s != 0).count() > 160 * 120 / 2);
assert_eq!(differ(&many), 0);
// With few colors, each row keeps part of its own step.
assert!(differ(&few) > 160 * 15 / 2, "{}", differ(&few));
}
#[test]
fn edges_and_fine_lines_stay_sharp() {
// Black lines 1 to 4 px wide and white gaps between them on a block-coded mid-gray ground, one
// line on a block edge.
let base = ground(160, 120, true, 0, 0);
let lines = [(16, 1), (31, 2), (40, 3), (61, 4)];
let img = Raster::from_fn(160, 120, |x, y| {
if lines.iter().any(|&(at, wide)| (at..at + wide).contains(&x)) {
[0, 0, 0, 255]
} else {
let v = base.pixel(x, y)[0] + 80;
[v, v, v, 255]
}
});
let out = deblocked(&img, FEW_COLORS).unwrap();
for y in 0..120 {
for &(at, wide) in &lines {
for x in at..at + wide {
assert_eq!(out.pixel(x, y), [0, 0, 0, 255], "line pixel ({x}, {y})");
}
// The ground beside a line moves by no more than a block's offset (the edges between
// rows in its column are smoothed; the one across the line is not).
for x in [at - 1, at + wide] {
let moved = (i32::from(out.pixel(x, y)[0]) - i32::from(img.pixel(x, y)[0])).abs();
assert!(moved <= 3, "beside the line, ({x}, {y}) moved {moved}");
}
}
}
}
#[test]
fn transparent_pixels_keep_their_colors() {
let base = ground(160, 120, true, 0, 0);
let img = Raster::from_fn(160, 120, |x, y| {
let mut p = base.pixel(x, y);
if x >= 100 {
p[3] = if x < 104 { 128 } else { 0 };
}
p
});
let out = deblocked(&img, FEW_COLORS).unwrap();
for y in 0..120 {
for x in 100..160 {
assert_eq!(out.pixel(x, y), img.pixel(x, y), "({x}, {y})");
}
}
assert_eq!(out.rgba.chunks(4).map(|p| p[3]).collect::<Vec<_>>(), img.rgba.chunks(4).map(|p| p[3]).collect::<Vec<_>>());
}
}

Some files were not shown because too many files have changed in this diff Show More