mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 12:35:48 -05:00
Merge main into feat/scripts-api-d1b-prefs-matrix-clipboard
This commit is contained in:
commit
4bb499bb97
153 files changed
+6040
-497
No files matched your search
@@ -47,6 +47,9 @@ jobs:
|
||||
test-shards: 6
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
|
||||
# its shard builds), and `cache warm` puts their files into the one entry it saves.
|
||||
warm-split: true
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
@@ -65,14 +68,17 @@ jobs:
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
|
||||
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
|
||||
# script reports a leg that starts late with its own error before the job times out.
|
||||
# free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its
|
||||
# start deadline while any split leg is queued or running, then allows 180 minutes from the last
|
||||
# split completion for the saving leg to start. Without split legs, it allows 180 minutes from
|
||||
# the script's start. A failed split leg fails this job too. The script then waits up to 160
|
||||
# minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the
|
||||
# script's deadlines expire when split builds or runner waits take too long.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 290
|
||||
timeout-minutes: 360
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
|
||||
Generated
-1
@@ -8573,7 +8573,6 @@ version = "0.25.1"
|
||||
dependencies = [
|
||||
"craft-affinity",
|
||||
"craft-image-codecs",
|
||||
"crc32fast",
|
||||
"proptest",
|
||||
"vectorcraft-affinity",
|
||||
]
|
||||
|
||||
@@ -160,11 +160,14 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
|
||||
- 2026-11-29: Randomize Fill Colors joins the Color Effects add-on (Object › Plug-ins › Color Effects): each selected filled path, compound path and live compound shape, inside groups and graph series too, gets a fill color of its own at random: any color, tints of a global or spot swatch, or grays between a minimum and a maximum percent, with a seed that repeats the result and Preview, as one undo step (`addon.color.randomFill`); art on a locked artboard keeps its fill (also when `ids` names it), except new art made there while it is still selected.
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-29: Mark Bounds of Each joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own inward corner marks, or a rectangle, on its geometric or visual bounds, stroked in the color and weight given, stacked directly above it; clip groups are measured by their clipping path. A dialog with Preview, one undo step (`addon.arrange.markBounds`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Group by Row joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap from top to bottom go into one group for each row (or, by column, from left to right), within their own layer or group and artboard, at the stacking place of their frontmost member; an object alone in its row stays as it is. One undo step, with a previewed dialog (`addon.arrange.groupRows`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the
|
||||
//! log (`logs/vectorcraft.log`) and to `logs/hang-report-<process id>.txt`: the stage, a clipboard
|
||||
//! call in progress, the last commands, the last frames' times, the platform, the window system, the
|
||||
//! graphics processor and the present mode the app asked for, and how long the session has run with
|
||||
//! how many documents open. The process holds a lock on the file until the interface thread answers
|
||||
//! graphics processor, its driver when known, and the present mode the app asked for, and how long
|
||||
//! the session has run with how many documents open. The process holds a lock on the file until the interface thread answers
|
||||
//! again; then the log says after how long and the file is removed. A file nobody holds at a later
|
||||
//! launch was left by a session that was closed while it did not answer, and a locked one belongs to
|
||||
//! another instance that is stalled now and is left alone. That launch writes the report to the log,
|
||||
@@ -113,6 +113,8 @@ pub struct Facts {
|
||||
pub flatpak: bool,
|
||||
/// The graphics processor the window draws with.
|
||||
pub graphics: Option<String>,
|
||||
/// The active graphics driver's identity, when the backend reports it.
|
||||
graphics_driver: Option<String>,
|
||||
/// The present mode and frame queue the app asked the window surface for.
|
||||
pub surface: String,
|
||||
}
|
||||
@@ -128,14 +130,29 @@ impl Facts {
|
||||
session_type: value("XDG_SESSION_TYPE"),
|
||||
flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()),
|
||||
graphics,
|
||||
graphics_driver: None,
|
||||
surface,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "wgpu", test))]
|
||||
pub fn with_graphics_driver(mut self, driver: &str, info: &str) -> Facts {
|
||||
// D3D12 reports 0.0.0.0 when the driver version could not be read.
|
||||
let mut fields = [driver, info].map(clean).into_iter().filter(|value| !value.is_empty() && value != "0.0.0.0");
|
||||
self.graphics_driver = fields.next().map(|mut detail| {
|
||||
if let Some(info) = fields.next().filter(|info| info != &detail) {
|
||||
detail.push_str(" / ");
|
||||
detail.push_str(&info);
|
||||
}
|
||||
detail
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// The facts as report lines.
|
||||
pub fn lines(&self) -> String {
|
||||
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
|
||||
format!(
|
||||
let mut lines = format!(
|
||||
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
|
||||
vectorcraft_ui_egui::os_window::version(),
|
||||
std::env::consts::OS,
|
||||
@@ -146,7 +163,13 @@ impl Facts {
|
||||
if self.flatpak { "yes" } else { "no" },
|
||||
or_unknown(&self.graphics),
|
||||
self.surface,
|
||||
)
|
||||
);
|
||||
if let Some(driver) = &self.graphics_driver {
|
||||
lines.push_str("Graphics driver: ");
|
||||
lines.push_str(driver);
|
||||
lines.push('\n');
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -279,3 +279,22 @@ fn troubleshooting_info_holds_both_sessions_reports() {
|
||||
assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n"));
|
||||
assert!(text.contains("Recent commands, oldest first: none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn troubleshooting_info_distinguishes_drivers_on_the_same_adapter() {
|
||||
let mut shared = shared(None);
|
||||
let beacon = Beacon::new();
|
||||
for (driver, info, expected) in [
|
||||
(" 32.0.16.1088 ", "", Some("32.0.16.1088")),
|
||||
("32.0.16.2124", "", Some("32.0.16.2124")),
|
||||
("Mesa\nRADV", "Mesa 25.2", Some("MesaRADV / Mesa 25.2")),
|
||||
("Mesa", "Mesa", Some("Mesa")),
|
||||
("0.0.0.0", "", None),
|
||||
("", "", None),
|
||||
] {
|
||||
shared.facts = facts().with_graphics_driver(driver, info);
|
||||
let text = troubleshooting(&shared, &beacon, UNIX_EPOCH);
|
||||
assert!(text.contains("Graphics: Test GPU"), "the adapter description is still in the report");
|
||||
assert_eq!(text.lines().find_map(|line| line.strip_prefix("Graphics driver: ")), expected);
|
||||
}
|
||||
}
|
||||
@@ -432,6 +432,12 @@ fn opens_through_xwayland(pref: Option<&str>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The docking runtime needs the backend the desktop window is opened on.
|
||||
fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo {
|
||||
let backend = if forced_to_x11 { Backend::X11 } else { detected };
|
||||
ShellInfo::current().backend(backend)
|
||||
}
|
||||
|
||||
/// The nightly channel this build is, as a string for the log.
|
||||
fn channel_name() -> &'static str {
|
||||
match build_flavor::COMPILED {
|
||||
@@ -718,10 +724,10 @@ fn main() -> std::process::ExitCode {
|
||||
// A window forced onto XWayland runs on X11, whose window manager draws the frame: the
|
||||
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
|
||||
// Preferences › User Interface › System Title Bar.
|
||||
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
|
||||
let shell_info = desktop_shell_info(Backend::from_env(), forced_to_x11);
|
||||
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
|
||||
// beside it (#2450, #5311).
|
||||
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
|
||||
let wayland = shell_info.backend == Backend::Wayland;
|
||||
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
|
||||
let shell_info = shell_info.caps(caps);
|
||||
let titlebar_pref =
|
||||
@@ -981,14 +987,22 @@ fn main() -> std::process::ExitCode {
|
||||
.map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency));
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let surface = None;
|
||||
let facts = hang_watch::Facts::new(
|
||||
|name| std::env::var(name).ok(),
|
||||
std::path::Path::new("/.flatpak-info").exists(),
|
||||
hang_watch::window_system(winit_window.as_deref()),
|
||||
app.graphics_adapter.clone(),
|
||||
hang_watch::surface(surface),
|
||||
);
|
||||
#[cfg(feature = "wgpu")]
|
||||
let facts = if let Some(rs) = &cc.wgpu_render_state {
|
||||
let info = rs.adapter.get_info();
|
||||
facts.with_graphics_driver(&info.driver, &info.driver_info)
|
||||
} else {
|
||||
facts
|
||||
};
|
||||
let hang = std::sync::Arc::new(hang_watch::Shared {
|
||||
facts: hang_watch::Facts::new(
|
||||
|name| std::env::var(name).ok(),
|
||||
std::path::Path::new("/.flatpak-info").exists(),
|
||||
hang_watch::window_system(winit_window.as_deref()),
|
||||
app.graphics_adapter.clone(),
|
||||
hang_watch::surface(surface),
|
||||
),
|
||||
facts,
|
||||
started: std::time::Instant::now(),
|
||||
last: std::sync::Mutex::new(None),
|
||||
previous: previous_hang.clone(),
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn desktop_shell_reports_the_backend_selected_for_docking() {
|
||||
let wayland = desktop_shell_info(Backend::Wayland, false);
|
||||
assert_eq!(wayland.backend, Backend::Wayland);
|
||||
assert!(!wayland.window_positions(), "native Wayland keeps palettes inside the window");
|
||||
|
||||
for (detected, force_x11) in [(Backend::Wayland, true), (Backend::X11, false)] {
|
||||
let x11 = desktop_shell_info(detected, force_x11);
|
||||
assert_eq!(x11.backend, Backend::X11);
|
||||
assert!(x11.window_positions(), "X11 and XWayland can place native palettes");
|
||||
}
|
||||
}
|
||||
|
||||
/// The saved UI state of an old `ui.json`, as the legacy import reads it.
|
||||
fn legacy_ui(bytes: &[u8]) -> Option<vectorcraft_ui_egui::UiState> {
|
||||
vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 4.8L18.7 1.4L22.6 21.6L4.8 18.2Z"/>
|
||||
<rect x="0.8" y="3.6" width="2.4" height="2.4" fill="currentColor"/>
|
||||
<rect x="17.5" y="0.2" width="2.4" height="2.4" fill="currentColor"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 525 B After Width: | Height: | Size: 527 B |
@@ -19,7 +19,6 @@ craft-affinity = { workspace = true }
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
# The tests build containers and decode previews.
|
||||
crc32fast = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
# tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate
|
||||
# is tested without vectorcraft-engine (`cargo xtask ci shard`).
|
||||
|
||||
@@ -41,6 +41,70 @@ fn source(bytes: &[u8]) -> Vec<u8> {
|
||||
block.bytes(block.root, b"Data").unwrap().to_vec()
|
||||
}
|
||||
|
||||
/// The fixture's one tiled bitmap read straight from its archive entries, interleaved: RGBA8 for
|
||||
/// RGBA layers (16-bit samples scaled to 8 bits with rounding) and C, M, Y, K, alpha for CMYK.
|
||||
/// Each channel is a grid of 256-byte × 256-row tiles in row-major order; state 2 is a tile of
|
||||
/// 0xFF, state 4 a stored tile (the next `Idx<c>` entry), and any other state a tile of zeros.
|
||||
fn tiled_pixels(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
const TILE: usize = 256;
|
||||
let mut archive = Archive::open(bytes, Limits::default()).unwrap();
|
||||
let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap();
|
||||
// The bitmap the image layer (`ImgN`) holds as `Bitm`; the document's other bitmaps are masks.
|
||||
let bitmaps: Vec<usize> = (0..doc.objects.len())
|
||||
.filter(|&o| doc.is(o, b"ImgN"))
|
||||
.filter_map(|o| doc.obj(o, b"Bitm"))
|
||||
.filter(|&b| doc.is(b, b"DyBm") && doc.field(b, b"Sta1").is_some())
|
||||
.collect();
|
||||
assert_eq!(bitmaps.len(), 1, "one tiled image bitmap");
|
||||
let bitmap = bitmaps[0];
|
||||
let width = usize::try_from(doc.int(bitmap, b"BmpW").unwrap()).unwrap();
|
||||
let height = usize::try_from(doc.int(bitmap, b"BmpH").unwrap()).unwrap();
|
||||
let (channels, bps) = match doc.enumeration(bitmap, b"Frmt").unwrap().0 {
|
||||
0 => (4, 1),
|
||||
1 => (4, 2),
|
||||
4 => (5, 1),
|
||||
other => panic!("format {other}"),
|
||||
};
|
||||
let row = width * bps;
|
||||
let across = row.div_ceil(TILE);
|
||||
let mut planes = Vec::new();
|
||||
for c in 1..=channels {
|
||||
let digit = b'0' + c as u8;
|
||||
let Some(stream::Value::Array(states)) = doc.field(bitmap, &[b'S', b't', b'a', digit]) else { panic!("states of channel {c}") };
|
||||
let mut stored = doc.objs(bitmap, &[b'I', b'd', b'x', digit]).into_iter();
|
||||
let mut plane = vec![0u8; row * height];
|
||||
for (t, state) in states.iter().enumerate().take(across * height.div_ceil(TILE)) {
|
||||
let tile: Vec<u8> = match state {
|
||||
stream::Value::UInt(2) => vec![0xFF; TILE * TILE],
|
||||
stream::Value::UInt(4) => {
|
||||
let name = doc.entry(stored.next().unwrap(), b"Data").unwrap().to_string();
|
||||
let data = archive.read(&name).unwrap();
|
||||
assert_eq!(data.len(), TILE * TILE, "{name}");
|
||||
data
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let (ox, oy) = ((t % across) * TILE, (t / across) * TILE);
|
||||
for y in oy..(oy + TILE).min(height) {
|
||||
for x in ox..(ox + TILE).min(row) {
|
||||
plane[y * row + x] = tile[(y - oy) * TILE + x - ox];
|
||||
}
|
||||
}
|
||||
}
|
||||
planes.push(plane);
|
||||
}
|
||||
let sample = |c: usize, i: usize| -> u8 {
|
||||
if bps == 1 {
|
||||
planes[c][i]
|
||||
} else {
|
||||
let v = u32::from(u16::from_le_bytes([planes[c][2 * i], planes[c][2 * i + 1]]));
|
||||
u8::try_from((v * 255 + 32767) / 65535).unwrap()
|
||||
}
|
||||
};
|
||||
let pixels = (0..width * height).flat_map(|i| (0..channels).map(move |c| (c, i))).map(|(c, i)| sample(c, i)).collect();
|
||||
(u32::try_from(width).unwrap(), u32::try_from(height).unwrap(), pixels)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
|
||||
let Some((bytes, doc, images)) = read_fixture("patchy-embedded-jpeg.af") else { return };
|
||||
@@ -68,8 +132,8 @@ fn lazy_placed_images_keep_the_original_encoded_bytes() {
|
||||
|
||||
#[test]
|
||||
fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
|
||||
let Some((_, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
|
||||
let (_, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
|
||||
let Some((bytes8, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
|
||||
let (bytes16, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
|
||||
assert!(doc8.warnings.is_empty());
|
||||
assert!(doc16.warnings.is_empty());
|
||||
assert_eq!(images8.len(), 1);
|
||||
@@ -80,13 +144,13 @@ fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
|
||||
assert_eq!(&pixels[..4], &[0, 0, 0, 128]);
|
||||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] < 255));
|
||||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
|
||||
// Frozen pixel-retention baseline, including every alpha sample. It is not a render oracle.
|
||||
assert_eq!(crc32fast::hash(pixels), 0xc8ee4dc1);
|
||||
assert_eq!(tiled_pixels(&bytes8), (64, 48, pixels.clone()));
|
||||
assert_eq!(tiled_pixels(&bytes16), (64, 48, pixels.clone()), "16-bit samples scaled to 8 bits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_scaled_pixels_keep_the_full_affine_transform() {
|
||||
let Some((_, doc, images)) = read_fixture("patchy-transform.af") else { return };
|
||||
let Some((bytes, doc, images)) = read_fixture("patchy-transform.af") else { return };
|
||||
assert!(doc.warnings.is_empty());
|
||||
assert_eq!(images.len(), 1);
|
||||
assert_eq!((images[0].width, images[0].height), (80, 60));
|
||||
@@ -97,18 +161,19 @@ fn rotated_scaled_pixels_keep_the_full_affine_transform() {
|
||||
let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() };
|
||||
assert_eq!(pixels.len(), 80 * 60 * 4);
|
||||
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
|
||||
assert_eq!(crc32fast::hash(pixels), 0x3720a442);
|
||||
assert_eq!(tiled_pixels(&bytes), (80, 60, pixels.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() {
|
||||
// CMYK layers keep their inks for the importer to convert through a colour profile.
|
||||
let Some((_, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
|
||||
let Some((bytes, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
|
||||
assert_eq!(images.len(), 1);
|
||||
assert_eq!((images[0].width, images[0].height), (64, 48));
|
||||
let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() };
|
||||
assert_eq!(pixels.len(), 64 * 48 * 5);
|
||||
assert_eq!(crc32fast::hash(pixels), 0x56b1f659);
|
||||
assert_eq!(tiled_pixels(&bytes), (64, 48, pixels.clone()));
|
||||
assert!(pixels.as_chunks::<5>().0.iter().any(|p| p[0] != p[3]), "inks differ between channels");
|
||||
assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings);
|
||||
assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile");
|
||||
let (_, lab, images) = read_fixture("patchy-lab.af").unwrap();
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
|
||||
affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
|
||||
affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
|
||||
affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
|
||||
patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
|
||||
patchy-blend-affinity.af dpi=72;spreads=1;model_crc32=8497c917;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
|
||||
patchy-cmyk.af dpi=72;spreads=1;model_crc32=56754ce9;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-dpi300.af dpi=300;spreads=1;model_crc32=2561f9d3;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-embedded-jpeg.af dpi=72;spreads=1;model_crc32=ab4b6fbf;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-fx-blur.af dpi=72;spreads=1;model_crc32=29b5083b;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
|
||||
patchy-fx-gradient.af dpi=72;spreads=1;model_crc32=96cd10be;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
|
||||
patchy-fx.af dpi=72;spreads=1;model_crc32=7c8d4d20;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
|
||||
patchy-group.af dpi=72;spreads=1;model_crc32=dc37ab6c;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-incremental-chain.af dpi=72;spreads=1;model_crc32=38c9c5f4;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-lab.af dpi=72;spreads=1;model_crc32=df3a4e40;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
|
||||
patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
|
||||
patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-frame.af dpi=72;spreads=1;model_crc32=3bff8ef9;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-indent.af dpi=72;spreads=1;model_crc32=dc36dfc5;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-para-spacing.af dpi=72;spreads=1;model_crc32=6408f39b;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
|
||||
patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
|
||||
patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
|
||||
affinity3-mexican-guy.af dpi=300;spreads=1;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
|
||||
affinity3-mexican-man.af dpi=300;spreads=1;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
|
||||
affinity3-mexican-woman.af dpi=300;spreads=1;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
|
||||
affinity3-playing-cards.af dpi=300;spreads=1;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
|
||||
patchy-adjust-curves.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-adjust-hsl.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-artboards.af dpi=72;spreads=1;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
|
||||
patchy-blend-affinity.af dpi=72;spreads=1;counts={"depth": 2, "fills": 8, "gradients": 0, "images": 1, "layers": 1, "nodes": 10, "segments": 24, "shapes": 8, "strokes": 0, "subpaths": 8};boards=[];fonts={};warnings=["an unknown blend mode (imported as Normal) (2×)"]
|
||||
patchy-cmyk.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-dpi300.af dpi=300;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-embedded-jpeg.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-fx-blur.af dpi=72;spreads=1;counts={"depth": 1, "images": 2, "nodes": 2};boards=[];fonts={};warnings=["blur effects (left out) (2×)"]
|
||||
patchy-fx-gradient.af dpi=72;spreads=1;counts={"depth": 1, "images": 3, "nodes": 3};boards=[];fonts={};warnings=[]
|
||||
patchy-fx.af dpi=72;spreads=1;counts={"depth": 1, "images": 5, "nodes": 5};boards=[];fonts={};warnings=[]
|
||||
patchy-group.af dpi=72;spreads=1;counts={"depth": 2, "images": 3, "layers": 1, "nodes": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-incremental-chain.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-lab.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "unsupported": 1};boards=[];fonts={};warnings=["pixel layers in grey, Lab or 32-bit formats"]
|
||||
patchy-lazy-placed.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-live-filter.af dpi=72;spreads=1;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
|
||||
patchy-rgba16.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-rgba8.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes-2.af dpi=72;spreads=1;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes.af dpi=72;spreads=1;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-text-artistic.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-caps.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-frame.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 11, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-indent.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 2, "text_chars": 104, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
patchy-text-para-spacing.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 13, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-rotated.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)"]
|
||||
patchy-text-runs.af dpi=72;spreads=1;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
|
||||
patchy-transform.af dpi=72;spreads=1;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-vector-mask.af dpi=72;spreads=1;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
|
||||
patchy-vector.af dpi=72;spreads=1;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
|
||||
@@ -1,8 +1,7 @@
|
||||
//! Structural regression signatures, measured from the pinned files through our own reader.
|
||||
//! These freeze feature retention; they are not independent visual or compatibility oracles.
|
||||
//! The model CRC covers every decoded field via its Debug representation (including paths,
|
||||
//! paint, masks, image pixels and text runs). A deliberate reader/Debug change needs review;
|
||||
//! input authenticity is independently checked with SHA256 by the corpus gate.
|
||||
//! They count retained features; they are not independent visual or compatibility oracles.
|
||||
//! Pixels are checked against the stored tiles in `raster.rs`. Input authenticity is checked
|
||||
//! with SHA256 by the corpus gate.
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use vectorcraft_affinity::model::{Document, Kind, Node};
|
||||
use vectorcraft_affinity::paint::Paint;
|
||||
@@ -58,11 +57,5 @@ pub fn signature(doc: &Document) -> String {
|
||||
for spread in &doc.spreads {
|
||||
visit(&spread.nodes, &mut counts, &mut fonts, &mut boards, 1);
|
||||
}
|
||||
let model_crc32 = crc32fast::hash(format!("{:?}", doc.spreads).as_bytes());
|
||||
format!(
|
||||
"dpi={};spreads={};model_crc32={model_crc32:08x};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}",
|
||||
doc.dpi,
|
||||
doc.spreads.len(),
|
||||
doc.warnings
|
||||
)
|
||||
format!("dpi={};spreads={};counts={counts:?};boards={boards:?};fonts={fonts:?};warnings={:?}", doc.dpi, doc.spreads.len(), doc.warnings)
|
||||
}
|
||||
@@ -894,7 +894,7 @@ fn trimmed_bristle_strands_read_pressure_where_they_begin() {
|
||||
}
|
||||
let (_, neutral_width) = start(neutral);
|
||||
let expected = 0.5 + x / 80.0;
|
||||
assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
|
||||
assert!((width / neutral_width - expected).abs() < 0.02, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
|
||||
checked = true;
|
||||
}
|
||||
assert!(checked, "at least one strand begins past the pressure ramp's first eighth");
|
||||
@@ -1967,7 +1967,8 @@ fn pressure_varies_angle_and_roundness() {
|
||||
let b = Brush { name: "r".into(), kind: BrushKind::Calligraphic(vertical.clone()) };
|
||||
bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 0.0, 100.0), &pressed(vec![(0.0, p), (1.0, p)]))).width()
|
||||
};
|
||||
assert!(near(wide(0.0), 0.1, 0.05), "{}", wide(0.0));
|
||||
// Roundness 1% of the 10 pt size.
|
||||
assert!(near(wide(0.0), 0.1, 1e-6), "{}", wide(0.0));
|
||||
assert!(near(wide(1.0), 10.0, 0.05), "{}", wide(1.0));
|
||||
// The angle turns on past 180°: 170 + 40 is 210°, the nib at 30° (not stopped at 180°).
|
||||
let turned = Calligraphic { angle: 170.0, roundness: 10.0, variation: [40.0, 0.0, 0.0], ..c([Pressure, Fixed, Fixed]) };
|
||||
|
||||
+96
-6
@@ -1543,13 +1543,103 @@ fn export_bytes_match_shared_writer_goldens() {
|
||||
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
|
||||
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
|
||||
let path = dir.join(name);
|
||||
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&path, got).unwrap();
|
||||
continue;
|
||||
}
|
||||
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
assert_holds_shapes_doc(&expected, version);
|
||||
if got != expected {
|
||||
// Written for review only; a golden file changes by hand after its drawing checks pass.
|
||||
let actual = std::env::temp_dir().join(format!("{name}.actual"));
|
||||
let saved = std::fs::write(&actual, got).map_or_else(|e| format!("not saved: {e}"), |()| format!("saved to {}", actual.display()));
|
||||
panic!("DXF bytes changed versus {} (output {saved})", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that a golden file holds [`shapes_doc`] as the DXF Reference describes it, in a 200 × 100 pt
|
||||
/// region with y up: the red fill and the black 1 pt stroke of the rectangle (10, 40)–(110, 90), and
|
||||
/// the blue 2 pt circle of radius 30 around (150, 50). ACI colors 1, 5 and 7 are red, blue and
|
||||
/// black/white; code 420 holds 0xRRGGBB; code 370 is lineweight in hundredths of a millimeter
|
||||
/// (1 pt = 0.3528 mm gives 35, 2 pt gives 70); a POLYLINE vertex's bulge is tan(arc angle / 4).
|
||||
fn assert_holds_shapes_doc(golden: &str, version: DxfVersion) {
|
||||
let ents = section(&pairs(golden.as_bytes()), "ENTITIES");
|
||||
let colored = |aci: &str| -> Vec<&Pairs> { ents.iter().filter(|e| get(e, 62) == Some(aci)).collect() };
|
||||
// Every drawn point of the entities in one color; (0, 0) is the elevation point of POLYLINE
|
||||
// and HATCH headers, which no shape of the drawing reaches.
|
||||
let points = |aci: &str| -> Vec<(f64, f64)> {
|
||||
colored(aci).iter().flat_map(|e| all(e, 10).into_iter().zip(all(e, 20))).filter(|p| *p != (0.0, 0.0)).collect()
|
||||
};
|
||||
let bbox = |pts: &[(f64, f64)]| {
|
||||
pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)))
|
||||
};
|
||||
for aci in ["1", "7"] {
|
||||
let pts = points(aci);
|
||||
assert_eq!(pts.len() % 4, 0, "{version:?} ACI {aci}: rectangle corners {pts:?}");
|
||||
assert_eq!(bbox(&pts), (10.0, 40.0, 110.0, 90.0), "{version:?} ACI {aci}");
|
||||
// Each run of four points is one outline of the rectangle: all four corners, each joined to
|
||||
// the next (and the last to the first) by a horizontal or vertical edge.
|
||||
let corners = [(10.0, 40.0), (110.0, 40.0), (110.0, 90.0), (10.0, 90.0)];
|
||||
for quad in pts.chunks(4) {
|
||||
assert!(corners.iter().all(|c| quad.contains(c)), "{version:?} ACI {aci}: corners {quad:?}");
|
||||
for (i, a) in quad.iter().enumerate() {
|
||||
let b = quad[(i + 1) % 4];
|
||||
assert!((a.0 == b.0) != (a.1 == b.1), "{version:?} ACI {aci}: edge {a:?} to {b:?} in {quad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let circle = colored("5");
|
||||
assert!(!circle.is_empty(), "{version:?}: the blue circle");
|
||||
if let Some(c) = circle.iter().find(|e| kind(e) == "CIRCLE") {
|
||||
assert_eq!((all(c, 10), all(c, 20), all(c, 40)), (vec![150.0], vec![50.0], vec![30.0]), "{version:?}");
|
||||
} else {
|
||||
let pts = points("5");
|
||||
assert!(pts.len() >= 2, "{version:?}: circle vertices {pts:?}");
|
||||
for (x, y) in &pts {
|
||||
assert!(((x - 150.0).hypot(y - 50.0) - 30.0).abs() < 1e-4, "{version:?}: vertex ({x}, {y}) off the circle");
|
||||
}
|
||||
let turn: f64 = circle.iter().flat_map(|e| all(e, 42)).map(|b| 4.0 * b.atan()).sum();
|
||||
assert!((turn.abs() - std::f64::consts::TAU).abs() < 1e-4, "{version:?}: bulges sweep {turn} rad");
|
||||
// Each segment, the closing one included, is an arc of the circle: the point halfway along it,
|
||||
// which lies bulge × chord / 2 to the right of the chord's middle, is on the circle too.
|
||||
let mut verts: Vec<((f64, f64), f64)> = Vec::new();
|
||||
for e in &circle {
|
||||
let mut x = None;
|
||||
for (c, v) in e.iter() {
|
||||
let n = || v.trim().parse::<f64>().expect("a number");
|
||||
match c {
|
||||
10 => x = Some(n()),
|
||||
20 => {
|
||||
let p = (x.take().unwrap_or(f64::NAN), n());
|
||||
if p != (0.0, 0.0) {
|
||||
verts.push((p, 0.0));
|
||||
}
|
||||
}
|
||||
42 => {
|
||||
if let Some(last) = verts.last_mut() {
|
||||
last.1 = n();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, &((px, py), b)) in verts.iter().enumerate() {
|
||||
let (qx, qy) = verts[(i + 1) % verts.len()].0;
|
||||
let (mx, my) = (px + (qx - px) / 2.0 + b * (qy - py) / 2.0, py + (qy - py) / 2.0 - b * (qx - px) / 2.0);
|
||||
assert!(
|
||||
((mx - 150.0).hypot(my - 50.0) - 30.0).abs() < 1e-4,
|
||||
"{version:?}: segment ({px}, {py}) to ({qx}, {qy}) with bulge {b} leaves the circle at ({mx}, {my})"
|
||||
);
|
||||
}
|
||||
}
|
||||
if version >= DxfVersion::R2000 {
|
||||
let code = |aci: &str, c: i32| -> Vec<String> { colored(aci).iter().filter_map(|e| get(e, c)).map(str::to_string).collect() };
|
||||
assert!(code("1", 420).iter().all(|v| v == "16711680") && !code("1", 420).is_empty(), "{version:?}: red true color");
|
||||
assert_eq!(code("7", 420), ["0"], "{version:?}: black true color");
|
||||
assert_eq!(code("5", 420), ["255"], "{version:?}: blue true color");
|
||||
assert_eq!(code("7", 370), ["35"], "{version:?}: 1 pt stroke");
|
||||
assert_eq!(code("5", 370), ["70"], "{version:?}: 2 pt stroke");
|
||||
} else {
|
||||
let stroke = colored("7");
|
||||
assert_eq!((all(stroke[0], 40), all(stroke[0], 41)), (vec![1.0], vec![1.0]), "{version:?}: 1 pt polyline width");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -685,7 +685,9 @@ mod tests {
|
||||
let mid = f.split_line(0, 0, 0.5).unwrap();
|
||||
assert_eq!((mid, &f.lines[0]), (3, &vec![0, 3, 1, 2]));
|
||||
let p = f.points[3];
|
||||
assert!(p.at.y.abs() < 1e-9 && p.at.x > 0.0 && p.at.x < 100.0 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}");
|
||||
// The Catmull-Rom segment from (0, 0) to (100, 0), with (200, 0) after it, is at x = 43.75
|
||||
// half way, not at the straight line's 50.
|
||||
assert!(p.at.y.abs() < 1e-9 && (p.at.x - 43.75).abs() < 1e-9 && (p.opacity - 0.75).abs() < 1e-6, "on the curve, half way: {p:?}");
|
||||
assert!(f.remove_point(1));
|
||||
assert_eq!(f.lines, vec![vec![0, 2, 1]]);
|
||||
assert!(f.add_line(vec![0, 9]).is_err() && f.add_line(vec![0]).is_err());
|
||||
|
||||
@@ -1379,7 +1379,7 @@ fn diamond_pixels_follow_the_squares() {
|
||||
g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0));
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect();
|
||||
// White at the center, black in the corners, and the same on each side of it.
|
||||
assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}");
|
||||
assert_eq!((px[2 * 5 + 2], px[0], px[24]), ([255, 255, 255, 255], [0, 0, 0, 255], [0, 0, 0, 255]), "{px:?}");
|
||||
assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]);
|
||||
assert_eq!(px[5 + 2], px[3 * 5 + 2]);
|
||||
assert_eq!(px[2 * 5 + 1], px[5 + 2]);
|
||||
|
||||
@@ -108,6 +108,7 @@ impl GraphDesign {
|
||||
let mut e = n.extras_mut();
|
||||
e.graph = None;
|
||||
e.series_index = None;
|
||||
e.graph_design_art = false;
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let old = std::mem::take(ch);
|
||||
|
||||
@@ -457,7 +457,7 @@ mod tests {
|
||||
n.transform(Affine::scale_non_uniform(1.0, 0.25), false);
|
||||
assert!(n.extras().image_quad.is_none());
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}");
|
||||
assert!(b.height() < 1e-6 && (b.x0 + 200.0 / 9.0).abs() < 1e-6 && (b.x1 - 1400.0 / 9.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// A file's corners that the image cannot take are dropped as it is read, so a later scale
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct NodeExtras {
|
||||
/// Index of the graph series this generated group belongs to. Axes, the legend and other
|
||||
/// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them.
|
||||
pub series_index: Option<u32>,
|
||||
/// This object is a generated copy of a graph column or marker design.
|
||||
pub graph_design_art: bool,
|
||||
/// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale
|
||||
/// the placed gradients in it with the outlines.
|
||||
pub type_outlines: bool,
|
||||
@@ -108,6 +110,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
wrap: None,
|
||||
graph: None,
|
||||
series_index: None,
|
||||
graph_design_art: false,
|
||||
type_outlines: false,
|
||||
pixelated: false,
|
||||
shaper: None,
|
||||
|
||||
@@ -13,6 +13,7 @@ fn extras_are_written_flat_in_order() {
|
||||
e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true)));
|
||||
e.trace = Some(Box::new(serde_json::json!({"preset": "p"})));
|
||||
e.series_index = Some(2);
|
||||
e.graph_design_art = true;
|
||||
e.type_outlines = true;
|
||||
e.graphic_style = Some(3);
|
||||
e.attrs = Some(Box::default());
|
||||
@@ -59,6 +60,7 @@ fn extras_are_written_flat_in_order() {
|
||||
"mask",
|
||||
"trace",
|
||||
"series_index",
|
||||
"graph_design_art",
|
||||
"type_outlines",
|
||||
"kind",
|
||||
"graphic_style",
|
||||
|
||||
@@ -36,6 +36,7 @@ impl Serialize for Node {
|
||||
e.wrap.is_none(),
|
||||
e.graph.is_none(),
|
||||
e.series_index.is_none(),
|
||||
is_default(&e.graph_design_art),
|
||||
is_default(&e.type_outlines),
|
||||
is_default(&e.pixelated),
|
||||
e.shaper.is_none(),
|
||||
@@ -86,6 +87,7 @@ impl Serialize for Node {
|
||||
field!("wrap", &e.wrap);
|
||||
field!("graph", &e.graph);
|
||||
field!("series_index", &e.series_index);
|
||||
field!("graph_design_art", &e.graph_design_art);
|
||||
field!("type_outlines", &e.type_outlines);
|
||||
field!("pixelated", &e.pixelated);
|
||||
field!("shaper", &e.shaper);
|
||||
@@ -220,6 +222,8 @@ pub(super) struct NodeWire {
|
||||
#[serde(default)]
|
||||
series_index: Option<u32>,
|
||||
#[serde(default)]
|
||||
graph_design_art: bool,
|
||||
#[serde(default)]
|
||||
type_outlines: bool,
|
||||
#[serde(default)]
|
||||
pixelated: bool,
|
||||
@@ -480,6 +484,7 @@ impl From<NodeWire> for Node {
|
||||
wrap: w.wrap,
|
||||
graph: w.graph,
|
||||
series_index: w.series_index,
|
||||
graph_design_art: w.graph_design_art,
|
||||
type_outlines: w.type_outlines,
|
||||
pixelated: w.pixelated,
|
||||
shaper: w.shaper,
|
||||
|
||||
@@ -122,8 +122,12 @@ mod tests {
|
||||
// One stop doubles the light: sRGB 0.5 (linear 0.214) becomes linear 0.428, sRGB 0.686.
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": 1})).apply_rgb(grey), [0.686; 3]));
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": -20})).apply_rgb([1.0; 3]), [0.0; 3]));
|
||||
assert!(map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3])[0] > 0.3, "the offset lifts the shadows");
|
||||
assert!(map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey)[0] > 0.6);
|
||||
// The offset adds linear light: linear 0.1 is sRGB 0.349.
|
||||
let lifted = map(EXPOSURE, json!({"offset": 0.1})).apply_rgb([0.0; 3]);
|
||||
assert!(lifted.iter().all(|c| (c - 0.349_190_2).abs() < 1e-5), "the offset lifts the shadows: {lifted:?}");
|
||||
// Gamma 2 takes the square root of linear 0.214 (sRGB 0.5): linear 0.463, sRGB 0.710.
|
||||
let raised = map(EXPOSURE, json!({"gamma": 2})).apply_rgb(grey);
|
||||
assert!(raised.iter().all(|c| (c - 0.710_196).abs() < 1e-5), "{raised:?}");
|
||||
assert!(close(map(EXPOSURE, json!({"exposure": 1e300, "gamma": 0})).apply_rgb(grey), [1.0; 3]), "out of range values are clamped");
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, FillRule, PathData, Point, Rect, shapes};
|
||||
use vectorcraft_pathops::{self as po, BoolOp};
|
||||
|
||||
use crate::catalog::{EffectInfo, Lengths};
|
||||
@@ -43,7 +43,7 @@ pub(crate) fn catalog() -> Vec<EffectInfo> {
|
||||
id: HALFTONE,
|
||||
label: "Vector Halftone…",
|
||||
menu: &["Effect", "Color Effects"],
|
||||
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
|
||||
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
|
||||
defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}),
|
||||
raster: false,
|
||||
lengths: Lengths::default(),
|
||||
@@ -63,6 +63,12 @@ pub enum DotShape {
|
||||
Square,
|
||||
Diamond,
|
||||
Line,
|
||||
/// Round dots that grow into squares meeting corner to corner at 50% (a checkerboard), then
|
||||
/// round holes, as the Euclidean spot function draws them.
|
||||
Euclidean,
|
||||
/// Elongated dots that join along their long side at 40% into chains, along their short side
|
||||
/// at 60%, then elongated holes.
|
||||
Elliptical,
|
||||
}
|
||||
|
||||
impl DotShape {
|
||||
@@ -73,6 +79,8 @@ impl DotShape {
|
||||
"square" => DotShape::Square,
|
||||
"diamond" => DotShape::Diamond,
|
||||
"line" | "lines" => DotShape::Line,
|
||||
"euclidean" => DotShape::Euclidean,
|
||||
"elliptical" => DotShape::Elliptical,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -94,10 +102,227 @@ impl DotShape {
|
||||
DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)),
|
||||
// Cells along a row join into a line as thick as the tone.
|
||||
DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))),
|
||||
DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)),
|
||||
DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Elliptical)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Elliptical dot's height over its width: a dot as wide as its cell covers 40% of it
|
||||
/// (π × ratio / 4 = 0.4 of a quadrant).
|
||||
const ELLIPTICAL_RATIO: f64 = 1.6 / std::f64::consts::PI;
|
||||
|
||||
/// The Elliptical dot's middle-tone cut in a quadrant of half side 1, the line
|
||||
/// `ELLIPTICAL_CUT.0 × x + y = ELLIPTICAL_CUT.1`. It meets the side x = 1 at y = 0.25 and the y
|
||||
/// axis at 0.75 and runs through the quadrant's center, so the dot it cuts at 50% is its own
|
||||
/// complement: the dark bridges across the x side from 40%, and the y side stays light until 60%.
|
||||
const ELLIPTICAL_CUT: (f64, f64) = (0.5, 0.75);
|
||||
|
||||
/// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5.
|
||||
const SIZE_STEPS: usize = 512;
|
||||
|
||||
static EUCLIDEAN: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
static ELLIPTICAL: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
|
||||
/// The two spot-function dots.
|
||||
#[derive(Clone, Copy)]
|
||||
enum SpotKind {
|
||||
Euclidean,
|
||||
Elliptical,
|
||||
}
|
||||
|
||||
impl SpotKind {
|
||||
/// The first quadrant of the dot of width `a` in a quadrant of half side 1.
|
||||
fn quadrant(self, a: f64) -> Vec<CubicBez> {
|
||||
match self {
|
||||
SpotKind::Euclidean => quadrant(a, a, 1.0),
|
||||
SpotKind::Elliptical => elliptical_quadrant(a),
|
||||
}
|
||||
}
|
||||
|
||||
/// The width at which the dot covers half the cell.
|
||||
fn max_size(self) -> f64 {
|
||||
match self {
|
||||
SpotKind::Euclidean => 1.0,
|
||||
SpotKind::Elliptical => ELLIPTICAL_CUT.1 / ELLIPTICAL_RATIO,
|
||||
}
|
||||
}
|
||||
|
||||
fn table(self) -> &'static OnceLock<Vec<f64>> {
|
||||
match self {
|
||||
SpotKind::Euclidean => &EUCLIDEAN,
|
||||
SpotKind::Elliptical => &ELLIPTICAL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the dot of `kind` that covers that tone of the
|
||||
/// cell [-1, 1]².
|
||||
fn dot_sizes(kind: SpotKind) -> Vec<f64> {
|
||||
(0..=SIZE_STEPS)
|
||||
.map(|k| {
|
||||
// A quadrant of the cell has area 1.
|
||||
let target = k as f64 / SIZE_STEPS as f64 * 0.5;
|
||||
let (mut lo, mut hi) = (0.0, kind.max_size());
|
||||
for _ in 0..50 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if curves_area(&kind.quadrant(mid)) < target { lo = mid } else { hi = mid }
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The area between the origin and `curves`, which run from the x axis to the y axis.
|
||||
fn curves_area(curves: &[CubicBez]) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveArea;
|
||||
curves.iter().map(|c| c.signed_area()).sum()
|
||||
}
|
||||
|
||||
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`.
|
||||
fn ellipse_arc(out: &mut Vec<CubicBez>, a: f64, b: f64, t0: f64, t1: f64) {
|
||||
if t1 <= t0 {
|
||||
return;
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0);
|
||||
let d = (t1 - t0) / n;
|
||||
let k = 4.0 / 3.0 * (d / 4.0).tan();
|
||||
for i in 0..n as usize {
|
||||
let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0));
|
||||
let (p0, p3) = (at(u0), at(u1));
|
||||
let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos());
|
||||
let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos());
|
||||
out.push(CubicBez::new(p0, c1, c2, p3));
|
||||
}
|
||||
}
|
||||
|
||||
/// The straight segment from `p` to `q` as a cubic curve.
|
||||
fn segment(p: Point, q: Point) -> CubicBez {
|
||||
CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q)
|
||||
}
|
||||
|
||||
/// The first quadrant of the Elliptical dot of width `a` (height `ELLIPTICAL_RATIO × a`) in a
|
||||
/// quadrant of half side 1, from the x axis to the y axis. Up to width 1 (40%) it is the whole
|
||||
/// ellipse. Wider, the ellipse is clipped to the side x = 1, which makes a bridge to the next dot
|
||||
/// along x, and to the cut line [`ELLIPTICAL_CUT`], which keeps it off the y side.
|
||||
fn elliptical_quadrant(a: f64) -> Vec<CubicBez> {
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
let b = a * ELLIPTICAL_RATIO;
|
||||
let mut out = vec![];
|
||||
if a <= 1.0 {
|
||||
ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let (m, c) = ELLIPTICAL_CUT;
|
||||
// The ellipse crosses the side x = 1 at angle t0.
|
||||
let t0 = (1.0 / a).acos();
|
||||
// Between angles ts and te the ellipse lies beyond the cut line.
|
||||
let r = (m * a).hypot(b);
|
||||
let (ts, te) = if r > c {
|
||||
let (phi, alpha) = (b.atan2(m * a), (c / r).acos());
|
||||
(phi - alpha, phi + alpha)
|
||||
} else {
|
||||
(FRAC_PI_2, FRAC_PI_2)
|
||||
};
|
||||
let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, c) };
|
||||
out.push(segment(Point::new(1.0, 0.0), if t0 < ts || t0 >= te { at(t0) } else { Point::new(1.0, c - m) }));
|
||||
if t0 >= te {
|
||||
ellipse_arc(&mut out, a, b, t0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
if t0 < ts {
|
||||
ellipse_arc(&mut out, a, b, t0, ts.min(FRAC_PI_2));
|
||||
if ts >= FRAC_PI_2 {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
let from = out.last().map_or(Point::new(1.0, 0.0), |q| q.p3);
|
||||
out.push(segment(from, end));
|
||||
ellipse_arc(&mut out, a, b, te, FRAC_PI_2);
|
||||
out
|
||||
}
|
||||
|
||||
/// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤
|
||||
/// `h`, from its point on the x axis to its point on the y axis, as cubic curves.
|
||||
fn quadrant(a: f64, b: f64, h: f64) -> Vec<CubicBez> {
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let mut out = vec![];
|
||||
let r = a.hypot(b);
|
||||
if r <= h {
|
||||
ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
let (phi, alpha) = (b.atan2(a), (h / r).acos());
|
||||
let (ts, te) = (phi - alpha, phi + alpha);
|
||||
let start = if ts > 0.0 {
|
||||
ellipse_arc(&mut out, a, b, 0.0, ts);
|
||||
at(ts)
|
||||
} else {
|
||||
Point::new(h, 0.0)
|
||||
};
|
||||
let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) };
|
||||
out.push(segment(start, end));
|
||||
ellipse_arc(&mut out, a, b, te, FRAC_PI_2);
|
||||
out
|
||||
}
|
||||
|
||||
/// `curves` reversed, each curve run backwards.
|
||||
fn reversed(curves: &[CubicBez]) -> Vec<CubicBez> {
|
||||
curves.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect()
|
||||
}
|
||||
|
||||
/// `curves` with each point mapped by `f`.
|
||||
fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec<CubicBez> {
|
||||
curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect()
|
||||
}
|
||||
|
||||
/// The quadrant of the `kind` spot for tone `u` (0..0.5) in a cell of half side `h`, its size from
|
||||
/// the kind's table ([`dot_sizes`]).
|
||||
fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec<CubicBez> {
|
||||
let sizes = kind.table().get_or_init(|| dot_sizes(kind));
|
||||
let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64;
|
||||
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
|
||||
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
|
||||
let a = lo + (hi - lo) * (x - i as f64);
|
||||
mapped(&kind.quadrant(a), |p| Point::new(p.x * h, p.y * h))
|
||||
}
|
||||
|
||||
/// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to
|
||||
/// half tone, the `kind` dot with the tone's area (Euclidean: a circle clipped to the cell's
|
||||
/// diamond; Elliptical: an ellipse clipped to the cell's sides and its middle-tone cut); past half,
|
||||
/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the
|
||||
/// light becomes holes.
|
||||
fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
}
|
||||
};
|
||||
if t <= 0.5 {
|
||||
let q1 = spot_quadrant(t, h, kind);
|
||||
add(q1.clone(), true);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false);
|
||||
add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false);
|
||||
} else {
|
||||
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
|
||||
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
|
||||
}
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
/// One screen: its ink and angle, and how to read its tone from a sampled pixel.
|
||||
struct Screen {
|
||||
paint: Color,
|
||||
@@ -399,6 +624,7 @@ pub fn halftone_art(d: &Document, n: &Node) -> Option<Node> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::Shape;
|
||||
|
||||
/// A black square's samples: `side` points of black from (10, 10), white around it.
|
||||
fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) {
|
||||
@@ -464,6 +690,73 @@ mod tests {
|
||||
assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2);
|
||||
}
|
||||
|
||||
/// Is `p` (in cells of side 1) inside the dot `shape` draws for tone `t`?
|
||||
fn covers(shape: DotShape, t: f64, p: (f64, f64)) -> bool {
|
||||
fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_dots_cover_the_tone() {
|
||||
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
|
||||
for k in 1..100 {
|
||||
let t = f64::from(k) / 100.0;
|
||||
let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0;
|
||||
assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}");
|
||||
let b = shape.path(t, 2.0).control_bounds().unwrap();
|
||||
assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn euclidean_dots_meet_corner_to_corner_at_half() {
|
||||
let s = DotShape::Euclidean;
|
||||
// Round dots apart from their neighbors below half.
|
||||
assert!(!covers(s, 0.45, (0.49, 0.0)) && !covers(s, 0.45, (0.0, 0.49)) && covers(s, 0.45, (0.3, 0.0)));
|
||||
// At half the dot is the diamond reaching the middle of each side: a checkerboard.
|
||||
for p in [(0.49, 0.0), (-0.49, 0.0), (0.0, 0.49), (0.0, -0.49)] {
|
||||
assert!(covers(s, 0.5, p), "{p:?}");
|
||||
}
|
||||
assert!(!covers(s, 0.5, (0.26, 0.26)) && covers(s, 0.5, (0.24, 0.24)));
|
||||
// Past half the light becomes round holes at the corners.
|
||||
assert!(covers(s, 0.55, (0.0, 0.499)) && covers(s, 0.55, (0.499, 0.0)) && !covers(s, 0.55, (0.49, 0.49)));
|
||||
assert!(covers(s, 0.99, (0.3, 0.3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elliptical_dots_join_along_their_length_then_their_width() {
|
||||
let s = DotShape::Elliptical;
|
||||
// Below 40% the dots stand apart.
|
||||
assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45)));
|
||||
// From 40% they reach their neighbors along x, making chains, but not along y.
|
||||
assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45)));
|
||||
// The chains are bridges as tall as the tone allows across the shared side, not single
|
||||
// points: off the axis on the side x = 0.5, and on the cell's other side by symmetry.
|
||||
assert!(covers(s, 0.46, (0.499, 0.03)) && covers(s, 0.46, (-0.499, -0.03)) && !covers(s, 0.46, (0.499, 0.2)));
|
||||
assert!(covers(s, 0.5, (0.499, 0.12)) && !covers(s, 0.5, (0.499, 0.13)) && !covers(s, 0.5, (0.0, 0.49)));
|
||||
// Up to 60% the light still runs along the top edge between the corner holes.
|
||||
assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3)));
|
||||
// Past 60% the dark joins across the top edge too, leaving elongated holes.
|
||||
assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49)));
|
||||
// The holes are longer along x than along y.
|
||||
assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {ELLIPTICAL_RATIO}");
|
||||
// Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall.
|
||||
let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap();
|
||||
assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_shapes_make_dots_through_the_screen() {
|
||||
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
|
||||
let h = Halftone::of(&effect(json!({"frequency": 18, "shape": format!("{shape:?}")}))).unwrap();
|
||||
assert_eq!(h.shape, shape);
|
||||
let (s, b) = black_square(60.0, &h);
|
||||
let (layers, dots) = h.layers(&s, b, None);
|
||||
assert!(layers.len() == 1 && (150..=320).contains(&dots), "{shape:?}: {dots}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caps_refuse_too_many_cells() {
|
||||
let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap();
|
||||
|
||||
@@ -744,7 +744,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"pixelate.colorHalftone",
|
||||
"Color Halftone…",
|
||||
PIXELATE,
|
||||
"{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell",
|
||||
"{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} The effect screens cyan, magenta and yellow ink (channels 1 to 3; CMYK mode adds black as channel 4) at their angles into dots whose area follows the cell's mean ink coverage.",
|
||||
json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}),
|
||||
),
|
||||
r(
|
||||
|
||||
@@ -437,7 +437,7 @@ impl Screen {
|
||||
|
||||
/// Color Halftone: each channel screened at its angle in square cells sized so that a dot of
|
||||
/// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's
|
||||
/// dot covers the share of it that is the channel's mean there (white stays white, black black).
|
||||
/// dot covers the mean ink coverage of that cell (white stays white, black black).
|
||||
/// Coverage stays as it is.
|
||||
pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) {
|
||||
let Some(place) = Place::new(space, w, h) else { return };
|
||||
@@ -446,7 +446,8 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix
|
||||
if !(side.is_finite() && side / place.px >= 3.0) {
|
||||
return;
|
||||
}
|
||||
let channels = space.channels;
|
||||
// Screen RGB as dark ink against white, like the CMY channel previews.
|
||||
let channels = if space.channels == Channels::Rgb { Channels::CmyPlane } else { space.channels };
|
||||
let n = split([0; 4], channels).1;
|
||||
let limit = w.saturating_mul(h).saturating_add(4096);
|
||||
let mut screens = Vec::with_capacity(n);
|
||||
@@ -478,7 +479,7 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix
|
||||
let mean = if sum[1] > 1e-6 { f64::from(sum[0] / sum[1]) } else { 0.0 };
|
||||
// Full strength fills the cell, corners too; none leaves no speck.
|
||||
let radius = match mean {
|
||||
m if m >= 254.5 / 255.0 => f64::INFINITY,
|
||||
m if m >= 254.5 / 255.0 => side / std::f64::consts::SQRT_2 + 0.5 * place.px,
|
||||
m if m <= 0.5 / 255.0 => 0.0,
|
||||
m => dot_radius(m) * side,
|
||||
};
|
||||
|
||||
@@ -694,11 +694,6 @@ fn smart_blur_smooths_noise_and_keeps_edges() {
|
||||
assert_eq!(at(&all, w, 20, 10)[0], 255, "a 155-level step is still past 100");
|
||||
}
|
||||
|
||||
/// FNV-1a of `bytes`.
|
||||
fn digest(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
let (w, h) = (48, 40);
|
||||
@@ -706,7 +701,6 @@ fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
let a = if x > 4 && y < 36 { 255 } else { 128 };
|
||||
[((x * 5 + y) as u8).min(a), ((y * 6) as u8).min(a), (((x * y) % 97) as u8).min(a), a]
|
||||
});
|
||||
let mut sums = Vec::new();
|
||||
for p in [json!({}), json!({"radius": 2, "threshold": 10, "quality": "high"}), json!({"radius": 12, "threshold": 40, "quality": "low"})] {
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", p.clone()).apply(&mut d, w, h, &space(w, h));
|
||||
@@ -715,10 +709,127 @@ fn smart_blur_normal_mode_keeps_its_pixels() {
|
||||
p["blurMode"] = json!("normal");
|
||||
fx("blur.smart", p).apply(&mut normal, w, h, &space(w, h));
|
||||
assert_eq!(d, normal);
|
||||
sums.push(digest(&d));
|
||||
}
|
||||
// The pixels Smart Blur gave before it had a mode.
|
||||
assert_eq!(sums, [11495339692959753241, 14281410954765351056, 5111933201350526354]);
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 1 averages each pixel with the neighbours whose channels, alpha included,
|
||||
/// all lie within the threshold: grays 100 and 110 average to 105 each, 200 is 90 levels from 110
|
||||
/// and stays, and the two grays 100 after it have the same color but alpha 255 and 128, so neither
|
||||
/// takes the other.
|
||||
#[test]
|
||||
fn smart_blur_averages_only_the_neighbours_within_the_threshold() {
|
||||
let (w, h) = (5, 1);
|
||||
let src = image(w, h, |x, _| match x {
|
||||
0 => [100, 100, 100, 255],
|
||||
1 => [110, 110, 110, 255],
|
||||
2 => [200, 200, 200, 255],
|
||||
3 => [100, 100, 100, 255],
|
||||
_ => [100, 100, 100, 128],
|
||||
});
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 1, "threshold": 20})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 0, 0), [105, 105, 105, 255]);
|
||||
assert_eq!(at(&d, w, 1, 0), [105, 105, 105, 255]);
|
||||
assert_eq!(at(&d, w, 2, 0), [200, 200, 200, 255]);
|
||||
assert_eq!(at(&d, w, 3, 0), at(&src, w, 3, 0));
|
||||
assert_eq!(at(&d, w, 4, 0), at(&src, w, 4, 0));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 12 reads its neighbours from a box-blurred copy. Next to a step from gray
|
||||
/// 100 to gray 200 that copy holds values between them, so at threshold 50 the pixel on the dark
|
||||
/// side of the step takes in some lighter gray and the pixel on the light side some darker gray,
|
||||
/// while pixels more than 15 pixels from the step keep their gray. Medium quality takes in less of
|
||||
/// the other gray than low, and at threshold 30 the pixels next to the step keep their gray.
|
||||
#[test]
|
||||
fn smart_blur_at_a_wide_radius_reads_the_blurred_copy_next_to_an_edge() {
|
||||
let (w, h) = (60, 40);
|
||||
let src = image(w, h, |x, _| grey(if x < 30 { 100 } else { 200 }));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "low"})).apply(&mut d, w, h, &space(w, h));
|
||||
let dark = at(&d, w, 29, 20)[0];
|
||||
let light = at(&d, w, 30, 20)[0];
|
||||
assert!((101..=150).contains(&dark), "the dark side takes in some lighter gray: {dark}");
|
||||
assert!((150..=199).contains(&light), "the light side takes in some darker gray: {light}");
|
||||
assert_eq!(at(&d, w, 10, 20), grey(100));
|
||||
assert_eq!(at(&d, w, 50, 20), grey(200));
|
||||
// Medium quality spreads 7 samples instead of 5, read from a copy blurred over 2 pixels instead
|
||||
// of 3, so less of the other gray reaches the pixels next to the step.
|
||||
let mut medium = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 50, "quality": "medium"})).apply(&mut medium, w, h, &space(w, h));
|
||||
let (medium_dark, medium_light) = (at(&medium, w, 29, 20)[0], at(&medium, w, 30, 20)[0]);
|
||||
assert!(100 < medium_dark && medium_dark < dark, "medium {medium_dark}, low {dark}");
|
||||
assert!(light < medium_light && medium_light < 200, "medium {medium_light}, low {light}");
|
||||
// At threshold 30 the blurred values next to the step are too far from both grays, and the
|
||||
// pixels on either side keep their gray.
|
||||
let mut sharp = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut sharp, w, h, &space(w, h));
|
||||
assert_eq!(at(&sharp, w, 29, 20), grey(100));
|
||||
assert_eq!(at(&sharp, w, 30, 20), grey(200));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 12 and low quality samples offsets 0, 6 and 12 pixels along each axis,
|
||||
/// in both directions, within distance 12.5. A one-column gray-200 stripe at x = 30 on gray 100
|
||||
/// becomes (6 * 100 + 200) / 7, about 114.29, in the copy box-blurred with radius 3. For the
|
||||
/// gray-100 pixel at (24, 20), only the three samples at x = 30 have blurred values above 100.
|
||||
/// Their own value 200 is outside threshold 30, so they are excluded and the result stays 100.
|
||||
/// Including them would average ten samples of 100 with three of about 114.29 and round to 103.
|
||||
#[test]
|
||||
fn smart_blur_at_a_wide_radius_rejects_a_stripes_own_value_outside_the_threshold() {
|
||||
let (w, h) = (60, 40);
|
||||
let src = image(w, h, |x, _| grey(if x == 30 { 200 } else { 100 }));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 12, "threshold": 30, "quality": "low"})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 24, 20), grey(100));
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 2 reaches two pixels each way: grays 100, 110 and 120 lie within 20 levels
|
||||
/// of each other and all average to 110 (at radius 1 the ends would give 105 and 115), 200 and 210
|
||||
/// average to 205, and 60 is too far from both groups and stays.
|
||||
#[test]
|
||||
fn smart_blur_at_radius_two_averages_the_neighbours_two_pixels_away() {
|
||||
let (w, h) = (6, 1);
|
||||
let src = image(w, h, |x, _| grey([100, 110, 120, 200, 210, 60][x]));
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h));
|
||||
let want = image(w, h, |x, _| grey([110, 110, 110, 205, 205, 60][x]));
|
||||
assert_eq!(d, want);
|
||||
}
|
||||
|
||||
/// Smart Blur at radius 2 and high quality reads the original pixels within distance 2.5.
|
||||
/// The center at (2, 2) is gray 100, one neighbor is gray 120, and the rest are gray 200,
|
||||
/// outside threshold 20. A neighbor at (4, 2) is two pixels away, so the center averages
|
||||
/// (100 + 120) / 2 = 110. A neighbor at (4, 4) is sqrt(8), about 2.83 pixels away, so it is
|
||||
/// excluded and the center stays 100. Reading the whole square would give 110 in both cases.
|
||||
#[test]
|
||||
fn smart_blur_at_radius_two_keeps_the_neighbours_inside_the_disc() {
|
||||
let (w, h) = (5, 5);
|
||||
for ((nx, ny), want) in [((4, 2), 110), ((4, 4), 100)] {
|
||||
let src = image(w, h, |x, y| match (x, y) {
|
||||
(2, 2) => grey(100),
|
||||
p if p == (nx, ny) => grey(120),
|
||||
_ => grey(200),
|
||||
});
|
||||
let mut d = src.clone();
|
||||
fx("blur.smart", json!({"radius": 2, "threshold": 20, "quality": "high"})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 2, 2), grey(want), "neighbor at ({nx}, {ny})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Smart Blur's default radius 3 and medium quality (7 samples) read every integer offset
|
||||
/// in the 7 by 7 square without prefiltering, keeping offsets within distance 3.5.
|
||||
/// The center at (3, 3) is gray 100, its neighbor at (6, 3) is gray 120, and the rest are
|
||||
/// gray 200, outside the default threshold 25. The center averages (100 + 120) / 2 = 110.
|
||||
/// A search limited to two pixels would leave the center at 100.
|
||||
#[test]
|
||||
fn smart_blur_default_radius_averages_the_neighbour_three_pixels_away() {
|
||||
let (w, h) = (7, 7);
|
||||
let mut d = image(w, h, |x, y| match (x, y) {
|
||||
(3, 3) => grey(100),
|
||||
(6, 3) => grey(120),
|
||||
_ => grey(200),
|
||||
});
|
||||
fx("blur.smart", json!({})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 3, 3), grey(110));
|
||||
}
|
||||
|
||||
/// Smart Blur's test image: grays 56 and 64 in a checkerboard for x < 3 and 66 and 74 for x in 3..6
|
||||
@@ -1070,13 +1181,44 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() {
|
||||
let mut half = image(w, h, |x, _| if x < 32 { grey(160) } else { [0; 4] });
|
||||
halftone.apply(&mut half, w, h, &space(w, h));
|
||||
assert!((0..h).all(|y| (32..w).all(|x| at(&half, w, x, y) == [0; 4])));
|
||||
// Dots are bigger where the image is brighter.
|
||||
// Brighter areas have fewer dark pixels.
|
||||
let mut ramp = image(w, h, |x, _| grey((x * 4) as u8));
|
||||
halftone.apply(&mut ramp, w, h, &space(w, h));
|
||||
let lit = |x0: usize| (0..h).flat_map(|y| (x0..x0 + 16).map(move |x| (x, y))).filter(|(x, y)| at(&ramp, w, *x, *y)[0] > 127).count();
|
||||
assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_draws_dark_dots_on_light_rgb() {
|
||||
let (w, h) = (64, 64);
|
||||
let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0}));
|
||||
let mut d = image(w, h, |_, _| grey(192));
|
||||
halftone.apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(at(&d, w, 37, 37), grey(0));
|
||||
assert_eq!(at(&d, w, 32, 32), grey(255));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_full_coverage_only_overlaps_the_edge_of_an_empty_neighbor() {
|
||||
let (w, h) = (96, 64);
|
||||
let source = image(w, h, |x, _| grey(if x < w / 2 { 0 } else { 255 }));
|
||||
let mut screened = source.clone();
|
||||
fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0})).apply(&mut screened, w, h, &space(w, h));
|
||||
let half_cell = (8.0 * std::f64::consts::SQRT_2 / 2.0) as usize;
|
||||
let (edge, y) = (w / 2, h / 2 + half_cell);
|
||||
assert_eq!(at(&screened, w, edge - half_cell, y), grey(0), "the full cell keeps its center");
|
||||
assert_eq!(at(&screened, w, edge, y), grey(0), "the round dot crosses the straight cell edge");
|
||||
let fringe = at(&screened, w, edge + 2, y)[0];
|
||||
assert!(fringe > 0 && fringe < 255, "the last overlapping column is antialiased: {fringe}");
|
||||
// With an 8 px radius and the grid aligned to this edge, the circle and its antialiasing
|
||||
// can reach only the first three columns of white. Check every row, including cell corners.
|
||||
for y in 0..h {
|
||||
for x in edge + 3..w {
|
||||
assert_eq!(at(&screened, w, x, y), grey(255), "unexpected ink at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() {
|
||||
// Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a
|
||||
|
||||
@@ -1343,10 +1343,11 @@ fn transform_copies_of_images_stop_at_the_reach_limit() {
|
||||
fn pucker_bloat_moves_anchors_in_opposite_directions() {
|
||||
let bloat = run("distort.puckerBloat", json!({"amount": 50}), &square());
|
||||
let a = bloat.subpaths[0].anchors[0].p;
|
||||
assert!(a.x > 0.0 && a.y > 0.0, "bloat pulls corners in: {a:?}");
|
||||
// Half the amount of the way to the centre (50, 50): 25% of 50 pt.
|
||||
assert!((a.x - 12.5).abs() < 1e-9 && (a.y - 12.5).abs() < 1e-9, "bloat pulls corners in: {a:?}");
|
||||
let pucker = run("distort.puckerBloat", json!({"amount": -50}), &square());
|
||||
let a = pucker.subpaths[0].anchors[0].p;
|
||||
assert!(a.x < 0.0 && a.y < 0.0, "pucker pushes corners out: {a:?}");
|
||||
assert!((a.x + 12.5).abs() < 1e-9 && (a.y + 12.5).abs() < 1e-9, "pucker pushes corners out: {a:?}");
|
||||
assert_eq!(run("distort.puckerBloat", json!({"amount": 0}), &square()), square());
|
||||
}
|
||||
|
||||
|
||||
@@ -5,11 +5,14 @@
|
||||
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
|
||||
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
|
||||
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
|
||||
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
|
||||
//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their
|
||||
//! visual bounds share, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
|
||||
//! (a view command) are the UI's.
|
||||
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object.
|
||||
//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view
|
||||
//! command) are the UI's.
|
||||
|
||||
pub mod marks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -18,7 +21,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{Node, NodeId, OrientedBox};
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
@@ -108,6 +111,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_multi,
|
||||
group_overlapping
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.groupRows",
|
||||
"Group by Row",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}",
|
||||
has_multi,
|
||||
group_rows
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"Randomize Opacity",
|
||||
@@ -127,6 +139,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
sort
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Exactly two objects are selected (Swap Objects).
|
||||
@@ -577,11 +592,110 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect();
|
||||
let keyed: Vec<(Option<NodeId>, Rect)> = items.iter().map(|(_, k)| *k).collect();
|
||||
let sets: Vec<Vec<NodeId>> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
|
||||
group_each(s, "Group Overlapping Objects", &roots, sets)
|
||||
}
|
||||
|
||||
/// The rows of `items` (each a key and an extent `(start, end)` along the axis across the rows): the sets of
|
||||
/// two or more (each in the order given) among items of the same key whose extents overlap, chains included.
|
||||
/// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it
|
||||
/// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at
|
||||
/// another's start stays apart from it whatever their order. Adding 0.0 turns -0.0 into 0.0, which
|
||||
/// `total_cmp` would otherwise order first.
|
||||
fn rows_of<K: Eq + std::hash::Hash + Copy>(items: &[(K, (f64, f64))]) -> Vec<Vec<usize>> {
|
||||
let items: Vec<(K, (f64, f64))> = items.iter().map(|(k, (start, end))| (*k, (start + 0.0, end + 0.0))).collect();
|
||||
let mut order: Vec<usize> = (0..items.len()).collect();
|
||||
order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1)));
|
||||
let mut rows: Vec<Vec<usize>> = vec![];
|
||||
// Each key's open row: its index in `rows` and where it ends.
|
||||
let mut open: HashMap<K, (usize, f64)> = HashMap::new();
|
||||
for i in order {
|
||||
let (key, (start, end)) = items[i];
|
||||
match open.get_mut(&key) {
|
||||
Some((row, until)) if start < *until => {
|
||||
if let Some(r) = rows.get_mut(*row) {
|
||||
r.push(i);
|
||||
}
|
||||
*until = until.max(end);
|
||||
}
|
||||
_ => {
|
||||
open.insert(key, (rows.len(), end));
|
||||
rows.push(vec![i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
rows.retain(|r| r.len() > 1);
|
||||
for r in &mut rows {
|
||||
r.sort_unstable();
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn group_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.groupRows";
|
||||
if !p.is_object() {
|
||||
return Err(bad(C, "parameters must be an object"));
|
||||
}
|
||||
if p.get("direction").is_some_and(Value::is_null) {
|
||||
return Err(bad(C, "`direction` must be row or column"));
|
||||
}
|
||||
let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let editable_roots: Vec<_> = {
|
||||
let editable = d.editable();
|
||||
roots.iter().copied().filter(|id| editable(*id) && d.node(*id).is_some_and(|n| !n.is_layer())).collect()
|
||||
};
|
||||
for id in &editable_roots {
|
||||
let parent = d.parent_of(*id);
|
||||
let valid_parent = parent.and_then(|parent| d.node(parent)).is_some_and(|n| {
|
||||
matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })
|
||||
&& !n.is_compound_shape()
|
||||
&& n.extras().shaper.is_none()
|
||||
&& n.extras().objects_on_path.is_none()
|
||||
&& !vectorcraft_tools::builder::is_live_paint(n)
|
||||
});
|
||||
let in_graph = parent
|
||||
.and_then(|parent| d.ancestry(parent))
|
||||
.is_some_and(|ancestors| ancestors.iter().any(|ancestor| d.node(*ancestor).is_some_and(|n| n.extras().graph.is_some())));
|
||||
if !valid_parent || in_graph {
|
||||
return Err(bad(C, "selected objects must be in a layer or group without live structural roles"));
|
||||
}
|
||||
}
|
||||
// Each object's row key (its parent and its artboard) and its extent across the rows.
|
||||
type Keyed = ((NodeId, usize), (f64, f64));
|
||||
let symbols = d.symbol_boxes();
|
||||
let items: Vec<(NodeId, Keyed)> = editable_roots
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let parent = d.parent_of(*id)?;
|
||||
let container = d.node(parent)?;
|
||||
if container.clips() && container.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id) {
|
||||
return None;
|
||||
}
|
||||
let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?;
|
||||
let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) };
|
||||
Some((*id, ((parent, d.artboard_for_bounds(b)?), extent)))
|
||||
})
|
||||
.collect();
|
||||
let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect();
|
||||
let sets: Vec<Vec<NodeId>> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect();
|
||||
let mut selection = roots;
|
||||
selection.extend(s.doc()?.selection.objects.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.is_layer())));
|
||||
group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &selection, sets)
|
||||
}
|
||||
|
||||
/// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a
|
||||
/// new group of its own at its frontmost member's place, as undo step `label`, and select the new groups and
|
||||
/// the objects of `roots` left alone. No step when `sets` is empty.
|
||||
fn group_each(s: &mut Session, label: &str, roots: &[NodeId], sets: Vec<Vec<NodeId>>) -> Result<Value> {
|
||||
if sets.is_empty() {
|
||||
return Ok(json!({ "groups": [], "grouped": 0 }));
|
||||
}
|
||||
let grouped: std::collections::HashSet<NodeId> = sets.iter().flatten().copied().collect();
|
||||
let groups = s.edit("Group Overlapping Objects", |d, sel| {
|
||||
let groups = s.edit(label, |d, sel| {
|
||||
// Every group at once: the members behind each front one go, then each front one is
|
||||
// replaced by its group (one pass over the tree each, however many groups).
|
||||
let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]);
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds
|
||||
//! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than
|
||||
//! around the whole selection, stroked in a color of their own and stacked directly above the
|
||||
//! object, as one undo step.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
use vectorcraft_render::drawn_bounds_with;
|
||||
|
||||
use super::super::super::edit::selected_roots;
|
||||
use super::super::super::object::choice;
|
||||
use super::super::super::paint::new_color;
|
||||
use super::super::super::{CommandSpec, bad, cmd, color_param, has_selection};
|
||||
use super::{LEAST, LIMIT, MAX_OBJECTS, number_in};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.arrange.markBounds";
|
||||
/// The heaviest stroke (pt) the marks take, and the lightest.
|
||||
const MAX_WEIGHT: f64 = 1000.0;
|
||||
const MIN_WEIGHT: f64 = 0.01;
|
||||
/// A side shorter than this (pt) is no side: its marks are drawn as lines along the other one.
|
||||
const FLAT: f64 = 1e-9;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.arrange.markBounds",
|
||||
"Mark Bounds of Each",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
|
||||
has_selection,
|
||||
mark_bounds
|
||||
)]
|
||||
}
|
||||
|
||||
/// The four corners of `r`, each with the directions its legs run in (inward), the corners that
|
||||
/// fall on an earlier one left out.
|
||||
fn corners(r: Rect) -> Vec<(Point, f64, f64)> {
|
||||
let mut out: Vec<(Point, f64, f64)> = vec![];
|
||||
for (x, y, sx, sy) in [(r.x0, r.y0, 1.0, 1.0), (r.x1, r.y0, -1.0, 1.0), (r.x1, r.y1, -1.0, -1.0), (r.x0, r.y1, 1.0, -1.0)] {
|
||||
let at = Point::new(x, y);
|
||||
if out.iter().all(|(p, _, _)| (p.x - at.x).abs() > FLAT || (p.y - at.y).abs() > FLAT) {
|
||||
out.push((at, sx, sy));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per
|
||||
/// corner, a line where `r` has no width or no height.
|
||||
fn corner_paths(r: Rect, length: f64) -> Vec<PathData> {
|
||||
let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0));
|
||||
corners(r)
|
||||
.into_iter()
|
||||
.filter_map(|(p, sx, sy)| {
|
||||
let across = Point::new(p.x + sx * lx, p.y);
|
||||
let down = Point::new(p.x, p.y + sy * ly);
|
||||
let points = match (lx > FLAT, ly > FLAT) {
|
||||
(true, true) => vec![across, p, down],
|
||||
(true, false) => vec![across, p],
|
||||
(false, true) => vec![p, down],
|
||||
(false, false) => return None,
|
||||
};
|
||||
Some(PathData::single(SubPath::polyline(&points, false)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the marks of object `id` go: directly above it, or above the outermost clip group or
|
||||
/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer
|
||||
/// with a clipping mask holds its marks too, since nothing lies outside it.
|
||||
fn anchor(d: &Document, id: NodeId) -> NodeId {
|
||||
let (mut at, mut outermost) = (id, id);
|
||||
while let Some(up) = d.parent_of(at) {
|
||||
if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() {
|
||||
outermost = up;
|
||||
}
|
||||
at = up;
|
||||
}
|
||||
outermost
|
||||
}
|
||||
|
||||
fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle");
|
||||
let visual = choice(p, C, "bounds", &["geometric", "visual"])? == Some("visual");
|
||||
let length = number_in(p, "length", 10.0, (LEAST, LIMIT), C)?;
|
||||
let weight = number_in(p, "weight", 1.0, (MIN_WEIGHT, MAX_WEIGHT), C)?;
|
||||
let color = new_color(s, p, color_param(p, "color", C)?.unwrap_or(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len());
|
||||
for id in roots {
|
||||
let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue };
|
||||
let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) };
|
||||
if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) {
|
||||
marked.push((anchor(d, id), r));
|
||||
}
|
||||
}
|
||||
if marked.is_empty() {
|
||||
return Err(bad(C, "nothing to mark: the selection has no bounds"));
|
||||
}
|
||||
let ap = Appearance::basic(Paint::None, Paint::solid(color), weight);
|
||||
let ids = s.edit("Mark Bounds of Each", |d, sel| {
|
||||
// Each anchor once, its objects' marks in stacking order from the back.
|
||||
let mut lists: Vec<(NodeId, Vec<Node>)> = vec![];
|
||||
let mut at: HashMap<NodeId, usize> = HashMap::new();
|
||||
let mut out = Vec::with_capacity(marked.len());
|
||||
for (anchor, r) in &marked {
|
||||
let node = if rectangle {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), ap.clone());
|
||||
n.name = Some("Bounds".into());
|
||||
n
|
||||
} else {
|
||||
let children = corner_paths(*r, length).into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, ap.clone()))).collect();
|
||||
let mut g = Node::group(d.alloc_id(), children);
|
||||
g.name = Some("Corner Marks".into());
|
||||
g
|
||||
};
|
||||
out.push(node.id);
|
||||
let k = *at.entry(*anchor).or_insert_with(|| {
|
||||
lists.push((*anchor, vec![]));
|
||||
lists.len() - 1
|
||||
});
|
||||
if let Some((_, nodes)) = lists.get_mut(k) {
|
||||
nodes.push(node);
|
||||
}
|
||||
}
|
||||
d.insert_beside(lists, false)?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "count": ids.len() }))
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
//! Mark Bounds of Each: the marks each object gets, where they go in the stacking order, how
|
||||
//! groups, clip groups, strokes and guides are measured, one undo step, and bad params refused.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Node, NodeId};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::COMMAND;
|
||||
use crate::Session;
|
||||
|
||||
/// A new document whose new art has no stroke, so visual and geometric bounds agree.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// The ids of the children of `parent`, in stacking order from the back.
|
||||
fn children(s: &Session, parent: NodeId) -> Vec<NodeId> {
|
||||
node(s, parent).children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
fn parent(s: &Session, id: NodeId) -> NodeId {
|
||||
s.doc().unwrap().doc.parent_of(id).unwrap()
|
||||
}
|
||||
|
||||
/// Each path of the mark `id` (a group's members, or the path itself) as its points.
|
||||
fn lines(s: &Session, id: NodeId) -> Vec<Vec<(f64, f64)>> {
|
||||
let n = node(s, id);
|
||||
let paths: Vec<Node> = match n.children() {
|
||||
Some(c) => c.iter().map(|c| (**c).clone()).collect(),
|
||||
None => vec![n],
|
||||
};
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let path = p.path_data().unwrap();
|
||||
path.subpaths[0].anchors.iter().map(|a| ((a.p.x * 1e6).round() / 1e6, (a.p.y * 1e6).round() / 1e6)).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool {
|
||||
[(a.x0, b.0), (a.y0, b.1), (a.x1, b.2), (a.y1, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6)
|
||||
}
|
||||
|
||||
fn marks_bounds(s: &Session, id: NodeId) -> Rect {
|
||||
node(s, id).geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_gets_inward_corner_marks_above_it_in_one_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0);
|
||||
let b = rect(&mut s, 200.0, 100.0, 40.0, 40.0);
|
||||
let layer = parent(&s, a);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let marks = ids_of(&r);
|
||||
assert_eq!((marks.len(), r["count"].as_u64()), (2, Some(2)));
|
||||
// Directly above each object, not around the selection.
|
||||
assert_eq!(children(&s, layer), vec![a, marks[0], b, marks[1]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks, "the marks are selected");
|
||||
assert_eq!(node(&s, marks[0]).name.as_deref(), Some("Corner Marks"));
|
||||
assert_eq!(
|
||||
lines(&s, marks[0]),
|
||||
vec![
|
||||
vec![(10.0, 0.0), (0.0, 0.0), (0.0, 10.0)],
|
||||
vec![(90.0, 0.0), (100.0, 0.0), (100.0, 10.0)],
|
||||
vec![(90.0, 50.0), (100.0, 50.0), (100.0, 40.0)],
|
||||
vec![(10.0, 50.0), (0.0, 50.0), (0.0, 40.0)],
|
||||
]
|
||||
);
|
||||
assert!(near(marks_bounds(&s, marks[1]), (200.0, 100.0, 240.0, 140.0)));
|
||||
// A red 1 pt stroke and no fill.
|
||||
let group = node(&s, marks[1]);
|
||||
let ap = &group.children().unwrap()[0].appearance;
|
||||
assert_eq!((ap.fill_paint(), ap.stroke_paint(), ap.stroke_width()), (Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(children(&s, layer), vec![a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_weight_color_and_the_rectangle_style() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 100.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap();
|
||||
let marks = ids_of(&r);
|
||||
// A leg is never longer than half its side, so opposite marks do not overlap.
|
||||
assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]);
|
||||
let group = node(&s, marks[0]);
|
||||
let ap = &group.children().unwrap()[0].appearance;
|
||||
assert_eq!((ap.stroke_paint(), ap.stroke_width()), (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.5));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
let rect = node(&s, mark);
|
||||
assert!(rect.children().is_none() && rect.path_data().unwrap().subpaths[0].closed, "one closed path");
|
||||
assert_eq!(rect.name.as_deref(), Some("Bounds"));
|
||||
assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leg_is_at_most_half_the_side_it_runs_along_vertically() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 200.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute(COMMAND, &json!({"length": 30})).unwrap();
|
||||
assert_eq!(
|
||||
lines(&s, ids_of(&r)[0]),
|
||||
vec![
|
||||
vec![(30.0, 0.0), (0.0, 0.0), (0.0, 10.0)],
|
||||
vec![(170.0, 0.0), (200.0, 0.0), (200.0, 10.0)],
|
||||
vec![(170.0, 20.0), (200.0, 20.0), (200.0, 10.0)],
|
||||
vec![(30.0, 20.0), (0.0, 20.0), (0.0, 10.0)],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (0.0, 0.0, 20.0, 20.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (-2.0, -2.0, 22.0, 22.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 50.0, 50.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let geometry = marks_bounds(&s, a);
|
||||
let (dx, dy) = (12.0, 8.0);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null, "params": {"x": dx, "y": dy, "blur": 0}})).unwrap();
|
||||
let shadow = Rect::new(geometry.x0 + dx, geometry.y0 + dy, geometry.x1 + dx, geometry.y1 + dy);
|
||||
let reach = geometry.union(shadow);
|
||||
let encloses = |r: Rect| r.x0 <= reach.x0 && r.y0 <= reach.y0 && r.x1 >= reach.x1 && r.y1 >= reach.y1;
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap();
|
||||
let geometric = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1)));
|
||||
assert!(!encloses(geometric), "the geometric mark leaves the shadow outside");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
let visual = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(encloses(visual), "the visual mark encloses the artwork and its shadow: {visual:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_bounds_enclose_brush_art_on_paths_and_in_groups() {
|
||||
for grouped in [false, true] {
|
||||
let mut s = session();
|
||||
let path = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 50, "x2": 150, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[path]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 1})).unwrap();
|
||||
s.execute("brush.apply", &json!({"name": "Dots"})).unwrap();
|
||||
let target = if grouped {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
parent(&s, path)
|
||||
} else {
|
||||
path
|
||||
};
|
||||
select(&mut s, &[target]);
|
||||
let geometry = marks_bounds(&s, path);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let source = d.node(target).unwrap();
|
||||
let painted = vectorcraft_render::painted_bounds(d, source).unwrap();
|
||||
let drawn = vectorcraft_render::drawn_bounds(d, source).unwrap();
|
||||
let base = vectorcraft_render::effect_bounds(&d.symbol_boxes(), source).unwrap();
|
||||
assert!(drawn.y0 < base.y0 && drawn.y1 > base.y1, "brush art reaches past the base stroke: {drawn:?}, {base:?}");
|
||||
let encloses = |r: Rect| r.x0 <= drawn.x0 && r.y0 <= drawn.y0 && r.x1 >= drawn.x1 && r.y1 >= drawn.y1;
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap();
|
||||
let geometric = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1)));
|
||||
assert!(!encloses(geometric), "the geometric mark leaves brush art outside");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap();
|
||||
let visual = marks_bounds(&s, ids_of(&r)[0]);
|
||||
assert!(near(visual, (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "the visual mark follows the drawn bounds: {visual:?}, {drawn:?}");
|
||||
assert!(encloses(visual), "the visual mark encloses the brush art: {visual:?}, {drawn:?}");
|
||||
assert!(
|
||||
visual.x0 > painted.x0 && visual.y0 > painted.y0 && visual.x1 < painted.x1 && visual.y1 < painted.y1,
|
||||
"the visual mark stays inside the culling margin: {visual:?}, {painted:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_by_their_members_and_clip_groups_by_the_clipping_path() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 50.0, 30.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let group = parent(&s, a);
|
||||
let art = rect(&mut s, 100.0, 100.0, 200.0, 150.0);
|
||||
let clip = rect(&mut s, 150.0, 120.0, 50.0, 40.0);
|
||||
select(&mut s, &[art, clip]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let clip_group = parent(&s, art);
|
||||
let layer = parent(&s, group);
|
||||
select(&mut s, &[group, clip_group]);
|
||||
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
|
||||
let marks = ids_of(&r);
|
||||
assert!(near(marks_bounds(&s, marks[0]), (0.0, 0.0, 60.0, 40.0)), "the members together");
|
||||
assert!(near(marks_bounds(&s, marks[1]), (150.0, 120.0, 200.0, 160.0)), "the clipping path");
|
||||
assert_eq!(children(&s, layer), vec![group, marks[0], clip_group, marks[1]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// An object inside the clip group: its marks go above the clip group, where it does not hide them.
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
assert_eq!(children(&s, layer), vec![group, clip_group, mark]);
|
||||
assert!(near(marks_bounds(&s, mark), (100.0, 100.0, 300.0, 250.0)), "the object's own bounds");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// And when a plain group lies between the object and the clip group.
|
||||
select(&mut s, &[art]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let inner = parent(&s, art);
|
||||
let clip_group = parent(&s, clip);
|
||||
assert_eq!(parent(&s, inner), clip_group);
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(children(&s, layer), vec![group, clip_group, ids_of(&r)[0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() {
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(children(&s, top), vec![sub, ids_of(&r)[0]], "above the clipping sublayer");
|
||||
|
||||
// A clipping top-level layer has nothing outside it to hold them: they go above the object.
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": top.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
select(&mut s, &[art]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
let mark = ids_of(&r)[0];
|
||||
let stack = children(&s, top);
|
||||
assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_objects_get_lines_and_guides_and_empty_groups_none() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 100, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[line]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
// No height: one mark at each end, along the line.
|
||||
assert_eq!(lines(&s, ids_of(&r)[0]), vec![vec![(10.0, 50.0), (0.0, 50.0)], vec![(90.0, 50.0), (100.0, 50.0)]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
let guide = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[guide]);
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
select(&mut s, &[guide]);
|
||||
let layer = s.doc().unwrap().target_parent().unwrap();
|
||||
let empty = s
|
||||
.edit("test", |d, _| {
|
||||
let g = Node::group(d.alloc_id(), vec![]);
|
||||
let id = g.id;
|
||||
d.insert(layer, usize::MAX, g)?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[guide, empty]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
|
||||
assert!(refused.contains("nothing to mark"), "{refused}");
|
||||
assert_eq!(steps(&s), n, "no undo step");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
// With a real object as well, only it gets marks.
|
||||
let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
|
||||
select(&mut s, &[guide, empty, a]);
|
||||
let r = s.execute(COMMAND, &json!({})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_it_is_off_without_a_selection() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for p in [
|
||||
json!({"style": "cross"}),
|
||||
json!({"bounds": "preview"}),
|
||||
json!({"length": 0}),
|
||||
json!({"length": 1e7}),
|
||||
json!({"length": "10"}),
|
||||
json!({"weight": 0}),
|
||||
json!({"weight": 1001}),
|
||||
json!({"color": "not a color"}),
|
||||
json!({"color": "#ff000080"}),
|
||||
json!({"color": 3}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled);
|
||||
assert!(s.execute(COMMAND, &json!({})).is_err());
|
||||
}
|
||||
@@ -779,6 +779,7 @@ fn off_without_a_selection() {
|
||||
"addon.arrange.size",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.groupRows",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
] {
|
||||
@@ -862,6 +863,503 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() {
|
||||
assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1));
|
||||
}
|
||||
|
||||
fn layer_children(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_groups_each_row_and_leaves_loners() {
|
||||
let mut s = session();
|
||||
// Row one: a and b (y 0 to 12). c only touches it (from y 12), alone in its row. Row two: d and e.
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let d = rect(&mut s, 0.0, 40.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 20.0, 2.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, 40.0, 12.0, 10.0, 10.0);
|
||||
let e = rect(&mut s, 20.0, 45.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b, c, d, e]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(r["grouped"], json!(4));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 2);
|
||||
assert_eq!(children(&s, groups[0]), [a, b], "the top row first, its members in stacking order");
|
||||
assert_eq!(children(&s, groups[1]), [d, e]);
|
||||
// Each group where its frontmost member was: a d b c e → group(ab) at b, c, group(de) at e.
|
||||
assert_eq!(layer_children(&s), [groups[0], c, groups[1]]);
|
||||
let sel = &s.doc().unwrap().selection.objects;
|
||||
assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&c) && sel.len() == 3, "{sel:?}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Row"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_children(&s), [a, d, b, c, e]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_makes_columns_and_joins_rows_an_object_spans() {
|
||||
let mut s = session();
|
||||
// Columns: a and b share x 0 to 15, c stands apart.
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 5.0, 50.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, 30.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "column"})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Column"));
|
||||
// By row, p and q lie in two rows until r, reaching from one to the other, joins them.
|
||||
let mut s = session();
|
||||
let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let q = rect(&mut s, 50.0, 20.0, 10.0, 10.0);
|
||||
select(&mut s, &[p, q]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "two rows of one: no groups, no step");
|
||||
let bridge = rect(&mut s, 100.0, 5.0, 10.0, 20.0);
|
||||
select(&mut s, &[p, q, bridge]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [p, q, bridge]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_layers_and_artboards_apart_and_measures_visual_bounds() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 200, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
// Touching a's bottom edge: a row of its own until strokes reach over the edge.
|
||||
let below = rect(&mut s, 50.0, 20.0, 20.0, 20.0);
|
||||
let far = rect(&mut s, 550.0, 0.0, 20.0, 20.0);
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let other = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, below, far, other]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "another artboard, another layer, a touching edge: no groups");
|
||||
select(&mut s, &[a, below]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
select(&mut s, &[a, below, far, other]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, below], "the strokes overlap");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_ne!(doc.parent_of(far), Some(groups[0]), "left on its own artboard");
|
||||
assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_measures_clipping_groups_by_their_mask() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
// A 200 tall object clipped to a 30 tall mask at y 100.
|
||||
let clipped = rect(&mut s, 50.0, 0.0, 10.0, 200.0);
|
||||
let mask = rect(&mut s, 40.0, 100.0, 30.0, 30.0);
|
||||
select(&mut s, &[clipped, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().selection.objects[0];
|
||||
let b = rect(&mut s, 100.0, 110.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, group, b]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() {
|
||||
for clipping_layer in [false, true] {
|
||||
let mut s = session();
|
||||
let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
select(&mut s, &[mask, a, b]);
|
||||
let parent = if clipping_layer {
|
||||
s.doc().unwrap().doc.layers[0].id
|
||||
} else {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.doc().unwrap().selection.objects[0]
|
||||
};
|
||||
s.edit("Set clipping", |d, _| {
|
||||
d.node_mut(parent).unwrap().set_clips(true);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[mask, a]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(children(&s, parent), [mask, a, b]);
|
||||
select(&mut s, &[mask, a, b]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, parent), [mask, groups[0]]);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
assert!(s.doc().unwrap().selection.objects.contains(&mask));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_leaves_selected_layers_and_sublayers_in_place() {
|
||||
for sublayers in [false, true] {
|
||||
let mut s = session();
|
||||
let parent = s.doc().unwrap().doc.layers[0].id;
|
||||
let mut layers = vec![];
|
||||
for _ in 0..2 {
|
||||
let command = if sublayers { "layer.newSublayer" } else { "layer.new" };
|
||||
let params = if sublayers { json!({"parent": parent.0}) } else { json!({"top": true}) };
|
||||
let layer = NodeId(s.execute(command, ¶ms).unwrap()["id"].as_u64().unwrap());
|
||||
rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
layers.push(layer);
|
||||
}
|
||||
s.execute("layer.setCurrent", &json!({"id": parent.0})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &layers);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(0), "layers must not become ordinary group members");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
select(&mut s, &[layers[0], layers[1], a, b]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(children(&s, groups[0]), [a, b]);
|
||||
for layer in &layers {
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(*layer), sublayers.then_some(parent));
|
||||
assert!(s.doc().unwrap().selection.objects.contains(layer));
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_objects_without_a_parent() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0);
|
||||
s.edit("Set root objects", |d, _| {
|
||||
for id in [a, b] {
|
||||
let node = d.remove(id)?;
|
||||
d.layers.push(node);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "row"}), json!({"direction": "column"})]);
|
||||
}
|
||||
|
||||
fn refuse_row_parts_and_group_whole(s: &mut Session, group: NodeId, parts: &[Vec<NodeId>]) {
|
||||
let center = bounds(s, group).center();
|
||||
let a = rect(s, center.x - 10.0, center.y - 10.0, 20.0, 20.0);
|
||||
let b = rect(s, center.x - 5.0, center.y - 5.0, 20.0, 20.0);
|
||||
let members = children(s, group);
|
||||
for direction in ["row", "column"] {
|
||||
for selected in parts {
|
||||
select(s, selected);
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(s.doc().unwrap().selection, selection);
|
||||
let mut mixed = selected.clone();
|
||||
mixed.extend([a, b]);
|
||||
select(s, &mixed);
|
||||
refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(s, group), members);
|
||||
}
|
||||
select(s, &[group, a, b]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!(r["grouped"], json!(3));
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(children(s, groups[0]), [group, a, b]);
|
||||
assert_eq!(children(s, group), members);
|
||||
assert_eq!(steps(s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_objects_on_path_children_but_groups_the_whole_group() {
|
||||
let mut s = session();
|
||||
let path = rect(&mut s, 20.0, 20.0, 100.0, 100.0);
|
||||
let member = rect(&mut s, 30.0, 30.0, 20.0, 20.0);
|
||||
let group = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0, "ids": [member.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
refuse_row_parts_and_group_whole(&mut s, group, &[vec![path, member]]);
|
||||
assert!(s.doc().unwrap().doc.node(group).unwrap().extras().objects_on_path.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_live_paint_faces_and_edges_but_groups_the_whole_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let group = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(group).unwrap();
|
||||
let faces: Vec<_> = vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect();
|
||||
let edges: Vec<_> = vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect();
|
||||
assert!(faces.len() >= 2);
|
||||
assert!(edges.len() >= 2);
|
||||
refuse_row_parts_and_group_whole(&mut s, group, &[faces.clone(), edges.clone()]);
|
||||
let node = s.doc().unwrap().doc.node(group).unwrap();
|
||||
assert_eq!(vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect::<Vec<_>>(), faces);
|
||||
assert_eq!(vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect::<Vec<_>>(), edges);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_live_graph_descendants_but_groups_the_whole_graph() {
|
||||
let mut s = session();
|
||||
let params = json!({"type": "column", "x": 20, "y": 20, "width": 200, "height": 200, "csv": ",Series\nA,3\nB,5"});
|
||||
let graph = NodeId(s.execute("graph.create", ¶ms).unwrap()["id"].as_u64().unwrap());
|
||||
let node = s.doc().unwrap().doc.node(graph).unwrap();
|
||||
let series = node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let marks: Vec<_> = series.children().unwrap().iter().take(2).map(|n| n.id).collect();
|
||||
assert_eq!(marks.len(), 2);
|
||||
let direct = children(&s, graph);
|
||||
refuse_row_parts_and_group_whole(&mut s, graph, &[marks, direct]);
|
||||
assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_live_blend_keys() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.blend.make", &json!({})).unwrap();
|
||||
let blend = s.doc().unwrap().selection.objects[0];
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 90.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({})]);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({})]);
|
||||
assert_eq!(children(&s, blend), [a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_shaper_children() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": [[25, 25], [125, 25]]})).unwrap()["id"].as_u64().unwrap());
|
||||
let members = children(&s, shaper);
|
||||
assert!(members.len() >= 2);
|
||||
let sources = members[0];
|
||||
let face = s
|
||||
.doc()
|
||||
.unwrap()
|
||||
.doc
|
||||
.node(shaper)
|
||||
.unwrap()
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|n| n.name.as_deref().is_some_and(|name| name.starts_with(vectorcraft_doc::shaper::FILL_PREFIX)))
|
||||
.unwrap()
|
||||
.id;
|
||||
let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &[sources, face]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
select(&mut s, &[sources, face, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(&s, shaper), members);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_explicitly_selected_live_compound_shape_operands() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let b = rect(&mut s, 10.0, 0.0, 30.0, 30.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap();
|
||||
let shape = s.doc().unwrap().selection.objects[0];
|
||||
let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0);
|
||||
for direction in ["row", "column"] {
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]);
|
||||
assert_eq!(children(&s, shape), [a, b]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() {
|
||||
for command in ["object.lock", "object.hide"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute(command, &json!({})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
assert!(s.doc().unwrap().selection.objects.contains(&b));
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, groups[0]), [a, c]);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_leaves_objects_outside_all_artboards_ungrouped() {
|
||||
for direction in ["row", "column"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 500.0, 500.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 505.0, 505.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
let c = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let d = rect(&mut s, 5.0, 5.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b, c, d]);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(r["grouped"], json!(2));
|
||||
assert_eq!(children(&s, groups[0]), [c, d]);
|
||||
assert_eq!(layer_children(&s), [a, b, groups[0]]);
|
||||
let sel = &s.doc().unwrap().selection.objects;
|
||||
assert!(sel.contains(&a) && sel.contains(&b));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_documents_and_excludes_raster_effects_from_bounds() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 0, "y": 5, "blur": 0}})).unwrap();
|
||||
let b = rect(&mut s, 0.0, 21.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(layer_children(&s), [a, b]);
|
||||
let spec = super::specs().into_iter().find(|c| c.id == "addon.arrange.groupRows").unwrap();
|
||||
assert!(spec.params.contains("excludes raster effects"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.groupRows"));
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
assert!(enabled(&s, "addon.arrange.groupRows"));
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.groupRows",
|
||||
&[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true}), json!({"direction": null})],
|
||||
);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let groups = ids_of(&r["groups"]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(children(&s, groups[0]), [a, c], "the locked object stays out");
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_refuses_non_object_params_without_an_edit() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let selection = s.doc().unwrap().selection.objects.clone();
|
||||
refuses(&mut s, "addon.arrange.groupRows", &[json!([]), json!(["row"]), json!("row"), json!(true), json!(3)]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_reads_the_symbol_index_once_for_all_members() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeKind, Symbol};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
let mut d = Document::new(400.0, 300.0);
|
||||
for i in 0..200 {
|
||||
let art = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
d.symbols.push(Symbol { dynamic: false, name: format!("Mark {i}"), art: Arc::new(art) });
|
||||
}
|
||||
let layer = d.layers[0].id;
|
||||
let ids: Vec<_> = (0..8)
|
||||
.map(|i| {
|
||||
let xf = Affine::translate((0.0, f64::from(i) * 20.0));
|
||||
let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Mark {i}"), xf });
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap()
|
||||
})
|
||||
.collect();
|
||||
let symbol_count = d.symbols.len();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
select(&mut s, &ids);
|
||||
let n = steps(&s);
|
||||
let before = vectorcraft_doc::symbols_read();
|
||||
let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap();
|
||||
let read = vectorcraft_doc::symbols_read() - before;
|
||||
assert!(read <= symbol_count, "{read} symbols read, {symbol_count} in the document");
|
||||
assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n));
|
||||
assert_eq!(layer_children(&s), ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_sorts_many_objects_into_rows() {
|
||||
// 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps,
|
||||
// neighboring pairs only touch.
|
||||
let items: Vec<(u8, (f64, f64))> = (0..20_000)
|
||||
.map(|i| {
|
||||
let top = (10_000 - i / 2) as f64 * 10.0;
|
||||
(0, (if i % 2 == 0 { top + 1.0 } else { top }, top + 10.0))
|
||||
})
|
||||
.collect();
|
||||
let rows = super::rows_of(&items);
|
||||
assert_eq!(rows.len(), 10_000);
|
||||
assert!(rows.iter().all(|r| r.len() == 2 && r[1] == r[0] + 1), "pairs, in the order given");
|
||||
assert_eq!(rows.first(), Some(&vec![19_998, 19_999]), "the top row first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() {
|
||||
// An extent with no height at the top edge of another only touches it, whichever is in front.
|
||||
let flat_behind: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (0.0, 10.0))];
|
||||
let flat_in_front: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 10.0)), (0, (0.0, 0.0))];
|
||||
assert!(super::rows_of(&flat_behind).is_empty());
|
||||
assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front));
|
||||
// Inside the row, it joins.
|
||||
assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]);
|
||||
// A start of -0.0 is the same edge as 0.0, so the flat extent there still only touches.
|
||||
let negative_zero: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (-0.0, 10.0))];
|
||||
assert!(super::rows_of(&negative_zero).is_empty(), "{:?}", super::rows_of(&negative_zero));
|
||||
}
|
||||
|
||||
fn opacity(s: &Session, id: NodeId) -> f32 {
|
||||
s.doc().unwrap().doc.node(id).unwrap().opacity
|
||||
}
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu,
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors
|
||||
//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu,
|
||||
//! Object › Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
mod print_fixes;
|
||||
mod random_fill;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -92,6 +94,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
|s, p| copy_paint(s, p, false)
|
||||
),
|
||||
cmd!(
|
||||
"addon.color.randomFill",
|
||||
"Randomize Fill Colors",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}",
|
||||
has_selection,
|
||||
random_fill::run
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Randomize Fill Colors (`addon.color.randomFill`, Object › Plug-ins › Color Effects › Randomize
|
||||
//! Fill Colors…): each selected filled path, compound path and live compound shape, and each one inside the selected
|
||||
//! groups, gets a fill color of its own, picked at random from a seed: any color, a tint of one
|
||||
//! global or spot swatch, or a gray, as one undo step.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint};
|
||||
#[cfg(test)]
|
||||
use super::super::super::graph::is_design_art;
|
||||
use super::super::super::graph::{is_series_group, paint_targets};
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::paint::swatch_solid;
|
||||
use super::super::super::{bad, checked_ids_or_selection, number_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const C: &str = "addon.color.randomFill";
|
||||
/// The schemes the colors are picked from (`scheme`).
|
||||
pub const SCHEMES: [&str; 3] = ["color", "tint", "gray"];
|
||||
|
||||
/// How each color is picked.
|
||||
enum Scheme {
|
||||
/// Any color: red, green and blue each at random, in the document's color mode.
|
||||
Color,
|
||||
/// A tint of the swatch, from the least to the most (0..1).
|
||||
Tint(String, f32, f32),
|
||||
/// A gray, from the least black to the most (0..1).
|
||||
Gray(f32, f32),
|
||||
}
|
||||
|
||||
/// The percentage `p` gives for `key` (`default` when left out).
|
||||
fn percent(p: &Value, key: &str, default: f64) -> Result<f64> {
|
||||
let v = number_or(p, key, default, C)?;
|
||||
if (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) }
|
||||
}
|
||||
|
||||
/// The scheme `p` asks for, checked against the document's swatches.
|
||||
fn scheme(s: &Session, p: &Value) -> Result<Scheme> {
|
||||
let name = text_param(p, "scheme", C)?.unwrap_or("color");
|
||||
if !SCHEMES.contains(&name) {
|
||||
return Err(bad(C, "`scheme` must be color, tint or gray"));
|
||||
}
|
||||
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
|
||||
if name == "color" && (given("min") || given("max")) {
|
||||
return Err(bad(C, "`min` and `max` go with scheme tint or gray"));
|
||||
}
|
||||
if name != "tint" && given("swatch") {
|
||||
return Err(bad(C, "`swatch` goes with scheme tint"));
|
||||
}
|
||||
if name == "color" {
|
||||
return Ok(Scheme::Color);
|
||||
}
|
||||
let (min, max) = (percent(p, "min", 0.0)?, percent(p, "max", 100.0)?);
|
||||
if min > max {
|
||||
return Err(bad(C, "`min` is greater than `max`"));
|
||||
}
|
||||
let (min, max) = ((min / 100.0) as f32, (max / 100.0) as f32);
|
||||
if name == "gray" {
|
||||
return Ok(Scheme::Gray(min, max));
|
||||
}
|
||||
let swatch = text_param(p, "swatch", C)?.ok_or_else(|| bad(C, "scheme tint needs a `swatch`: a global or spot color swatch"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
swatch_solid(d, swatch, Some(1.0)).map_err(|e| bad(C, e))?;
|
||||
if let Some((base, _)) = d.swatch_link(swatch)
|
||||
&& d.tint_paint(&base, 1.0).is_none()
|
||||
{
|
||||
return Err(bad(C, format!("`{swatch}` needs a global or spot base swatch `{base}`")));
|
||||
}
|
||||
Ok(Scheme::Tint(swatch.to_string(), min, max))
|
||||
}
|
||||
|
||||
/// Whether the object `id` is left as it is: it, or a layer or group holding it, is hidden or
|
||||
/// locked, or it is the clipping path of the group or layer holding it.
|
||||
fn left_alone(d: &Document, id: NodeId) -> bool {
|
||||
let Some(line) = d.ancestry(id) else { return true };
|
||||
let nodes: Vec<&Node> = line.iter().filter_map(|id| d.node(*id)).collect();
|
||||
if nodes.len() != line.len() || nodes.iter().any(|n| !n.visible || n.locked) {
|
||||
return true;
|
||||
}
|
||||
matches!(nodes.as_slice(), [.., parent, n] if parent.clips() && parent.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id))
|
||||
}
|
||||
|
||||
/// Add to `out` `n` when it is a filled path, compound path or live compound shape that is shown and unlocked, or the
|
||||
/// ones inside it when it is a group or a layer. A clipping path (the first object of a clipping
|
||||
/// group or clipped layer, a compound path included), a guide, type, images, symbol instances,
|
||||
/// blends and envelopes are left as they are.
|
||||
fn filled(n: &Node, out: &mut Vec<NodeId>) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
}
|
||||
if n.is_compound_shape() {
|
||||
if !n.appearance.fill_paint().is_none() {
|
||||
out.push(n.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter().skip(usize::from(n.clips())) {
|
||||
filled(c, out);
|
||||
}
|
||||
}
|
||||
NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } if !n.appearance.fill_paint().is_none() => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group replaced by the paths, compound paths and live compound shapes directly inside
|
||||
/// it. A compound path or live compound shape directly in a series group is kept, and the other ids go through
|
||||
/// [`paint_targets`], as for `paint.setFill`.
|
||||
fn series_roots(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let is_series = |id: NodeId| doc.node(id).is_some_and(|n| is_series_group(doc, n));
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape();
|
||||
let ordinary: std::collections::HashSet<NodeId> = paint_targets(doc, ids).into_iter().collect();
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = doc.node(*id) else { continue };
|
||||
if is_series(*id) {
|
||||
out.extend(n.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. }) || compound(m)).map(|m| m.id));
|
||||
} else if (compound(n) && doc.parent_of(*id).is_some_and(is_series)) || ordinary.contains(id) {
|
||||
out.push(*id);
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
out.retain(|id| seen.insert(*id));
|
||||
out
|
||||
}
|
||||
|
||||
/// The graph series groups among the ancestors of `targets`, each checked once.
|
||||
fn cached_series_groups(doc: &Document, targets: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut groups: HashSet<NodeId> = targets.iter().filter_map(|id| doc.ancestry(*id)).flatten().collect();
|
||||
groups.retain(|id| doc.node(*id).is_some_and(|n| is_series_group(doc, n)));
|
||||
groups
|
||||
}
|
||||
|
||||
/// [`is_design_art`] with the series groups looked up in `series_groups`.
|
||||
fn cached_is_design_art(doc: &Document, id: NodeId, series_groups: &HashSet<NodeId>) -> bool {
|
||||
let Some(chain) = doc.ancestry(id) else { return false };
|
||||
let Some(at) = chain.iter().position(|a| series_groups.contains(a)) else { return false };
|
||||
match chain.len() - at {
|
||||
1 => false,
|
||||
2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let scheme = scheme(s, p)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.is_empty() {
|
||||
return Ok(json!({ "count": 0 }));
|
||||
}
|
||||
let model = s.doc()?.doc.color_mode.model();
|
||||
// A run that gives every object the fill it has records no undo step.
|
||||
let count = edit_if_changed(s, "Randomize Fill Colors", |before, d| {
|
||||
// Art on a locked artboard is left as it is, as for the other commands that take `ids`.
|
||||
let locks = before.locked_artboards();
|
||||
// A nested member stands for the outermost compound path or live compound shape after each ancestor is checked.
|
||||
let mut resolved = vec![];
|
||||
for id in &ids {
|
||||
let Some(chain) = before.ancestry(*id) else { continue };
|
||||
let mut target = None;
|
||||
let mut blocked = false;
|
||||
let mut parent: Option<&Node> = None;
|
||||
let mut layer_object_checked = false;
|
||||
for ancestor in &chain {
|
||||
let Some(n) = before.node(*ancestor) else {
|
||||
blocked = true;
|
||||
break;
|
||||
};
|
||||
if !n.visible || n.locked || parent.is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == n.id)) {
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
if !layer_object_checked && (n.is_ruler_guide() || !n.is_layer()) {
|
||||
layer_object_checked = true;
|
||||
if !n.is_ruler_guide() && locks.holds(n) {
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape() {
|
||||
target.get_or_insert(*ancestor);
|
||||
}
|
||||
parent = Some(n);
|
||||
}
|
||||
if !blocked {
|
||||
resolved.push(target.unwrap_or(*id));
|
||||
}
|
||||
}
|
||||
// A graph's series group stands for its marks, as for `paint.setFill`.
|
||||
let roots = series_roots(before, &resolved);
|
||||
let mut targets = vec![];
|
||||
for id in &roots {
|
||||
let id = *id;
|
||||
if left_alone(before, id) || locks.holds_id(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(n) = before.node(id) else { continue };
|
||||
filled(n, &mut targets);
|
||||
}
|
||||
let series_groups = cached_series_groups(before, &targets);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
// A compound directly in a series group is one of the series' marks unless the graph drew it from a design;
|
||||
// the rest of the series' art below its top level is design art.
|
||||
let series_compound = |id: NodeId| {
|
||||
let Some(n) = before.node(id) else { return false };
|
||||
if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art {
|
||||
return false;
|
||||
}
|
||||
let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false };
|
||||
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
|
||||
let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref());
|
||||
graph.is_some_and(|spec| {
|
||||
let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str());
|
||||
let marker = spec.series_markers.get(index).and_then(Option::as_deref);
|
||||
![column, marker].into_iter().flatten().any(|name| {
|
||||
before
|
||||
.graph_designs
|
||||
.iter()
|
||||
.any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape()))
|
||||
})
|
||||
})
|
||||
};
|
||||
targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups)));
|
||||
let count = keeping_series_paint(d, &roots, |d| {
|
||||
let mut count = 0;
|
||||
for id in &targets {
|
||||
let paint = match &scheme {
|
||||
Scheme::Color => Paint::solid(Color::rgb(rng.range(0.0, 1.0), rng.range(0.0, 1.0), rng.range(0.0, 1.0)).in_model(model)),
|
||||
Scheme::Tint(swatch, lo, hi) => swatch_solid(d, swatch, Some(rng.range(*lo, *hi))).map_err(|e| bad(C, e))?,
|
||||
Scheme::Gray(lo, hi) => Paint::solid(Color::gray(rng.range(*lo, *hi))),
|
||||
};
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& n.appearance.fill_paint() != paint
|
||||
{
|
||||
n.appearance.set_fill(paint);
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
Ok(count)
|
||||
})?;
|
||||
Ok((count, count > 0))
|
||||
})?;
|
||||
Ok(json!({ "count": count }))
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
//! Randomize Fill Colors: the colors each scheme gives, which objects take them, one undo step, and
|
||||
//! bad params refused without a change.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = "addon.color.randomFill";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rects(s: &mut Session, n: usize) -> Vec<NodeId> {
|
||||
(0..n).map(|i| rect(s, i as f64 * 10.0)).collect()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn fill(s: &Session, id: NodeId) -> Paint {
|
||||
s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint()
|
||||
}
|
||||
|
||||
fn fills(s: &Session, ids: &[NodeId]) -> Vec<Paint> {
|
||||
ids.iter().map(|id| fill(s, *id)).collect()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn enabled(s: &Session, cmd: &str) -> bool {
|
||||
s.commands().into_iter().find(|c| c.id == cmd).unwrap().enabled
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_gets_its_own_color_from_the_seed() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 12);
|
||||
select(&mut s, &ids);
|
||||
let before = fills(&s, &ids);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"seed": 7})).unwrap();
|
||||
assert_eq!(r["count"], json!(12));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let first = fills(&s, &ids);
|
||||
assert!(first.iter().all(|p| matches!(p, Paint::Solid { color: Color::Rgb { .. }, swatch: None, .. })), "{first:?}");
|
||||
assert!(first.windows(2).all(|w| w[0] != w[1]), "each its own: {first:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fills(&s, &ids), before, "undone");
|
||||
// The same seed repeats them; another seed doesn't.
|
||||
s.execute(C, &json!({"seed": 7})).unwrap();
|
||||
assert_eq!(fills(&s, &ids), first);
|
||||
s.execute(C, &json!({"seed": 8})).unwrap();
|
||||
assert_ne!(fills(&s, &ids), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_ids_take_one_color_from_the_seed() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
let once = fill(&s, a);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0, a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
assert_eq!(fill(&s, a), once);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_document_gets_cmyk_colors() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
let ids = rects(&mut s, 3);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "color"})).unwrap();
|
||||
assert!(fills(&s, &ids).iter().all(|p| matches!(p, Paint::Solid { color: Color::Cmyk { .. }, .. })), "{:?}", fills(&s, &ids));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grays_and_tints_stay_within_the_range() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 20);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 20, "max": 40, "seed": 3})).unwrap();
|
||||
let grays: Vec<f32> = fills(&s, &ids)
|
||||
.into_iter()
|
||||
.map(|p| match p {
|
||||
Paint::Solid { color: Color::Gray { k }, swatch: None, .. } => k,
|
||||
other => panic!("not a gray: {other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert!(grays.iter().all(|k| (0.2..=0.4).contains(k)), "{grays:?}");
|
||||
assert!(grays.windows(2).any(|w| w[0] != w[1]), "{grays:?}");
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
s.execute(C, &json!({"scheme": "tint", "swatch": "Ink", "min": 10, "max": 50, "seed": 3})).unwrap();
|
||||
for p in fills(&s, &ids) {
|
||||
let Paint::Solid { swatch: Some(name), tint, .. } = p else { panic!("not linked: {p:?}") };
|
||||
assert_eq!(name, "Ink");
|
||||
assert!((0.1..=0.5).contains(&tint), "{tint}");
|
||||
}
|
||||
// min = max gives every object that gray.
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 45, "max": 45})).unwrap();
|
||||
assert!(fills(&s, &ids).iter().all(|p| *p == Paint::solid(Color::gray(0.45))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_are_entered_and_unfilled_hidden_and_locked_objects_left_alone() {
|
||||
let mut s = session();
|
||||
let [a, b, c, hidden, locked] = [0.0, 10.0, 20.0, 30.0, 40.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b, c, hidden, locked]);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [c.0], "none": true})).unwrap();
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
|
||||
select(&mut s, &[g]);
|
||||
let (before_hidden, before_locked) = (fill(&s, hidden), fill(&s, locked));
|
||||
assert!(!before_hidden.is_none() && !before_locked.is_none());
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 50, "max": 50})).unwrap();
|
||||
assert_eq!(r["count"], json!(2));
|
||||
let gray = Paint::solid(Color::gray(0.5));
|
||||
assert_eq!((fill(&s, a), fill(&s, b), fill(&s, c)), (gray.clone(), gray.clone(), Paint::None), "the unfilled one keeps None");
|
||||
assert_eq!(fill(&s, g), Paint::None, "the group gets no fill of its own");
|
||||
assert_eq!((fill(&s, hidden), fill(&s, locked)), (before_hidden, before_locked));
|
||||
// `ids` stand in for the selection; with nothing selected the menu item is off.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(!enabled(&s, C));
|
||||
let d = rect(&mut s, 50.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [d.0], "color": "#336699"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute(C, &json!({"ids": [d.0], "scheme": "gray", "min": 10, "max": 10})).unwrap();
|
||||
assert_eq!(fill(&s, d), Paint::solid(Color::gray(0.1)));
|
||||
assert_eq!(fill(&s, a), gray, "not among ids");
|
||||
// An object given by id inside a hidden or locked group keeps its fill.
|
||||
for hide in [true, false] {
|
||||
let e = rect(&mut s, 60.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [e.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[e]);
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute(if hide { "object.hide" } else { "object.lock" }, &json!({"ids": [outer.0]})).unwrap();
|
||||
let kept = fill(&s, e);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [e.0], "scheme": "gray"})).unwrap()["count"], json!(0), "hidden group: {hide}");
|
||||
assert_eq!(fill(&s, e), kept);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_takes_one_color_and_a_clipping_path_none() {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
// The topmost becomes the clipping path.
|
||||
let [art, mask] = [100.0, 102.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[art, mask]);
|
||||
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let is_clipping = |s: &Session, id: NodeId| matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. });
|
||||
assert!(is_clipping(&s, mask) && !is_clipping(&s, art));
|
||||
// A clipping path given a fill still keeps it.
|
||||
s.execute("paint.setFill", &json!({"ids": [mask.0], "color": "#00ff00"})).unwrap();
|
||||
let mask_fill = fill(&s, mask);
|
||||
assert!(!mask_fill.is_none());
|
||||
select(&mut s, &[compound, clip]);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(r["count"], json!(2), "the compound path and the clipped art");
|
||||
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, mask), mask_fill, "the clipping path keeps its fill");
|
||||
// Given by id, the clipping path keeps it too.
|
||||
assert_eq!(s.execute(C, &json!({"ids": [mask.0], "scheme": "gray"})).unwrap()["count"], json!(0));
|
||||
assert_eq!(fill(&s, mask), mask_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_member_given_by_id_colors_the_compound() {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = fill(&s, compound);
|
||||
let members = fills(&s, &[a, b]);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 7})).unwrap()["count"], json!(1));
|
||||
assert_ne!(fill(&s, compound), before);
|
||||
assert_eq!(fills(&s, &[a, b]), members);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_clipping_path_keeps_its_fill() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0);
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[art, compound]);
|
||||
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.node(clip).unwrap().children().unwrap()[0].id, compound, "the compound path clips");
|
||||
s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#00ff00"})).unwrap();
|
||||
let mask_fill = fill(&s, compound);
|
||||
assert!(!mask_fill.is_none());
|
||||
select(&mut s, &[clip]);
|
||||
assert_eq!(s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "the clipped art only");
|
||||
assert_eq!(fill(&s, art), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(fill(&s, compound), mask_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_compound_shape_takes_one_color_and_keeps_its_members_fills() {
|
||||
for target in ["shape", "group", "member"] {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert!(s.doc().unwrap().doc.node(shape).unwrap().is_compound_shape());
|
||||
let id = match target {
|
||||
"group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()),
|
||||
"member" => a,
|
||||
_ => shape,
|
||||
};
|
||||
let before = fill(&s, shape);
|
||||
let members = fills(&s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [id.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(1), "{target}");
|
||||
assert_eq!(fill(&s, shape), Paint::solid(Color::gray(0.3)), "{target}");
|
||||
assert_eq!(fills(&s, &[a, b]), members, "{target}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill(&s, shape), before);
|
||||
assert_eq!(fills(&s, &[a, b]), members);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_graph_keeps_the_fills_of_generated_design_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("graph.column", &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let mut design_paths = vec![];
|
||||
let d = &s.doc().unwrap().doc;
|
||||
d.node(graph).unwrap().walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) && super::is_design_art(d, n.id) && !n.appearance.fill_paint().is_none() {
|
||||
design_paths.push(n.id);
|
||||
}
|
||||
});
|
||||
assert!(!design_paths.is_empty());
|
||||
let before = fills(&s, &design_paths);
|
||||
select(&mut s, &[graph]);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(fills(&s, &design_paths), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_in_a_graph_series_takes_a_color() {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
|
||||
assert!(marks.len() >= 2);
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "the compound path is directly in the series group");
|
||||
for ids in [vec![compound], vec![marks[0]], vec![group]] {
|
||||
let before = fill(&s, compound);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert!(r["count"].as_u64().unwrap() >= 1, "{ids:?}");
|
||||
assert_ne!(fill(&s, compound), before, "{ids:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_in_a_graph_series_takes_a_color_after_its_design_is_deleted() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
s.execute("graph.design", &json!({"delete": "Tile"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.graph_designs.is_empty());
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let index = series.extras().series_index.unwrap() as usize;
|
||||
let spec = d.node(graph).unwrap().extras().graph.as_deref().unwrap();
|
||||
if kind == "column" {
|
||||
assert_eq!(spec.series_columns[index].as_ref().unwrap().design, "Tile");
|
||||
} else {
|
||||
assert_eq!(spec.series_markers[index].as_deref(), Some("Tile"));
|
||||
}
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}");
|
||||
let before = fill(&s, compound);
|
||||
let members = fills(&s, marks);
|
||||
select(&mut s, &[graph]);
|
||||
let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert!(result["count"].as_u64().unwrap() >= 1, "{kind}");
|
||||
assert_ne!(fill(&s, compound), before, "{kind}");
|
||||
assert_eq!(fills(&s, marks), members, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Path { .. }));
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let designed = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.edit("Set series design without replacing ordinary marks", |d, _| {
|
||||
d.node_mut(graph).unwrap().extras_mut().graph = designed;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group), "{kind}");
|
||||
assert!(!s.doc().unwrap().doc.node(compound).unwrap().extras().graph_design_art, "{kind}");
|
||||
let members = fills(&s, marks);
|
||||
for ids in [vec![compound], vec![marks[0]], vec![group], vec![graph]] {
|
||||
let before = fill(&s, compound);
|
||||
let result = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert!(result["count"].as_u64().unwrap() >= 1, "{kind}: {ids:?}");
|
||||
assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{kind}: {ids:?}");
|
||||
assert_ne!(fill(&s, compound), before, "{kind}: {ids:?}");
|
||||
assert_eq!(fills(&s, marks), members, "{kind}: {ids:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() {
|
||||
for kind in ["column", "line", "scatter"] {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none())
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
assert!(marks.len() >= 2, "{kind}");
|
||||
let marks = &marks[..2];
|
||||
select(&mut s, marks);
|
||||
let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(nested), Some(group), "{kind}");
|
||||
let before = fills(&s, marks);
|
||||
select(&mut s, &[graph]);
|
||||
// `paint.setFill` on the graph leaves a group inside a series alone, as design art; so does this command.
|
||||
s.execute("paint.setFill", &json!({"color": "#aa0000"})).unwrap();
|
||||
let after_set_fill = fills(&s, marks);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert_eq!(fills(&s, marks), before, "{kind}");
|
||||
assert_eq!(after_set_fill, before, "{kind}: paint.setFill keeps grouped marks too");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_compound_design_copies_in_a_graph_series_keep_their_fills() {
|
||||
// `legacy` clears the design flags and keeps the series' design reference; `flag_only` keeps the flags and clears the
|
||||
// reference, so each check keeps the copies' fills on its own.
|
||||
let modes = [(false, false), (true, false), (false, true)];
|
||||
for (kind, (legacy, flag_only)) in ["column", "line", "scatter"].into_iter().flat_map(|kind| modes.map(|mode| (kind, mode))) {
|
||||
let mut s = session();
|
||||
let marks = rects(&mut s, 2);
|
||||
select(&mut s, &marks);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [compound.0], "color": "#336699"})).unwrap();
|
||||
select(&mut s, &[compound]);
|
||||
s.execute("graph.design", &json!({"new": "Tile"})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(if kind == "column" { "graph.column" } else { "graph.marker" }, &json!({"id": graph.0, "design": "Tile"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap();
|
||||
let group = series.id;
|
||||
let copies: Vec<NodeId> =
|
||||
series.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Compound { .. })).map(|m| m.id).collect();
|
||||
assert!(!copies.is_empty(), "{kind}: the generated compound is directly in the series group");
|
||||
for id in &copies {
|
||||
assert!(d.node(*id).unwrap().extras().graph_design_art, "{kind}");
|
||||
assert!(super::is_design_art(d, *id), "{kind}");
|
||||
}
|
||||
let mut art = vec![];
|
||||
series.walk(&mut |n| {
|
||||
if super::is_design_art(d, n.id) {
|
||||
art.push(n.id);
|
||||
}
|
||||
});
|
||||
if legacy {
|
||||
s.edit("Clear graph design flags", |d, _| {
|
||||
for id in &art {
|
||||
d.node_mut(*id).unwrap().extras_mut().graph_design_art = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
if flag_only {
|
||||
s.edit("Clear series design reference", |d, _| {
|
||||
let mut extras = d.node_mut(graph).unwrap().extras_mut();
|
||||
let spec = extras.graph.as_deref_mut().unwrap();
|
||||
spec.series_columns.iter_mut().for_each(|c| *c = None);
|
||||
spec.series_markers.iter_mut().for_each(|m| *m = None);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
for id in &copies {
|
||||
assert!(s.doc().unwrap().doc.node(*id).unwrap().extras().graph_design_art, "{kind}");
|
||||
}
|
||||
}
|
||||
let before = fills(&s, &art);
|
||||
let runs = if flag_only { vec![copies.clone()] } else { vec![vec![graph], vec![group], copies] };
|
||||
for ids in runs {
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert_eq!(fills(&s, &art), before, "{kind}, legacy: {legacy}, flag only: {flag_only}: {ids:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_or_locked_compound_members_given_by_id_keep_the_compounds_fill() {
|
||||
for hide in [true, false] {
|
||||
let mut s = session();
|
||||
let [a, b] = [0.0, 2.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a, b]);
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.setProps", &if hide { json!({"id": a.0, "visible": false}) } else { json!({"id": a.0, "locked": true}) }).unwrap();
|
||||
let member = s.doc().unwrap().doc.node(a).unwrap();
|
||||
assert!(if hide { !member.visible } else { member.locked });
|
||||
let parent = s.doc().unwrap().doc.node(compound).unwrap();
|
||||
assert!(parent.visible && !parent.locked);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap()["count"], json!(0), "hidden: {hide}");
|
||||
assert_eq!(fill(&s, compound), before.node(compound).unwrap().appearance.fill_paint());
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_colors_follow_ids_order_without_repeating_objects() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 3);
|
||||
s.execute(C, &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "seed": 7})).unwrap();
|
||||
let first = fills(&s, &ids);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute(C, &json!({"ids": [ids[2].0, ids[0].0, ids[2].0, ids[1].0], "seed": 7})).unwrap()["count"], json!(3));
|
||||
assert_eq!(fills(&s, &[ids[2], ids[0], ids[1]]), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_members_color_the_outermost_compound_unless_an_ancestor_is_blocked() {
|
||||
for blocked in ["none", "hidden", "locked", "artboard"] {
|
||||
let mut s = session();
|
||||
let [a, b, c] = [0.0, 2.0, 4.0].map(|x| rect(&mut s, x));
|
||||
select(&mut s, &[a]);
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[group, b]);
|
||||
let inner = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[inner, c]);
|
||||
let outer = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
match blocked {
|
||||
"hidden" => {
|
||||
s.execute("object.setProps", &json!({"id": group.0, "visible": false})).unwrap();
|
||||
}
|
||||
"locked" => {
|
||||
s.execute("object.setProps", &json!({"id": inner.0, "locked": true})).unwrap();
|
||||
}
|
||||
"artboard" => {
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let members = fills(&s, &[a, b, c, group, inner]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"ids": [a.0], "scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(fills(&s, &[a, b, c, group, inner]), members, "{blocked}");
|
||||
if blocked == "none" {
|
||||
assert_eq!(r["count"], json!(1));
|
||||
assert_eq!(fill(&s, outer), Paint::solid(Color::gray(0.3)));
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
} else {
|
||||
assert_eq!(r["count"], json!(0), "{blocked}");
|
||||
assert_eq!(steps(&s), n, "{blocked}");
|
||||
}
|
||||
assert!(*s.doc().unwrap().doc == *before, "{blocked}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invalid_series_index_keeps_ordinary_subgroups_reachable() {
|
||||
let mut s = session();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["A"], "rows": [[20], [30]]}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let series = s.doc().unwrap().doc.node(graph).unwrap().children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let group = series.id;
|
||||
let marks: Vec<NodeId> = series.children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| n.id).collect();
|
||||
assert!(!marks.is_empty());
|
||||
select(&mut s, &marks);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.edit("Set series index", |d, _| {
|
||||
d.node_mut(group).unwrap().extras_mut().series_index = Some(u32::MAX);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = fills(&s, &marks);
|
||||
let r = s.execute(C, &json!({"ids": [group.0], "scheme": "gray", "min": 30, "max": 30})).unwrap();
|
||||
assert_eq!(r["count"], json!(marks.len()));
|
||||
assert!(fills(&s, &marks).iter().all(|p| *p == Paint::solid(Color::gray(0.3))));
|
||||
assert_ne!(fills(&s, &marks), before);
|
||||
assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_ref().unwrap().series_paints.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tint_swatch_with_a_deleted_base_is_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 2);
|
||||
select(&mut s, &ids);
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let tint = s.execute("swatch.new", &json!({"name": "Pale", "swatch": "Ink", "tint": 40})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
s.execute("swatch.delete", &json!({"name": "Ink", "unlink": false})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.swatch("Ink").is_none());
|
||||
assert_eq!(d.swatch_link(&tint), Some(("Ink".to_string(), 0.4)));
|
||||
let before = d.clone();
|
||||
let n = steps(&s);
|
||||
let e = s.execute(C, &json!({"scheme": "tint", "swatch": tint, "min": 10, "max": 80})).unwrap_err().to_string();
|
||||
assert!(e.contains("base swatch `Ink`"), "{e}");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inverted_range_that_rounds_to_equal_f32_bounds_is_refused() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
for p in [json!({"scheme": "gray", "min": 50.0000001, "max": 50}), json!({"scheme": "tint", "swatch": "Ink", "min": 50.0000001, "max": 50})] {
|
||||
let e = s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("`min` is greater than `max`"), "{p}: {e}");
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_undo_step_when_no_fill_changes() {
|
||||
let mut s = session();
|
||||
let ids = rects(&mut s, 2);
|
||||
select(&mut s, &ids);
|
||||
s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40})).unwrap();
|
||||
assert_eq!((r["count"].clone(), steps(&s)), (json!(0), n), "the same grays again");
|
||||
// Only unfilled objects: nothing to color.
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({})).unwrap()["count"], json!(0));
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
select(&mut s, &[a]);
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#336699"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#e01020", "spot": true})).unwrap();
|
||||
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
let bad: [(Value, &str); 14] = [
|
||||
(json!({"scheme": "rainbow"}), "`scheme` must be color, tint or gray"),
|
||||
(json!({"scheme": 3}), "`scheme` must be a string"),
|
||||
(json!({"min": 10}), "`min` and `max` go with scheme tint or gray"),
|
||||
(json!({"scheme": "gray", "swatch": "Ink"}), "`swatch` goes with scheme tint"),
|
||||
(json!({"scheme": "gray", "min": -1}), "`min` must be from 0 to 100"),
|
||||
(json!({"scheme": "gray", "max": 101}), "`max` must be from 0 to 100"),
|
||||
(json!({"scheme": "gray", "min": 80, "max": 20}), "`min` is greater than `max`"),
|
||||
(json!({"scheme": "gray", "max": "50"}), "`max` must be a number"),
|
||||
(json!({"scheme": "tint"}), "scheme tint needs a `swatch`"),
|
||||
(json!({"scheme": "tint", "swatch": "Nope"}), "no swatch `Nope`"),
|
||||
(json!({"scheme": "tint", "swatch": "Process"}), "is a process colour"),
|
||||
(json!({"seed": -1}), "`seed` must be a whole number"),
|
||||
(json!({"seed": 1.5}), "`seed` must be a whole number"),
|
||||
(json!({"ids": [999_999]}), "no such object id"),
|
||||
];
|
||||
for (p, want) in bad {
|
||||
let e = s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_a_locked_artboard_given_by_id_keeps_its_fill() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0);
|
||||
let before = fill(&s, a);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let n = steps(&s);
|
||||
assert_eq!(s.execute(C, &json!({"ids": [a.0], "seed": 3})).unwrap()["count"], json!(0));
|
||||
assert_eq!(fill(&s, a), before);
|
||||
assert_eq!(steps(&s), n);
|
||||
}
|
||||
@@ -120,6 +120,10 @@ fn palette_exports_take_the_transparency_dither() {
|
||||
let dithered = file(json!({"transparencyDither": method}));
|
||||
let [left, right] = opaque_halves(&dithered);
|
||||
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
|
||||
if method == "pattern" {
|
||||
// The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%.
|
||||
assert_eq!([left, right], [0.25, 0.75], "{format}");
|
||||
}
|
||||
assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file");
|
||||
// Without transparency the dither does nothing.
|
||||
let opaque = file(json!({"transparencyDither": method, "transparency": false}));
|
||||
|
||||
@@ -54,8 +54,8 @@ pub(crate) use series::{
|
||||
capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes,
|
||||
capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows,
|
||||
capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, graph_part_members, is_design_art,
|
||||
is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
|
||||
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
|
||||
is_graph_line, is_series_group, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks,
|
||||
series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -328,7 +328,9 @@ pub(super) fn column_art(
|
||||
}
|
||||
parts.push(Arc::new(d.reid(&crate::cmd::place::transformed(n, by))));
|
||||
}
|
||||
Some(Arc::new(Node::group(d.alloc_id(), parts)))
|
||||
let mut n = Node::group(d.alloc_id(), parts);
|
||||
n.extras_mut().graph_design_art = true;
|
||||
Some(Arc::new(n))
|
||||
};
|
||||
let mut parts = vec![];
|
||||
let (mut label, mut sliding) = (fit_affine(frame, rect), None);
|
||||
|
||||
@@ -271,7 +271,9 @@ impl Gen<'_> {
|
||||
/// A copy of design art drawn in a series: a single path gets a group of its own, as painting a series paints the
|
||||
/// paths directly inside its group and the design keeps its own paint.
|
||||
fn design_copy(&mut self, n: Arc<Node>) -> Arc<Node> {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n }
|
||||
let mut n = if matches!(n.kind, NodeKind::Path { .. }) { Arc::new(Node::group(self.d.alloc_id(), vec![n])) } else { n };
|
||||
Arc::make_mut(&mut n).extras_mut().graph_design_art = true;
|
||||
n
|
||||
}
|
||||
/// A series group. Empty series are omitted by the caller; the index is stored on the group
|
||||
/// so later paint edits find the series without counting siblings.
|
||||
|
||||
@@ -204,7 +204,7 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i
|
||||
|
||||
/// 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 {
|
||||
pub(crate) 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))
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Vector Halftone…",
|
||||
["Object"],
|
||||
None,
|
||||
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
has_selection,
|
||||
halftone
|
||||
)]
|
||||
@@ -28,7 +28,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.vectorHalftone";
|
||||
let shape = match text_param(p, "shape", C)? {
|
||||
Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?,
|
||||
Some(v) => {
|
||||
DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))?
|
||||
}
|
||||
None => DotShape::Circle,
|
||||
};
|
||||
let frequency = number_or(p, "frequency", 20.0, C)?;
|
||||
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Document Profiles",
|
||||
[],
|
||||
None,
|
||||
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
|
||||
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), unusable?: why file.new does not read it (a link or a folder: new documents get the defaults, and file.newProfiles.edit refuses it), path?; customized, unusable and path left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
|
||||
always,
|
||||
list_profiles
|
||||
),
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Profile",
|
||||
[],
|
||||
None,
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; an error when its file is a link or a folder, which file.new does not read either; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
|
||||
always,
|
||||
edit_profile
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset Profile",
|
||||
[],
|
||||
None,
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again (a link is removed, not the file it leads to; a folder is not deleted, an error); an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
|
||||
always,
|
||||
reset_profile
|
||||
),
|
||||
@@ -996,6 +996,44 @@ pub fn profile_names() -> impl Iterator<Item = &'static str> {
|
||||
CATEGORIES.iter().map(|c| c.0)
|
||||
}
|
||||
|
||||
/// What is at a New Document profile's file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ProfileFile {
|
||||
/// Nothing: the shipped profile applies.
|
||||
None,
|
||||
/// A plain file, which `file.new` reads.
|
||||
Plain,
|
||||
/// A link or another entry that is not a plain file or a folder: `file.new` does not read it (the
|
||||
/// new document has the defaults), `file.newProfiles.edit` does not open it and
|
||||
/// `file.newProfiles.reset` removes it (a link, not what it leads to).
|
||||
NotPlain,
|
||||
/// A folder, which `file.new` does not read and `file.newProfiles.edit` does not open either.
|
||||
/// `file.newProfiles.reset` does not delete a folder.
|
||||
Folder,
|
||||
}
|
||||
|
||||
impl ProfileFile {
|
||||
/// Whether the category has a file in place of the shipped profile.
|
||||
pub fn customized(self) -> bool {
|
||||
self != Self::None
|
||||
}
|
||||
|
||||
/// Whether `file.newProfiles.reset` removes what is there.
|
||||
pub fn resettable(self) -> bool {
|
||||
matches!(self, Self::Plain | Self::NotPlain)
|
||||
}
|
||||
}
|
||||
|
||||
/// What is at `path`, looked at without following a link.
|
||||
fn profile_file(path: &std::path::Path) -> ProfileFile {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(m) if crate::store::is_plain(&m) => ProfileFile::Plain,
|
||||
Ok(m) if m.is_dir() && !crate::store::is_link_entry(&m) => ProfileFile::Folder,
|
||||
Ok(_) => ProfileFile::NotPlain,
|
||||
Err(_) => ProfileFile::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The profile `v` names (a built-in category, any case).
|
||||
fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> {
|
||||
let name = v.as_str().map(str::trim).unwrap_or_default();
|
||||
@@ -1022,9 +1060,9 @@ impl Session {
|
||||
Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION)))
|
||||
}
|
||||
|
||||
/// Whether profile `name` has a file, which `file.newProfiles.reset` deletes.
|
||||
pub fn new_doc_profile_customized(&self, name: &str) -> bool {
|
||||
self.profile_path(name).is_some_and(|p| p.is_file())
|
||||
/// What is at profile `name`'s file, looked at without following a link.
|
||||
pub fn new_doc_profile_file(&self, name: &str) -> ProfileFile {
|
||||
self.profile_path(name).map_or(ProfileFile::None, |p| profile_file(&p))
|
||||
}
|
||||
|
||||
/// Profile `name`'s document, its file's path and a warning for each color profile the file
|
||||
@@ -1045,7 +1083,7 @@ impl Session {
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
// A link is refused: the script's gate does not check where it leads.
|
||||
Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()),
|
||||
Ok(m) if !crate::store::is_plain(&m) => return Err(crate::store::NOT_PLAIN.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
@@ -1088,7 +1126,11 @@ fn list_profiles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// A request that may not read the folder learns nothing of its files.
|
||||
Some(path) => {
|
||||
if let Some(p) = shown(&path) {
|
||||
v["customized"] = json!(path.is_file());
|
||||
let file = profile_file(&path);
|
||||
v["customized"] = json!(file.customized());
|
||||
if matches!(file, ProfileFile::NotPlain | ProfileFile::Folder) {
|
||||
v["unusable"] = json!(crate::store::NOT_PLAIN);
|
||||
}
|
||||
v["path"] = json!(p);
|
||||
}
|
||||
}
|
||||
@@ -1121,12 +1163,19 @@ fn edit_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = file.to_string_lossy().to_string();
|
||||
// document.open reads it next: a profile it can't open is not written either.
|
||||
crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?;
|
||||
if !file.exists() {
|
||||
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
|
||||
file.parent()
|
||||
.map_or(Ok(()), std::fs::create_dir_all)
|
||||
.and_then(|()| std::fs::write(&file, bytes))
|
||||
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
|
||||
match profile_file(&file) {
|
||||
ProfileFile::Plain => {}
|
||||
// file.new does not read a link or a folder, so it is not opened as the profile either.
|
||||
ProfileFile::NotPlain | ProfileFile::Folder => return Err(profile_error(format!("{path}: {}", crate::store::NOT_PLAIN), &path)),
|
||||
// Made new, so a dangling link put there since is not written through.
|
||||
ProfileFile::None => {
|
||||
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
|
||||
file.parent()
|
||||
.map_or(Ok(()), std::fs::create_dir_all)
|
||||
.and_then(|()| std::fs::OpenOptions::new().write(true).create_new(true).open(&file))
|
||||
.and_then(|mut f| std::io::Write::write_all(&mut f, &bytes))
|
||||
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
|
||||
}
|
||||
}
|
||||
s.execute("document.open", &json!({ "path": path }))
|
||||
}
|
||||
@@ -1136,9 +1185,14 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?;
|
||||
let file = writable_profile(s, name, C)?;
|
||||
let path = file.to_string_lossy().to_string();
|
||||
if profile_file(&file) == ProfileFile::Folder {
|
||||
return Err(profile_error(format!("{path}: a folder, which Reset does not delete"), &path));
|
||||
}
|
||||
let reset = match std::fs::remove_file(&file) {
|
||||
Ok(()) => true,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
// On Windows a link to a folder, or a junction, is removed as a folder; what it leads to stays.
|
||||
Err(_) if std::fs::symlink_metadata(&file).is_ok_and(|m| crate::store::is_link_entry(&m)) && std::fs::remove_dir(&file).is_ok() => true,
|
||||
Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)),
|
||||
};
|
||||
Ok(json!({ "name": name, "reset": reset }))
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.groupRows",
|
||||
"addon.arrange.markBounds",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.offset",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
@@ -30,6 +32,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.color.fillToStroke",
|
||||
"addon.color.filter",
|
||||
"addon.color.nearestSwatch",
|
||||
"addon.color.randomFill",
|
||||
"addon.color.select",
|
||||
"addon.color.strokeToFill",
|
||||
"addon.color.swatchLegend",
|
||||
|
||||
@@ -149,17 +149,30 @@ pub(crate) fn clip_group(d: &mut Document, path: PathData, rule: FillRule, art:
|
||||
}
|
||||
|
||||
/// Render `nodes` alone over transparency: (premultiplied pixels, width, height).
|
||||
fn render(doc: &Document, nodes: Vec<Node>, region: Rect, scale: f64, anti_alias: AntiAlias) -> vectorcraft_render::Rendered {
|
||||
let mut tmp = doc.clone();
|
||||
fn render(doc: &mut Document, nodes: Vec<Node>, region: Rect, scale: f64, anti_alias: AntiAlias) -> vectorcraft_render::Rendered {
|
||||
struct RestoreLayers<'a> {
|
||||
doc: &'a mut Document,
|
||||
original: Vec<Arc<Node>>,
|
||||
}
|
||||
|
||||
impl Drop for RestoreLayers<'_> {
|
||||
fn drop(&mut self) {
|
||||
std::mem::swap(&mut self.doc.layers, &mut self.original);
|
||||
}
|
||||
}
|
||||
|
||||
let mut layer = Node::layer(NodeId(u64::MAX), "raster", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
*ch = nodes.into_iter().map(Arc::new).collect();
|
||||
}
|
||||
tmp.layers = vec![Arc::new(layer)];
|
||||
// Keep the same resource tables, including images made by earlier effects, without
|
||||
// copying them for each render. Restore the original layers even if rendering unwinds.
|
||||
let original = std::mem::replace(&mut doc.layers, vec![Arc::new(layer)]);
|
||||
let scoped = RestoreLayers { doc, original };
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
r.threads = 0;
|
||||
// Art Optimized is supersampled, as in exports: shapes meeting edge to edge leave no seam.
|
||||
r.render_region_with(&tmp, region, scale, &RenderOptions { skip_templates: true, anti_alias, supersample: true, ..Default::default() })
|
||||
r.render_region_with(scoped.doc, region, scale, &RenderOptions { skip_templates: true, anti_alias, supersample: true, ..Default::default() })
|
||||
}
|
||||
|
||||
/// The note for pixels drawn since [`vectorcraft_render::decode_failures`] stood at `failed`, when
|
||||
|
||||
@@ -589,6 +589,18 @@ fn overflow_note(ids: &[NodeId], left_out: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Create Outlines has a text object to convert in the selected roots.
|
||||
pub fn can_create_outlines(s: &Session) -> bool {
|
||||
use std::ops::ControlFlow::{Break, Continue};
|
||||
|
||||
let Ok(roots) = selected_roots(s) else { return false };
|
||||
let Some(st) = s.active() else { return false };
|
||||
roots
|
||||
.iter()
|
||||
.filter_map(|id| st.doc.node(*id))
|
||||
.any(|node| node.try_walk(&mut |child| if matches!(child.kind, NodeKind::Text(_)) { Break(()) } else { Continue(()) }).is_break())
|
||||
}
|
||||
|
||||
/// Text objects among `ids` and their descendants.
|
||||
fn text_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
text_ids_where(d, ids, |_| true)
|
||||
|
||||
@@ -39,6 +39,7 @@ pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_
|
||||
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::typecmd::can_create_outlines;
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use cmd::{EyedropperOptions, PathfinderOptions};
|
||||
pub use journal::Journal;
|
||||
|
||||
@@ -2691,8 +2691,9 @@ struct Destination {
|
||||
|
||||
/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the
|
||||
/// same document as `item`. An object may go directly above or below itself: a copy goes there, as
|
||||
/// `layer.move` puts copies, and a move there leaves the object where it is.
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result<Destination, HostError> {
|
||||
/// `layer.move` puts copies, and a move there leaves the object where it is. A copy (`copy`) of a
|
||||
/// clipping path cannot go below it.
|
||||
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
|
||||
let how = placement_of(how)?;
|
||||
let beside = matches!(how, Placement::Above | Placement::Below);
|
||||
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
|
||||
@@ -2725,6 +2726,15 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
|
||||
(parent, Some(target))
|
||||
}
|
||||
};
|
||||
// The clipping path stays at the bottom of its clip group or clipping layer. Moving the
|
||||
// clipping path below itself leaves it where it is.
|
||||
if how == Placement::Below
|
||||
&& (target != item.id || copy)
|
||||
&& d.node(parent).is_some_and(crate::doc::Node::clips)
|
||||
&& d.position(target).is_some_and(|(_, i, _)| i == 0)
|
||||
{
|
||||
return Err(HostError::Error("an object cannot go below a clipping mask".into()));
|
||||
}
|
||||
if !editable(d, parent) {
|
||||
return Err(HostError::Error("the layer or group is hidden or locked".into()));
|
||||
}
|
||||
@@ -2784,7 +2794,7 @@ fn item_move(h: &Host, a: &[Data]) -> Answer {
|
||||
if matches!(arg(a, 1), Data::Undefined) {
|
||||
return Err(HostError::Type("move needs a relative object".into()));
|
||||
}
|
||||
let to = destination(h, item, arg(a, 1), arg(a, 2))?;
|
||||
let to = destination(h, item, arg(a, 1), arg(a, 2), false)?;
|
||||
if to.beside != Some(item.id) {
|
||||
place(h, item.doc, item.id, &to)?;
|
||||
}
|
||||
@@ -2825,7 +2835,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
None
|
||||
}
|
||||
target => Some(destination(h, item, target, arg(a, 2))?),
|
||||
target => Some(destination(h, item, target, arg(a, 2), true)?),
|
||||
};
|
||||
let id = atomically(h, |h| {
|
||||
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
|
||||
@@ -2857,17 +2867,22 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (before, after) = with_doc(h, item.doc, |_, st| {
|
||||
let at = st.doc.position(item.id);
|
||||
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
|
||||
(at.map(|(_, i, _)| i), count)
|
||||
// The Arrange commands keep a clipping path at the bottom of its parent and the art below the
|
||||
// parent's ruler guides, so the item's place is counted among the art above the clipping path.
|
||||
let (before, floor, art) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let at = d.position(item.id);
|
||||
let parent = at.and_then(|(p, ..)| p);
|
||||
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips));
|
||||
let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c));
|
||||
(at.map(|(_, i, _)| i), floor, art)
|
||||
});
|
||||
let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) };
|
||||
let top = i + 1 >= after;
|
||||
let unchanged = match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => top,
|
||||
_ => i == 0,
|
||||
};
|
||||
let unchanged = i < floor
|
||||
|| match id {
|
||||
"object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art,
|
||||
_ => i <= floor,
|
||||
};
|
||||
if !unchanged {
|
||||
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,9 @@
|
||||
//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside
|
||||
//! groups and compound paths included.
|
||||
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
|
||||
//! or locked layer or group, throws `Cannot edit` with nothing changed.
|
||||
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
|
||||
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
|
||||
//! artboard.
|
||||
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
|
||||
//! commands change in its place, and a gradient that `filled = true` gives it is placed on that
|
||||
//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and
|
||||
@@ -106,6 +108,18 @@ fn cannot_edit(id: NodeId) -> HostError {
|
||||
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
|
||||
}
|
||||
|
||||
/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or
|
||||
/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one.
|
||||
fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> {
|
||||
if !editable(&st.doc, id) {
|
||||
return Err(cannot_edit(id));
|
||||
}
|
||||
if super::on_locked_artboard(h, st, id) {
|
||||
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The path `d` names, which must still be in its document.
|
||||
fn path_of(h: &super::Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let item = item_of(h, d)?;
|
||||
@@ -234,7 +248,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
|
||||
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
|
||||
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
|
||||
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
|
||||
/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
|
||||
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
|
||||
/// that is, is written at once, so that its points read as the grid snaps them.
|
||||
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
forget_waiting_starts(h);
|
||||
@@ -246,15 +260,13 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
|
||||
flush(h)?;
|
||||
let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?;
|
||||
let r = f(&mut subs);
|
||||
let (same, ok, aligned) = read_path(h, item, |st, _, pd| {
|
||||
let (same, refused, aligned) = read_path(h, item, |st, _, pd| {
|
||||
let d = &st.doc;
|
||||
let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned)));
|
||||
(pd.subpaths == subs, editable(d, item.id), aligned)
|
||||
(pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned)
|
||||
})?;
|
||||
if !same {
|
||||
if !ok {
|
||||
return Err(cannot_edit(item.id));
|
||||
}
|
||||
refused?;
|
||||
*h.dom.pending.borrow_mut() = Some((item, subs));
|
||||
if aligned {
|
||||
flush(h)?;
|
||||
@@ -337,15 +349,12 @@ fn drawing_normally<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
|
||||
/// must be one the user could edit.
|
||||
/// must be one the user could edit ([`refuse_path_edit`]).
|
||||
/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the
|
||||
/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put
|
||||
/// back afterwards, so the edit changes only the path.
|
||||
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
|
||||
let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id));
|
||||
if !ok {
|
||||
return Err(cannot_edit(item.id));
|
||||
}
|
||||
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.entry("ids").or_insert_with(|| json!([item.id.0]));
|
||||
}
|
||||
@@ -436,18 +445,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
|
||||
/// path, or one in a hidden or locked layer or group, stops it before anything is deleted.
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused) = with_doc(h, doc, |_, st| {
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
|
||||
Ok::<_, HostError>((ids, refused))
|
||||
let locks = st.doc.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
|
||||
}
|
||||
if !on_locked.is_empty() {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
}
|
||||
|
||||
@@ -222,6 +222,18 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
/// What [`read_capped_plain`] tells a path that is not a plain file.
|
||||
pub(crate) const NOT_PLAIN: &str = "not a plain file";
|
||||
|
||||
/// Whether `m`, read without following a link, is a plain file: not a link, a folder or (on Windows)
|
||||
/// a junction or other reparse point.
|
||||
pub(crate) fn is_plain(m: &std::fs::Metadata) -> bool {
|
||||
m.file_type().is_file() && !reparse_point(m)
|
||||
}
|
||||
|
||||
/// Whether `m`, read without following a link, is a link (on Windows also a junction or other
|
||||
/// reparse point).
|
||||
pub(crate) fn is_link_entry(m: &std::fs::Metadata) -> bool {
|
||||
m.file_type().is_symlink() || reparse_point(m)
|
||||
}
|
||||
|
||||
/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without
|
||||
/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and
|
||||
/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check
|
||||
|
||||
@@ -523,6 +523,7 @@ fn ids_null_takes_the_selection_in_every_command_that_falls_back_to_it() {
|
||||
("addon.cleanup.deepUngroup", json!({}), rect),
|
||||
("addon.cleanup.rejoin", json!({}), rect),
|
||||
("addon.color.nearestSwatch", json!({}), rect),
|
||||
("addon.color.randomFill", json!({"seed": 1}), rect),
|
||||
("addon.pathtools.cornerSet", json!({"radius": 2}), rect),
|
||||
("addon.pathtools.cornerRemove", json!({}), rect),
|
||||
("addon.pathtools.shape.convert", json!({}), rect),
|
||||
|
||||
@@ -435,7 +435,7 @@ fn alt_drag_of_30000_objects_takes_few_tree_walks() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Copy"));
|
||||
// The squares stay; their copies move together.
|
||||
let moved = bounds(&s, copies[0]).origin() - square_at(0).origin();
|
||||
assert!(moved.x > 0.0, "{moved:?}");
|
||||
assert!((moved.x - 80.0).abs() < 1e-6 && moved.y.abs() < 1e-6, "the copies move by the drag: {moved:?}");
|
||||
for (k, (id, copy)) in ids.iter().zip(&copies).enumerate() {
|
||||
assert_eq!(bounds(&s, *id), square_at(k));
|
||||
assert_eq!(bounds(&s, *copy), square_at(k) + moved);
|
||||
|
||||
@@ -1168,6 +1168,70 @@ fn a_profile_that_is_a_link_is_not_followed() {
|
||||
assert!(r.get("profile").is_none(), "{r}");
|
||||
}
|
||||
|
||||
/// The listing entry of profile `name`.
|
||||
fn listed_profile(s: &mut Session, name: &str) -> Value {
|
||||
let listed = s.execute("file.newProfiles", &json!({})).unwrap();
|
||||
listed["profiles"].as_array().unwrap().iter().find(|p| p["name"] == name).cloned().unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_linked_profile_is_listed_as_unusable_and_reset_removes_the_link() {
|
||||
use crate::cmd::newdoc::ProfileFile;
|
||||
let (mut s, dir, root) = with_profiles("linked-listing");
|
||||
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
|
||||
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::Plain);
|
||||
assert!(listed_profile(&mut s, "Print").get("unusable").is_none());
|
||||
let outside = root.join("outside.vectorcraft");
|
||||
std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap();
|
||||
|
||||
// file.new does not read it, so the listing says so, and Edit does not open it.
|
||||
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::NotPlain);
|
||||
assert!(ProfileFile::NotPlain.resettable());
|
||||
let p = listed_profile(&mut s, "Print");
|
||||
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
|
||||
let e = s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap_err().to_string();
|
||||
assert!(e.contains("not a plain file"), "{e}");
|
||||
// Reset removes the link and leaves the file it led to.
|
||||
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap()["reset"], true);
|
||||
assert!(std::fs::symlink_metadata(dir.join("Print.vectorcraft")).is_err() && outside.is_file());
|
||||
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_profile_link_to_nothing_is_listed_and_edit_does_not_write_through_it() {
|
||||
let (mut s, dir, root) = with_profiles("dangling");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let outside = root.join("outside.vectorcraft");
|
||||
std::os::unix::fs::symlink(&outside, dir.join("Web.vectorcraft")).unwrap();
|
||||
let p = listed_profile(&mut s, "Web");
|
||||
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
|
||||
assert!(s.execute("file.newProfiles.edit", &json!({"name": "Web"})).is_err());
|
||||
assert!(!outside.exists(), "Edit wrote the shipped profile where the link leads");
|
||||
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Web"})).unwrap()["reset"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_in_a_profiles_place_is_listed_as_unusable() {
|
||||
let (mut s, dir, _root) = with_profiles("folder");
|
||||
std::fs::create_dir_all(dir.join("Mobile.vectorcraft")).unwrap();
|
||||
let p = listed_profile(&mut s, "Mobile");
|
||||
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
|
||||
let e = s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap_err().to_string();
|
||||
assert!(e.contains("not a plain file"), "{e}");
|
||||
let r = s.execute("file.new", &json!({"profile": "Mobile"})).unwrap();
|
||||
assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}");
|
||||
// Reset does not delete a folder, and Manage Profiles turns it off.
|
||||
let file = s.new_doc_profile_file("Mobile");
|
||||
assert_eq!(file, crate::cmd::newdoc::ProfileFile::Folder);
|
||||
assert!(file.customized() && !file.resettable());
|
||||
let e = s.execute("file.newProfiles.reset", &json!({"name": "Mobile"})).unwrap_err().to_string();
|
||||
assert!(e.contains("a folder"), "{e}");
|
||||
assert!(dir.join("Mobile.vectorcraft").is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_names_are_checked_and_editing_needs_the_folder() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -104,6 +104,27 @@ fn assert_written(what: &str, d: &Document) {
|
||||
assert!(diff < 0.02 && diff < without / 4.0, "{what}: read back {:.2}% off ({:.2}% without the effects)", diff * 100.0, without * 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_pass_keeps_layers_and_a_previously_generated_image() {
|
||||
use crate::cmd::rasterfx::effect_image;
|
||||
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let art = rect(&mut d, Rect::new(40.0, 40.0, 80.0, 80.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let original_layer = Arc::clone(&d.layers[0]);
|
||||
let first = effect_image(&mut d, &art, None, 1.0).unwrap();
|
||||
let second = effect_image(&mut d, &first, None, 1.0).unwrap();
|
||||
|
||||
assert_eq!(d.layers.len(), 1);
|
||||
assert!(Arc::ptr_eq(&d.layers[0], &original_layer));
|
||||
assert_eq!(d.images.len(), 2);
|
||||
|
||||
add(&mut d, second);
|
||||
let rendered = render(&d);
|
||||
let at = (60 * rendered.width as usize + 60) * 4;
|
||||
let pixel = &rendered.pixels[at..at + 4];
|
||||
assert!(pixel[0] > 240 && pixel[1] < 15 && pixel[2] < 15, "the second pass still reads the first pass's image: {pixel:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_layers_type_images_and_symbols_keep_their_raster_effects() {
|
||||
// A group's shadow (one shadow of both members).
|
||||
|
||||
@@ -739,6 +739,8 @@ fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
|
||||
let art = || PdfPage::new(100.0, 50.0, "1 0 0 rg 10 10 20 20 re f");
|
||||
write(&src, &pdf(&[art(), PdfPage::new(80.0, 40.0, ""), art()], None));
|
||||
let mut s = Session::new();
|
||||
// A freed buffer that had the blob's address may have been read before, in another test.
|
||||
let mark = vectorcraft_pdf::read_mark();
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let boards: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
|
||||
@@ -748,7 +750,7 @@ fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
|
||||
// The pages are read from the one copy every page's blob keeps: a page that read the file
|
||||
// again would count here.
|
||||
let blob = d.images.values().next().map(|b| b.bytes.clone()).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::reads_of(&blob), 0, "the pages are read from the file read once");
|
||||
assert_eq!(vectorcraft_pdf::reads_of_since(&blob, mark), 0, "the pages are read from the file read once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1545,10 +1545,10 @@ fn kept_art_follows_the_swatches_once_a_replaced_plugin_paints() {
|
||||
assert_eq!(draw(&s), (WHITE, RED), "without the swatch, the object as it is");
|
||||
}
|
||||
|
||||
/// Whether `px` is within 40 levels of `want` on every channel. A blur leaves the middle of a
|
||||
/// shape close to its color.
|
||||
/// Whether `px` is within 2 levels of `want` on every channel. The samples sit well inside their
|
||||
/// shapes, so a blur changes them only by rounding.
|
||||
fn near(px: [u8; 4], want: [u8; 4]) -> bool {
|
||||
px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 40)
|
||||
px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2)
|
||||
}
|
||||
|
||||
/// A kept raster of a blur over a painted effect is made again when a swatch its piece names
|
||||
|
||||
@@ -119,33 +119,23 @@ fn mean_diff(a: &Rendered, b: &Rendered) -> f64 {
|
||||
fn listed_applied_edited_and_undone() {
|
||||
let (mut s, g) = striped();
|
||||
let list = s.execute("effect.list", &json!({})).unwrap();
|
||||
for (id, _) in EFFECTS {
|
||||
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed"));
|
||||
assert_eq!(e["raster"], json!(true), "{id}");
|
||||
assert!(e["params"].as_str().unwrap().contains("radius") || id == "blur.radial", "{id}");
|
||||
}
|
||||
let menus: Vec<Value> =
|
||||
EFFECTS.iter().map(|(id, _)| list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap()["menu"].clone()).collect();
|
||||
assert_eq!(menus, [json!(["Effect", "Blur"]), json!(["Effect", "Blur"]), json!(["Effect", "Sharpen"])]);
|
||||
for (group, menu) in [
|
||||
(ARTISTIC.as_slice(), "Artistic"),
|
||||
(BRUSH_STROKES.as_slice(), "Brush Strokes"),
|
||||
(DISTORT.as_slice(), "Distort"),
|
||||
(PIXELATE.as_slice(), "Pixelate"),
|
||||
(SKETCH.as_slice(), "Sketch"),
|
||||
(TEXTURE.as_slice(), "Texture"),
|
||||
(VIDEO.as_slice(), "Video"),
|
||||
([("video.ntscColors", "{}")].as_slice(), "Video"),
|
||||
// A few representative entries, one per kind of submenu, are listed as raster effects.
|
||||
for (id, menu) in [
|
||||
("blur.radial", "Blur"),
|
||||
("sharpen.unsharpMask", "Sharpen"),
|
||||
("artistic.cutout", "Artistic"),
|
||||
("sketch.chrome", "Sketch"),
|
||||
("video.ntscColors", "Video"),
|
||||
] {
|
||||
for (id, _) in group {
|
||||
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap_or_else(|| panic!("{id} listed"));
|
||||
assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}");
|
||||
}
|
||||
let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed"));
|
||||
assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}");
|
||||
}
|
||||
assert!(list["catalog"].as_array().unwrap().iter().all(|e| e["id"] != "blur.notAnEffect"));
|
||||
assert!(s.execute("effect.apply", &json!({"effect": "blur.notAnEffect", "ids": [g]})).is_err());
|
||||
// Numbers far out of range are stored as given and read clamped; the canvas still draws.
|
||||
// Radial Blur's Blur Center is refused outside 0 to 1 instead.
|
||||
let center = |id: &str, k: &str| id == "blur.radial" && matches!(k, "centerX" | "centerY");
|
||||
for (id, _) in EFFECTS {
|
||||
for id in ["blur.radial", "sharpen.unsharpMask"] {
|
||||
let defaults = vectorcraft_render::effects::default_params(id).unwrap();
|
||||
let junk: serde_json::Map<String, Value> = defaults
|
||||
.as_object()
|
||||
@@ -161,11 +151,11 @@ fn listed_applied_edited_and_undone() {
|
||||
assert!(s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"centerX": 1e308}})).is_err());
|
||||
let _ = render(&s);
|
||||
let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone();
|
||||
assert_eq!(n.appearance.effects.len(), 3);
|
||||
assert_eq!(n.appearance.effects.len(), 2);
|
||||
assert_eq!(n.appearance.effects[0].params["method"], json!("spin"), "defaults fill the rest");
|
||||
s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"method": "zoom"}})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects[0].params["method"], json!("zoom"));
|
||||
for _ in 0..4 {
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects.is_empty());
|
||||
|
||||
@@ -925,6 +925,87 @@ fn a_path_inside_a_compound_path_is_not_reordered() {
|
||||
assert_eq!(out, vec![json!([1, 2])]);
|
||||
}
|
||||
|
||||
/// [`doc`] with `a`, `b` and a rectangle `c` on top made into a clip group `g`, clipped by `c`. The
|
||||
/// page items are `g`, `b`, `a` and `c`, topmost first.
|
||||
fn clip_group() -> (Session, NodeId, NodeId, NodeId, NodeId) {
|
||||
let (mut s, a, b) = doc();
|
||||
let c = rect(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(children_of(&s, g), [c, a, b], "the clipping path is at the bottom");
|
||||
(s, g, a, b, c)
|
||||
}
|
||||
|
||||
/// The ids of the children of `id`, bottom first.
|
||||
fn children_of(s: &Session, id: NodeId) -> Vec<NodeId> {
|
||||
s.active().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_placed_below_a_clipping_path() {
|
||||
let (mut s, g, a, b, c) = clip_group();
|
||||
let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s));
|
||||
// From outside the group, from above the clipping path inside it, a copy, and a copy of the
|
||||
// clipping path below itself.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, mask = p[4], out = [];\
|
||||
var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\
|
||||
function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\
|
||||
function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); },\
|
||||
function () { mask.duplicate(mask, ElementPlacement.PLACEAFTER); }];\
|
||||
for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\
|
||||
vc.log(out);",
|
||||
);
|
||||
let messages = out[0].as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(messages.len(), 4, "{out:?}");
|
||||
for m in &messages {
|
||||
assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}");
|
||||
}
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// Directly above the clipping path is allowed, and so is moving the clipping path beside itself.
|
||||
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[4], ElementPlacement.PLACEBEFORE);");
|
||||
assert_eq!(children_of(&s, g), [c, d, a, b]);
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var p = app.activeDocument.pageItems; p[4].move(p[4], ElementPlacement.PLACEAFTER);");
|
||||
assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, d, a, b], steps));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zorder_that_leaves_an_object_in_place_runs_no_command() {
|
||||
// The topmost art of a layer with a ruler guide above it.
|
||||
let (mut s, a, b) = doc();
|
||||
let layer = s.active().unwrap().doc.layers[0].id;
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap();
|
||||
let kids = s.active().unwrap().doc.layers[0].children().unwrap().clone();
|
||||
assert!(kids.len() == 3 && kids[2].is_ruler_guide(), "the guide is above the art");
|
||||
let steps = undo_steps(&s);
|
||||
let r =
|
||||
run(&mut s, "var p = app.activeDocument.pageItems; p[0].zOrder(ZOrderMethod.BRINGTOFRONT); p[0].zOrder(ZOrderMethod.BRINGFORWARD);").unwrap();
|
||||
assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps));
|
||||
assert_eq!(layer_order(&s)[..2], [a, b]);
|
||||
// The lowest object above a clipping path, and the clipping path itself.
|
||||
let (mut s, g, a, b, c) = clip_group();
|
||||
let steps = undo_steps(&s);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD,\
|
||||
ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\
|
||||
p[2].zOrder(ZOrderMethod.SENDBACKWARD); p[2].zOrder(ZOrderMethod.SENDTOBACK);\
|
||||
for (var k = 0; k < ways.length; k++) p[3].zOrder(ways[k]);",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps));
|
||||
assert_eq!(children_of(&s, g), [c, a, b]);
|
||||
// A change still runs the command.
|
||||
log(&mut s, "app.activeDocument.pageItems[1].zOrder(ZOrderMethod.SENDTOBACK);");
|
||||
assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, b, a], steps + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() {
|
||||
let (mut s, a, b) = doc();
|
||||
|
||||
@@ -1480,6 +1480,34 @@ fn assigning_guides_refuses_paths_that_cannot_be_selected() {
|
||||
assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_changes_refuse_paths_on_a_locked_artboard() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
// Points (waiting and written at once), paint, stroke and a transform.
|
||||
for change in [
|
||||
"p.closed = false;",
|
||||
"p.pathPoints[0].anchor = [1, 2];",
|
||||
"p.setEntirePath([[0, 0], [10, 10]]);",
|
||||
"p.filled = false;",
|
||||
"p.strokeWidth = 7;",
|
||||
"p.translate(5, 5);",
|
||||
] {
|
||||
let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}"));
|
||||
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}");
|
||||
}
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete objects on a locked artboard"), "{e}");
|
||||
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps));
|
||||
// A value the path has changes nothing and does not throw, and the path changes once the
|
||||
// artboard is unlocked.
|
||||
log(&mut s, "app.activeDocument.pathItems[0].closed = true;");
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].strokeWidth = 7;");
|
||||
assert_ne!(art(&s), before);
|
||||
}
|
||||
|
||||
fn is_guide(s: &Session, id: NodeId) -> bool {
|
||||
matches!(node(s, id).kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
@@ -197,6 +197,10 @@ fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() {
|
||||
let dithered = file(&mut s, p.clone());
|
||||
let [left, right] = opaque_halves(&pixels(&dithered));
|
||||
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
|
||||
if method == "pattern" {
|
||||
// The ordered pattern keeps exactly one pixel of each 2x2 cell at 25% and three at 75%.
|
||||
assert_eq!([left, right], [0.25, 0.75], "{format}");
|
||||
}
|
||||
if format == "gif" {
|
||||
assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}");
|
||||
}
|
||||
|
||||
@@ -832,6 +832,9 @@ fn structured_junk() {
|
||||
("addon.color.nearestSwatch", json!({"library": "spectrum-gradients", "fill": "x", "ids": [u64::MAX]})),
|
||||
("addon.color.applyNearestSwatch", json!({"library": "web-safe-216", "fill": true, "stroke": true})),
|
||||
("addon.color.applyNearestSwatch", json!({"library": "nope", "ids": "x", "stroke": 3})),
|
||||
("addon.color.randomFill", json!({"seed": u64::MAX})),
|
||||
("addon.color.randomFill", json!({"scheme": "gray", "min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
|
||||
("addon.color.randomFill", json!({"scheme": "tint", "swatch": "[Registration]", "min": 100, "max": 0, "seed": 1e308, "ids": []})),
|
||||
("effect.apply", json!({"effect": "no.such.effect"})),
|
||||
("effect.remove", json!({"index": 99})),
|
||||
("effect.remove", json!({"indices": [0, 99, u64::MAX]})),
|
||||
@@ -1034,6 +1037,8 @@ fn structured_junk() {
|
||||
("addon.arrange.match", json!({"source": "key", "rotate": true})),
|
||||
("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})),
|
||||
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
|
||||
("addon.arrange.groupRows", json!({"direction": "column"})),
|
||||
("addon.arrange.groupRows", json!({"direction": "diagonal", "junk": f64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": 100, "max": 0, "seed": 1e308, "ids": []})),
|
||||
@@ -1042,6 +1047,10 @@ fn structured_junk() {
|
||||
("addon.arrange.sort", json!({"by": "opacity", "apply": "y", "order": "descending", "ids": [u64::MAX]})),
|
||||
("addon.arrange.sort", json!({"by": "x", "apply": "opacity", "distribute": true, "seed": 1e308, "ids": []})),
|
||||
("addon.arrange.sort", json!({"by": "nope", "apply": null, "order": 3, "distribute": "x"})),
|
||||
("addon.arrange.markBounds", json!({"style": "rectangle", "bounds": "visual", "weight": 1000, "color": "cmyk 0 100 100 0"})),
|
||||
("addon.arrange.markBounds", json!({"length": 1e6, "weight": 0.01, "color": [0, 0, 1]})),
|
||||
("addon.arrange.markBounds", json!({"length": f64::MAX, "weight": -1, "color": "#ff000080", "style": 3})),
|
||||
("addon.arrange.markBounds", json!({"length": 1e-308, "bounds": "nope", "color": {"swatch": 1}})),
|
||||
("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})),
|
||||
("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})),
|
||||
("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})),
|
||||
|
||||
@@ -744,20 +744,41 @@ fn objects_beyond_the_document_range_are_left_out() {
|
||||
assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings);
|
||||
}
|
||||
|
||||
/// A magenta rectangle with a Recolor adjustment (`RcRA`) attached, at `lightness`.
|
||||
fn recolored(visible: bool, lightness: f64) -> F {
|
||||
let mut node = rectangle(10, (0.0, 0.0), (50.0, 50.0));
|
||||
let recolor = F::Def(
|
||||
20,
|
||||
vec![tag(b"RcRA")],
|
||||
vec![
|
||||
(tag(b"Visi"), F::Bool(visible)),
|
||||
(tag(b"AdjP"), F::Obj(tag(b"RecP"), vec![(tag(b"RecH"), F::F64(0.0)), (tag(b"RecS"), F::F64(1.0)), (tag(b"RecL"), F::F64(lightness))])),
|
||||
],
|
||||
);
|
||||
if let F::Def(_, _, fields) = &mut node {
|
||||
fields.push((tag(b"AdCh"), F::Shared(vec![recolor])));
|
||||
}
|
||||
node
|
||||
}
|
||||
|
||||
fn first_fill(n: &Node) -> Paint {
|
||||
let Some(AppearanceItem::Fill(fill)) = n.appearance.items.first() else { panic!("no fill: {:?}", n.appearance) };
|
||||
fill.paint.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_af_g_symbol_fill_is_white() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af");
|
||||
let Ok(bytes) = std::fs::read(&path) else {
|
||||
return;
|
||||
};
|
||||
let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap();
|
||||
assert!(!loaded.preview_only, "{:?}", loaded.warnings);
|
||||
let d = &loaded.doc;
|
||||
// The visible "g41" group holds the "g" symbol (path43).
|
||||
let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present");
|
||||
let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present");
|
||||
let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else {
|
||||
panic!("path43 has no fill: {:?}", path43.appearance);
|
||||
};
|
||||
assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint);
|
||||
fn attached_recolor_adjustments_recolor_the_shape() {
|
||||
// Lightness 1 recolors to white.
|
||||
let loaded = open("recolor.af", &canvas_with(vec![recolored(true, 1.0)], None));
|
||||
assert!(!loaded.warnings.iter().any(|w| w.contains("attached to other layers")), "{:?}", loaded.warnings);
|
||||
let rect = named(&loaded.doc, "Magenta box");
|
||||
assert!(rect.appearance.effects.is_empty());
|
||||
assert_eq!(first_fill(rect), Paint::solid(Color::rgb(1.0, 1.0, 1.0)));
|
||||
// Lightness 0.5 at hue 0 and full saturation is pure red.
|
||||
let d = open("red.af", &canvas_with(vec![recolored(true, 0.5)], None)).doc;
|
||||
let [r, g, b, a] = pixel(&d, 25, 25);
|
||||
assert!(r > 250 && g < 5 && b < 5 && a == 255, "{:?}", [r, g, b, a]);
|
||||
// A hidden adjustment leaves the shape as it is.
|
||||
let d = open("hidden.af", &canvas_with(vec![recolored(false, 1.0)], None)).doc;
|
||||
assert_eq!(first_fill(named(&d, "Magenta box")), Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)));
|
||||
}
|
||||
@@ -64,8 +64,12 @@ fn type42_descendants_draw_their_own_glyphs() {
|
||||
}
|
||||
// The H, then the I one H's width along; both stand on the baseline, a cap height tall.
|
||||
let (bh, bi) = (bounds(paths[0]), bounds(paths[1]));
|
||||
assert!((bh.x0 - 10.0).abs() < 8.0 && bh.width() > 20.0 && bh.width() < 50.0 * wh, "{bh:?}");
|
||||
assert!((bh.height() - bi.height()).abs() < 0.5 && bh.height() > 25.0 && bh.height() < 40.0, "{bh:?} {bi:?}");
|
||||
// The bundled font's H spans (90, 0)–(562, 656) of its 1000-unit em: at 50 pt from x = 10 that
|
||||
// is 14.5 to 38.1, 32.8 tall.
|
||||
assert!((bh.x0 - 14.5).abs() < 0.01 && (bh.width() - 23.6).abs() < 0.01 && (bh.height() - 32.8).abs() < 0.01, "{bh:?}");
|
||||
// In the y-down document the baseline at y = 20 lands at 80, and the cap height 32.8 above it at 47.2.
|
||||
assert!((bh.y0 - 47.2).abs() < 0.01 && (bh.y1 - 80.0).abs() < 0.01, "{bh:?}");
|
||||
assert!((bh.height() - bi.height()).abs() < 0.5, "{bh:?} {bi:?}");
|
||||
assert!(bi.x0 > 10.0 + 50.0 * wh - 1.0 && bi.x1 < 10.0 + 50.0 * (wh + wi), "{bi:?}");
|
||||
}
|
||||
|
||||
@@ -78,8 +82,12 @@ fn type42_descendants_measure_space_and_outline_their_glyphs() {
|
||||
check(format!("(\\000\\001\\000\\002) stringwidth pop {} sub abs 0.01 lt", 50.0 * (wh + wi)));
|
||||
// xyshow places each character where its numbers say.
|
||||
check("gsave nulldevice 10 20 moveto (\\000\\001\\000\\002) [30 0 7 0] xyshow currentpoint grestore pop 47 sub abs 0.01 lt".into());
|
||||
// charpath outlines them.
|
||||
check("newpath 10 20 moveto (\\000\\001) true charpath pathbbox exch pop sub abs 25 gt exch 10 sub abs 8 lt and".into());
|
||||
// charpath outlines them: the H's box is (14.5, 20)–(38.1, 52.8).
|
||||
check(
|
||||
"newpath 10 20 moveto (\\000\\001) true charpath pathbbox 52.8 sub abs 0.01 lt exch 38.1 sub abs 0.01 lt and \
|
||||
exch 20 sub abs 0.01 lt and exch 14.5 sub abs 0.01 lt and"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
/// A descendant that is a font by name only (its program isn't run) sets its characters as type,
|
||||
|
||||
@@ -1382,7 +1382,12 @@ mod tests {
|
||||
"{n}: {b:?}"
|
||||
);
|
||||
let area = p.subpaths[0].area().abs();
|
||||
assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}");
|
||||
if n == 2 {
|
||||
// Two cubics with handles 4/3 of the half height long: each encloses 2/5 of the box.
|
||||
assert!((area - 0.8 * 100.0 * 60.0).abs() < 1e-8, "{n}: {area}");
|
||||
} else {
|
||||
assert!((area - PI * 50.0 * 30.0).abs() / area < 0.01, "{n}: {area}");
|
||||
}
|
||||
}
|
||||
// A box with no height leaves the path flat rather than dividing by zero.
|
||||
let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6);
|
||||
|
||||
@@ -624,11 +624,14 @@ fn math_functions_follow_the_special_cases() {
|
||||
fn math_random_is_seeded_from_the_os_random_source() {
|
||||
// On wasm32-unknown-unknown `RandomState`'s keys come from memory addresses, which are the
|
||||
// same on every page load: the seed must come from the OS (the browser's crypto) instead.
|
||||
let src = include_str!("interp.rs");
|
||||
let Some(start) = src.find("fn random_seed()") else { panic!("interp.rs has no random_seed") };
|
||||
let body = &src[start..];
|
||||
let body = &body[..body.find("\n}").unwrap_or(body.len())];
|
||||
assert!(body.contains("random_seed_from(getrandom::u64())"), "Math.random isn't seeded from the OS random source");
|
||||
// The OS value is the generator's only state: realms given the same value draw the same
|
||||
// numbers, and a different value draws different ones.
|
||||
let draws = |os: u64| match Realm::with_os_random(Ok(os)).run("[Math.random(), Math.random(), Math.random()].join()") {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert_eq!(draws(0x1234_5678_9abc_def0), draws(0x1234_5678_9abc_def0));
|
||||
assert_ne!(draws(0x1234_5678_9abc_def0), draws(0x0fed_cba9_8765_4321));
|
||||
// The OS value is the seed, made odd so it's never zero; a failed read still gives a seed.
|
||||
assert_eq!(crate::interp::random_seed_from(Ok(0x40)), 0x41);
|
||||
assert_eq!(crate::interp::random_seed_from(Ok(0)), 1);
|
||||
|
||||
@@ -1714,6 +1714,61 @@ fn a_function_body_reads_its_own_new_target() {
|
||||
truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined");
|
||||
}
|
||||
|
||||
/// Eval code that uses `super` or `new.target` where it may not is a `SyntaxError` before any of
|
||||
/// it runs, so `x = 1` ahead of the forbidden form leaves `x` at 0 (ECMA-262 2015 sections
|
||||
/// 18.2.1.1 and 15.1.1).
|
||||
#[test]
|
||||
fn eval_code_with_a_forbidden_super_or_new_target_runs_none_of_it() {
|
||||
let a = "class A { constructor(v) { this.a = v; } } ";
|
||||
let calls = [
|
||||
"eval('x = 1; super.y');".to_string(),
|
||||
"class C { m() { (0, eval)('x = 1; super.y'); } } new C().m();".to_string(),
|
||||
"function F() { eval('x = 1; super.y'); } F();".to_string(),
|
||||
"class C { m() { (function () { eval('x = 1; super.y'); })(); } } new C().m();".to_string(),
|
||||
"eval('x = 1; super()');".to_string(),
|
||||
"class C { constructor() { eval('x = 1; super()'); } } new C();".to_string(),
|
||||
format!("{a}class B extends A {{ m() {{ eval('x = 1; super(1)'); }} }} new B(1).m();"),
|
||||
format!("{a}class B extends A {{ constructor() {{ (0, eval)('x = 1; super(1)'); }} }} new B();"),
|
||||
format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('x = 1; super(1)'); }})(); }} }} new B();"),
|
||||
"function F() { eval('x = 1; super()'); } F();".to_string(),
|
||||
"eval('x = 1; new.target');".to_string(),
|
||||
"(() => eval('x = 1; new.target'))();".to_string(),
|
||||
"function F() { (0, eval)('x = 1; new.target'); } new F();".to_string(),
|
||||
];
|
||||
let ran: Vec<&String> = calls
|
||||
.iter()
|
||||
.filter(|call| {
|
||||
let src = format!("var x = 0, e; try {{ {call} }} catch (err) {{ e = err; }} x === 0 && e instanceof SyntaxError");
|
||||
run(&src) != JsValue::Bool(true)
|
||||
})
|
||||
.collect();
|
||||
assert!(ran.is_empty(), "eval code ran or did not throw a SyntaxError: {ran:#?}");
|
||||
}
|
||||
|
||||
/// The `Function` constructor throws the `SyntaxError` for `super` in the body or a parameter
|
||||
/// itself, so it returns no function to call and `x = 1` in the body never runs (ECMA-262 2015
|
||||
/// section 19.2.1.1.1).
|
||||
#[test]
|
||||
fn a_function_body_with_super_is_not_made() {
|
||||
let a = "class A { constructor(v) { this.a = v; } } ";
|
||||
let calls = [
|
||||
"class C { m() { f = Function('x = 1; super.y'); } } new C().m();".to_string(),
|
||||
"class C { m() { f = Function('a = super.y', 'x = 1'); } } new C().m();".to_string(),
|
||||
"f = Function('x = 1; super.y');".to_string(),
|
||||
format!("{a}class B extends A {{ constructor() {{ super(1); f = Function('x = 1; super(1)'); }} }} new B();"),
|
||||
"f = Function('x = 1; super()');".to_string(),
|
||||
];
|
||||
let made: Vec<&String> = calls
|
||||
.iter()
|
||||
.filter(|call| {
|
||||
let src =
|
||||
format!("var x = 0, f, e; try {{ {call} f(); }} catch (err) {{ e = err; }} f === undefined && x === 0 && e instanceof SyntaxError");
|
||||
run(&src) != JsValue::Bool(true)
|
||||
})
|
||||
.collect();
|
||||
assert!(made.is_empty(), "Function made a function or did not throw a SyntaxError: {made:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_class_chains_stay_within_the_limits() {
|
||||
let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();";
|
||||
|
||||
@@ -476,7 +476,7 @@ fn an_evaluator_with_site_is_told_where_it_is_called() {
|
||||
assert_eq!(given.len(), 2, "{given:?}");
|
||||
assert_eq!(given[0].len(), 4, "{given:?}");
|
||||
assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}");
|
||||
assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}");
|
||||
assert_eq!(given[0][2], Data::Number(3.0), "{given:?}");
|
||||
assert_eq!(given[1], vec![Data::String("y".into())]);
|
||||
}
|
||||
|
||||
@@ -615,7 +615,7 @@ fn an_error_says_where_in_the_source_it_was_raised() {
|
||||
r.start("var a = 1;\n throw new TypeError('no');").unwrap();
|
||||
let e = finish(&mut r, 1).0.unwrap_err();
|
||||
assert_eq!((e.kind, e.line), (RunErrorKind::Thrown, 2));
|
||||
assert!(e.column >= 3, "{}", e.column);
|
||||
assert_eq!(e.column, 3);
|
||||
assert_eq!(e.message, "TypeError: no");
|
||||
}
|
||||
|
||||
|
||||
+23
-1
@@ -544,7 +544,29 @@ fn index_names_bytes(len: usize, per_entry: usize) -> usize {
|
||||
/// random source (the browser's crypto on the web), or the standard library's randomly keyed
|
||||
/// hasher when that fails; never zero.
|
||||
fn random_seed() -> u64 {
|
||||
random_seed_from(getrandom::u64())
|
||||
random_seed_from(os_random())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// What the OS random source returns to realms made on this thread, when set.
|
||||
pub(crate) static TEST_OS_RANDOM: std::cell::Cell<Option<Result<u64, getrandom::Error>>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// The OS random source (in tests, what `TEST_OS_RANDOM` holds when set).
|
||||
fn os_random() -> Result<u64, getrandom::Error> {
|
||||
test_os_random().unwrap_or_else(getrandom::u64)
|
||||
}
|
||||
|
||||
/// What a test set in `TEST_OS_RANDOM`.
|
||||
#[cfg(test)]
|
||||
fn test_os_random() -> Option<Result<u64, getrandom::Error>> {
|
||||
TEST_OS_RANDOM.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn test_os_random() -> Option<Result<u64, getrandom::Error>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// [`random_seed`] from what the OS random source returned.
|
||||
|
||||
@@ -369,7 +369,7 @@ fn combinator_rejection_relays_keep_the_input_location() {
|
||||
let reported = r.unhandled_rejections();
|
||||
assert_eq!(reported.len(), 1, "{method}: {reported:?}");
|
||||
assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]);
|
||||
assert!(reported[0].column > 0);
|
||||
assert_eq!(reported[0].column, 3, "{method}: {:?}", reported[0]);
|
||||
assert_eq!(reported[0].tag, r.script_tag());
|
||||
}
|
||||
let mut r = realm();
|
||||
@@ -377,7 +377,7 @@ fn combinator_rejection_relays_keep_the_input_location() {
|
||||
.unwrap();
|
||||
assert_eq!(r.unhandled_rejections().len(), 1);
|
||||
assert_eq!(r.unhandled_rejections()[0].line, 3);
|
||||
assert!(r.unhandled_rejections()[0].column > 0);
|
||||
assert_eq!(r.unhandled_rejections()[0].column, 3);
|
||||
let mut r = realm();
|
||||
r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap();
|
||||
let reported = r.unhandled_rejections();
|
||||
|
||||
@@ -209,6 +209,17 @@ impl Realm {
|
||||
Self::with_options(Options::default(), Limits::default())
|
||||
}
|
||||
|
||||
/// A realm whose `Math.random` starts from the seed made of `os`, as if the OS random source
|
||||
/// had returned it. The realm is made by [`Realm::new`], so its seed comes through the same
|
||||
/// path as any other realm's.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_os_random(os: Result<u64, getrandom::Error>) -> Self {
|
||||
crate::interp::TEST_OS_RANDOM.with(|c| c.set(Some(os)));
|
||||
let realm = Self::new();
|
||||
crate::interp::TEST_OS_RANDOM.with(|c| c.set(None));
|
||||
realm
|
||||
}
|
||||
|
||||
/// A realm whose scripts (and the source given to `eval` and `Function`) are read with
|
||||
/// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it
|
||||
/// counted together.
|
||||
|
||||
@@ -113,7 +113,7 @@ fn explicit_empty_and_named_rdf_subjects_cannot_be_merged() {
|
||||
fn packet_padding_requires_an_actual_wrapper_trailer() {
|
||||
let packet = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description xmlns:a="urn:test"><a:value><![CDATA[ <?xpacket end=]]></a:value></rdf:Description></rdf:RDF>"#;
|
||||
assert_eq!(xmp::pad_size(packet), 0);
|
||||
assert!(xmp::pad_size(PACKET) > 0);
|
||||
assert_eq!(xmp::pad_size(PACKET), 1);
|
||||
let prefixed = format!("<?xml version=\"1.0\"?>\n<!-- prolog -->\n{PACKET}");
|
||||
assert_eq!(xmp::pad_size(&prefixed), xmp::pad_size(PACKET));
|
||||
assert_eq!(xmp::pad_size(&format!("<?xpacket-note example?>{PACKET}")), xmp::pad_size(PACKET));
|
||||
|
||||
@@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
|
||||
@@ -731,7 +731,8 @@ fn hatched_brushes_fill_with_their_average_color() {
|
||||
let p = paths(&back.document);
|
||||
assert_eq!(p.len(), 1);
|
||||
let [r, g, b] = fill_rgb(&p[0]).unwrap();
|
||||
assert!(b == 255 && r == g && r > 0 && r < 255, "{:?}", [r, g, b]);
|
||||
// The horizontal hatch covers one row in eight of its 8 × 8 tile: 8 blue and 56 white pixels.
|
||||
assert_eq!([r, g, b], [223, 223, 255]);
|
||||
// With a transparent background (SETBKMODE 1) the hatch is blue with gaps: a translucent fill.
|
||||
let mut records = records;
|
||||
records.insert(0, (18, le(&[1])));
|
||||
@@ -739,7 +740,8 @@ fn hatched_brushes_fill_with_their_average_color() {
|
||||
let p = paths(&back.document);
|
||||
assert_eq!(fill_rgb(&p[0]), Some([0, 0, 255]));
|
||||
let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") };
|
||||
assert!(f.opacity > 0.0 && f.opacity < 1.0, "{}", f.opacity);
|
||||
// One eighth of 255, truncated to 31.
|
||||
assert!((f.opacity - 31.0 / 255.0).abs() < 1e-6, "{}", f.opacity);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -59,7 +59,7 @@ pub fn interior_point(path: &PathData) -> Option<Point>;
|
||||
|
||||
Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` treats every path as an edge, open paths included. Three crossing lines enclose a triangle, a line across a rectangle splits it in two, and an area enclosed by paths becomes a face even when nothing fills it. Each face lists the inputs whose fill covers it; the list is empty for an area that is only enclosed by paths. Each edge is a piece of a path, split wherever another path meets it, and keeps the key of the front-most input it lies on.
|
||||
|
||||
`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas.
|
||||
`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. When the paths cross each other so often that the sweep cuts them into more than `SHAPE_BUILDER_MAX_MAP_EDGES` pieces, it skips the full map and returns only the regions of the filled areas, which are capped on their own: a filled shape apart from open paths that cross too often still has its region.
|
||||
|
||||
```rust
|
||||
pub struct Adjacency { pub faces: Vec<MapFace>, pub edges: Vec<MapEdge>, pub slivers: Vec<PathData>, pub outlines: Vec<MapOutline> }
|
||||
|
||||
@@ -33,8 +33,9 @@ pub use pathfinder::{
|
||||
FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within,
|
||||
};
|
||||
pub use planar::{
|
||||
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out,
|
||||
encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
|
||||
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS,
|
||||
adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder,
|
||||
shape_builder_with_gap,
|
||||
};
|
||||
pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within};
|
||||
pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band};
|
||||
|
||||
@@ -561,6 +561,16 @@ pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec<Region> {
|
||||
arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`regions_with`], or `None` when the sweep cuts the shapes into more than `max_edges` pieces
|
||||
/// (the faces are then not built).
|
||||
pub(crate) fn regions_capped(shapes: &[Shape], precision: f64, max_edges: usize) -> Option<Vec<Region>> {
|
||||
let Some(a) = arrangement(shapes, precision) else { return Some(Vec::new()) };
|
||||
if a.top.segment_indices().nth(max_edges).is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(regions_of(&a))
|
||||
}
|
||||
|
||||
/// [`regions`] when there are at most `limit` of them; `None` when there are more, found as soon
|
||||
/// as the face past `limit` is built (the faces after it are not built).
|
||||
pub fn regions_within(shapes: &[Shape], limit: usize) -> Option<Vec<Region>> {
|
||||
|
||||
@@ -41,8 +41,8 @@ pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps};
|
||||
pub use map::interior_point;
|
||||
pub(crate) use map::{Map, Rest, map};
|
||||
pub use shape_builder::{
|
||||
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, run_around, shape_builder,
|
||||
shape_builder_with_gap,
|
||||
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path,
|
||||
run_around, shape_builder, shape_builder_with_gap,
|
||||
};
|
||||
pub(crate) use shape_builder::{builder, gap_inputs};
|
||||
|
||||
|
||||
@@ -42,6 +42,11 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> {
|
||||
|
||||
/// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped.
|
||||
pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {
|
||||
map_within(shapes, cover, precision, usize::MAX)
|
||||
}
|
||||
|
||||
/// [`map_with`], or `None` when the sweep cuts the paths into more than `max_edges` pieces.
|
||||
pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Option<Map> {
|
||||
let mut inputs: Vec<(BezPath, usize)> = Vec::new();
|
||||
for (i, s) in shapes.iter().enumerate() {
|
||||
let mut bp = BezPath::new();
|
||||
@@ -69,7 +74,7 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<
|
||||
return None;
|
||||
}
|
||||
let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0));
|
||||
let (points, edges) = sweep_graph(&inputs, eps, precision)?;
|
||||
let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges)?;
|
||||
let nv = points.len();
|
||||
|
||||
// Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is
|
||||
@@ -188,11 +193,17 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<
|
||||
Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap })
|
||||
}
|
||||
|
||||
fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option<(Vec<Point>, Vec<Edge>)> {
|
||||
fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize) -> Option<(Vec<Point>, Vec<Edge>)> {
|
||||
// The sweep can panic on rare near-degenerate input; that must never take the app down.
|
||||
let sweep =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::<Crossings>::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps)));
|
||||
let top = sweep.ok()?.ok()?;
|
||||
// What is built from here on takes time and memory in proportion to the pieces the sweep cut
|
||||
// the paths into, and paths that cross many times are cut into far more pieces than they have
|
||||
// segments.
|
||||
if top.segment_indices().nth(max_edges).is_some() {
|
||||
return None;
|
||||
}
|
||||
// The planar graph: vertices are the sweep's points, edges its segments. Points closer than
|
||||
// the sweep's tolerance are one vertex (it can put a corner that lies on another path's edge
|
||||
// a rounding error away from where it cuts that edge).
|
||||
@@ -426,8 +437,9 @@ impl Map {
|
||||
/// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath)
|
||||
/// that lie under another path in front of them, whose edges are that path's: under a closed
|
||||
/// path's outline, or along an open path in front.
|
||||
/// `None` when the sweep cuts the paths into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces.
|
||||
pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec<Region>, Vec<Shape>, Vec<Shape>)> {
|
||||
let m = map_with(shapes, false, precision)?;
|
||||
let m = map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?;
|
||||
let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m;
|
||||
let snap = *snap;
|
||||
let fills: Vec<Fill> = shapes.iter().map(Fill::new).collect();
|
||||
|
||||
@@ -9,6 +9,16 @@ use super::*;
|
||||
/// can take on art far past what a drawing holds.
|
||||
pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536;
|
||||
|
||||
/// Most pieces the sweep may cut the Shape Builder's paths into, where they cross each other and
|
||||
/// where an open path is traced there and back: twice [`SHAPE_BUILDER_MAX_SEGMENTS`], what open
|
||||
/// paths that cross nothing make at that cap. Paths that cross many times make far more pieces
|
||||
/// than they have segments (400 circles stacked nearly on top of each other, 1,600 segments, make
|
||||
/// about 320,000), and the regions and edges built from them took minutes and gigabytes of memory.
|
||||
/// Past this the Shape Builder skips the full map and keeps only the regions of the filled areas,
|
||||
/// which are capped on their own: when the open paths alone cross too often, a filled shape apart
|
||||
/// from them still has its region.
|
||||
pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS;
|
||||
|
||||
/// The Shape Builder's arrangement: see [`shape_builder`].
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BuilderArrangement {
|
||||
@@ -40,7 +50,10 @@ pub fn has_open_path(shapes: &[Shape]) -> bool {
|
||||
/// nothing fills, and each path with no closed subpath comes back cut wherever another path meets
|
||||
/// it, as pieces keyed by its index in `shapes`. Outlines are cut the same way. With more than
|
||||
/// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or a map that can't be built, only the filled areas
|
||||
/// count and there are no pieces.
|
||||
/// count and there are no pieces. The same happens when the sweep cuts the paths into more than
|
||||
/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces; the filled areas are then capped on their own. They
|
||||
/// then have no regions when they alone are cut into more pieces than that, and a filled area
|
||||
/// thinner than the precision is dropped as a sliver, as in [`regions`](crate::regions).
|
||||
pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement {
|
||||
shape_builder_with_gap(shapes, edges, 0.0)
|
||||
}
|
||||
@@ -97,7 +110,7 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) -
|
||||
faces
|
||||
} else {
|
||||
// The filled areas from their arrangement, whose faces merge exactly, then the gaps.
|
||||
let mut regions = crate::pathfinder::regions_with(shapes, precision);
|
||||
let mut regions = crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default();
|
||||
regions.extend(faces.into_iter().filter(|f| f.sources.is_empty()));
|
||||
regions
|
||||
};
|
||||
@@ -112,14 +125,16 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) -
|
||||
/// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no
|
||||
/// area, such as cutting lines) is left out, so a flood of them cannot push the arrangement past its
|
||||
/// size budget and take the filled shapes down with it; the regions keep the original indices.
|
||||
/// There are none when the sweep cuts the filled shapes into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces.
|
||||
fn filled_regions(shapes: &[Shape], precision: f64) -> Vec<crate::Region> {
|
||||
let fills = |s: &Shape| s.path.subpaths.iter().any(|sp| sp.closed || encloses_area(sp));
|
||||
let keep: Vec<usize> = (0..shapes.len()).filter(|&i| shapes.get(i).is_some_and(fills)).collect();
|
||||
if keep.len() == shapes.len() {
|
||||
return crate::pathfinder::regions_with(shapes, precision);
|
||||
return crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default();
|
||||
}
|
||||
let kept: Vec<Shape> = keep.iter().filter_map(|&i| shapes.get(i).cloned()).collect();
|
||||
crate::pathfinder::regions_with(&kept, precision)
|
||||
crate::pathfinder::regions_capped(&kept, precision, SHAPE_BUILDER_MAX_MAP_EDGES)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|mut r| {
|
||||
r.sources = r.sources.iter().filter_map(|&s| keep.get(s).copied()).collect();
|
||||
|
||||
@@ -603,6 +603,49 @@ fn shape_builder_offers_the_gaps_closed_shapes_enclose() {
|
||||
assert!(shape_builder(&s, false).regions.iter().all(|r| !r.sources.is_empty()));
|
||||
}
|
||||
|
||||
/// `n` horizontal and `n` vertical lines across one square, every one crossing every other.
|
||||
fn line_grid(n: usize) -> Vec<Shape> {
|
||||
let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64;
|
||||
let across = (0..n).map(|k| line((0.0, at(k)), (1000.0, at(k)), k as u64));
|
||||
let down = (0..n).map(|k| line((at(k), 0.0), (at(k), 1000.0), (n + k) as u64));
|
||||
across.chain(down).collect()
|
||||
}
|
||||
|
||||
/// `n` horizontal and `n` vertical bars across one square, every one crossing every other.
|
||||
fn bar_grid(n: usize) -> Vec<Shape> {
|
||||
let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64;
|
||||
let across = (0..n).map(|k| rect(0.0, at(k), 1000.0, at(k) + 1.0, k as u64));
|
||||
let down = (0..n).map(|k| rect(at(k), 0.0, at(k) + 1.0, 1000.0, (n + k) as u64));
|
||||
across.chain(down).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_past_its_edge_cap_is_not_built() {
|
||||
// 20 lines each way: each line is cut into 21 pieces, 840 in all.
|
||||
let s = line_grid(20);
|
||||
assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_some());
|
||||
assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_none());
|
||||
let bars = bar_grid(20);
|
||||
assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 100_000).is_some_and(|r| r.len() > 400));
|
||||
assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 1000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_builds_no_regions_past_its_edge_cap() {
|
||||
// 300 lines each way cross 90,000 times with 600 segments: the sweep cuts them into about
|
||||
// 180,000 pieces, past the cap, and nothing is built from them.
|
||||
let s = line_grid(300);
|
||||
let started = work_done();
|
||||
let BuilderArrangement { regions, lines, edges, lines_under } = shape_builder(&s, true);
|
||||
assert!(regions.is_empty() && lines.is_empty() && edges.is_empty() && lines_under.is_empty(), "{} regions", regions.len());
|
||||
assert_eq!(work_done() - started, 0, "no face or edge was looked up");
|
||||
// Bars, closed paths only, each edge crossing 300 others: their filled areas are not built
|
||||
// either.
|
||||
assert!(shape_builder(&bar_grid(150), true).regions.is_empty());
|
||||
// Under the cap, the same grid is built.
|
||||
assert_eq!(shape_builder(&line_grid(20), false).regions.len(), 19 * 19);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_stays_quick_up_to_its_cap() {
|
||||
// A wavy ring of nearly the most segments the map takes, crossed by a few lines.
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! The exact output of every Pathfinder operation, pinned so that work on the windings and the
|
||||
//! coverage tests can't change it: overlapping ellipses, rectangles and stars (even-odd and
|
||||
//! non-zero, repeated keys for Merge) at a few counts.
|
||||
//! non-zero, repeated keys for Merge) at a few counts. The filled regions of Unite, Minus Front,
|
||||
//! Minus Back, Intersect and Exclude on the same inputs are also checked point by point against the
|
||||
//! inputs' own coverage, so the pins do not rest on the sweep that computed them alone.
|
||||
|
||||
use kurbo::{BezPath, Shape as _};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
use vectorcraft_pathops::{PathfinderOp, Shape, pathfinder};
|
||||
|
||||
@@ -78,6 +81,62 @@ fn every_pathfinder_operation_is_pinned() {
|
||||
assert_eq!(got, PINNED);
|
||||
}
|
||||
|
||||
/// Whether an operation's output covers a point, from which inputs cover it.
|
||||
type CoverRule = fn(&[bool]) -> bool;
|
||||
|
||||
/// Shapes as kurbo paths with their fill rules.
|
||||
type Filled = Vec<(BezPath, FillRule)>;
|
||||
|
||||
fn inside(path: &BezPath, rule: FillRule, p: kurbo::Point) -> bool {
|
||||
let w = path.winding(p);
|
||||
match rule {
|
||||
FillRule::NonZero => w != 0,
|
||||
FillRule::EvenOdd => w % 2 != 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pinned_inputs_fill_what_their_coverage_says() {
|
||||
use PathfinderOp::*;
|
||||
// Which inputs cover a point decides whether each operation's output covers it.
|
||||
let rules: [(PathfinderOp, CoverRule); 5] = [
|
||||
(Unite, |m| m.iter().any(|&c| c)),
|
||||
(MinusFront, |m| m[0] && !m[1..].iter().any(|&c| c)),
|
||||
(MinusBack, |m| m[m.len() - 1] && !m[..m.len() - 1].iter().any(|&c| c)),
|
||||
(Intersect, |m| m.iter().all(|&c| c)),
|
||||
(Exclude, |m| m.iter().filter(|&&c| c).count() % 2 == 1),
|
||||
];
|
||||
for (n, seed) in [(2, 3), (5, 7), (12, 11), (30, 13)] {
|
||||
let input = shapes_of(n, seed);
|
||||
let paths: Filled = input.iter().map(|s| (s.path.to_bezpath(), s.rule)).collect();
|
||||
let cover = |p: kurbo::Point| paths.iter().map(|(b, r)| inside(b, *r, p)).collect::<Vec<bool>>();
|
||||
let outputs: Vec<(PathfinderOp, CoverRule, Filled)> =
|
||||
rules.iter().map(|&(op, rule)| (op, rule, pathfinder(op, &input).iter().map(|s| (s.path.to_bezpath(), s.rule)).collect())).collect();
|
||||
let (mut checked, mut filled) = (0, 0);
|
||||
// A grid whose pitch shares no factor with the inputs' coordinates; points within 0.25 pt
|
||||
// of an input edge are skipped, since the output's edge may sit there within the precision.
|
||||
for i in 0..200 {
|
||||
for j in 0..160 {
|
||||
let p = kurbo::Point::new(-60.0 + f64::from(i) * 1.37, -60.0 + f64::from(j) * 1.37);
|
||||
let m = cover(p);
|
||||
let near_edge = [(0.25, 0.25), (-0.25, 0.25), (0.25, -0.25), (-0.25, -0.25)]
|
||||
.iter()
|
||||
.any(|&(dx, dy)| cover(kurbo::Point::new(p.x + dx, p.y + dy)) != m);
|
||||
if near_edge {
|
||||
continue;
|
||||
}
|
||||
checked += 1;
|
||||
for (op, rule, out) in &outputs {
|
||||
let got = out.iter().any(|(b, r)| inside(b, *r, p));
|
||||
assert_eq!(got, rule(&m), "{op:?} n={n} at {p:?}, covered by {m:?}");
|
||||
filled += usize::from(got);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked > 10_000 && filled > 1_000, "n={n}: {checked} points, {filled} filled");
|
||||
}
|
||||
}
|
||||
|
||||
/// Computed with the sweep of craft-libs 610c86792a, which places output curves closer to their
|
||||
/// inputs than the one before (craft-libs#721): every output keeps its shapes, subpaths and
|
||||
/// anchors, and its area and length agree with the earlier pins to 1e-6 relative.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! algorithm follows the compatibility ([`Encryption`]): 40-bit RC4 for PDF 1.3 (revision 2),
|
||||
//! 128-bit RC4 for PDF 1.4 (revision 3) and 1.5 (revision 4), 128-bit AES for 1.6 (revision 4) and
|
||||
//! 256-bit AES for 1.7 and 2.0 (revision 6). The random file key, salts and initialisation vectors
|
||||
//! come from a SHA-256 stream seeded with the process's random hash keys, the time and the file
|
||||
//! come from a SHA-256 stream seeded with the OS random source, the time and the file
|
||||
//! itself. A linearised file is encrypted between its two steps ([`protect_keeping`]): what
|
||||
//! encrypted it then encrypts the hint stream written last ([`Cipher`]).
|
||||
//!
|
||||
@@ -168,14 +168,49 @@ struct Entropy {
|
||||
counter: u64,
|
||||
}
|
||||
|
||||
/// What the OS random source returned, and the time.
|
||||
type SeedSources = (Result<[u8; 32], getrandom::Error>, i64);
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// What the OS random source and the clock return to [`Entropy::new`] on this thread, when set.
|
||||
pub(crate) static TEST_SEED_SOURCES: std::cell::Cell<Option<SeedSources>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// 32 bytes from the OS random source, and the time.
|
||||
fn seed_sources() -> SeedSources {
|
||||
test_seed_sources().unwrap_or_else(|| {
|
||||
let mut os = [0u8; 32];
|
||||
let os = getrandom::fill(&mut os).map(|()| os);
|
||||
(os, vectorcraft_doc::metadata::now_unix().unwrap_or_default())
|
||||
})
|
||||
}
|
||||
|
||||
/// What a test set in `TEST_SEED_SOURCES`.
|
||||
#[cfg(test)]
|
||||
fn test_seed_sources() -> Option<SeedSources> {
|
||||
TEST_SEED_SOURCES.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn test_seed_sources() -> Option<SeedSources> {
|
||||
None
|
||||
}
|
||||
|
||||
impl Entropy {
|
||||
/// Seeded from the OS random source, with the time and `material` mixed in.
|
||||
fn new(material: &[&[u8]]) -> Result<Self, PdfError> {
|
||||
let mut os = [0u8; 32];
|
||||
getrandom::fill(&mut os).map_err(|e| failed(&format!("no random numbers ({e})")))?;
|
||||
let (os, now) = seed_sources();
|
||||
Self::seeded(os, now, material)
|
||||
}
|
||||
|
||||
/// [`Entropy::new`] from what the OS random source returned and the time. Nothing else goes
|
||||
/// into the seed, and a failed OS read is an error.
|
||||
fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result<Self, PdfError> {
|
||||
let os = os.map_err(|e| failed(&format!("no random numbers ({e})")))?;
|
||||
let mut h = Sha256::new();
|
||||
h.update(os);
|
||||
h.update(vectorcraft_doc::metadata::now_unix().unwrap_or_default().to_le_bytes());
|
||||
h.update(now.to_le_bytes());
|
||||
for m in material {
|
||||
h.update((m.len() as u64).to_le_bytes());
|
||||
h.update(m);
|
||||
|
||||
@@ -90,12 +90,12 @@ pub use import_shading::function_evaluation_limit;
|
||||
pub use marks::{leaves_out_bleed, page_bleed, printer_marks};
|
||||
pub use output::ActiveProfiles;
|
||||
pub use page_widths::{FontWidths, PageWidths};
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
pub use pages::reads_of;
|
||||
pub use pages::{
|
||||
IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info,
|
||||
is_postscript, open_pdf, read_illustrator_data_without_pdf_part, read_illustrator_data_without_pdf_part_with,
|
||||
};
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
pub use pages::{read_mark, reads_of, reads_of_since};
|
||||
pub use piece_info::{PRIVATE_CHUNK, PrivateData};
|
||||
pub use post::{THUMBNAIL_SIZE, Thumbnail};
|
||||
pub use print::*;
|
||||
|
||||
+39
-5
@@ -368,14 +368,33 @@ pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: &
|
||||
})
|
||||
}
|
||||
|
||||
/// How many times each buffer has been read as a PDF, by its address (tests).
|
||||
/// The number the next read as a PDF gets, and every read of a buffer by the buffer's address with
|
||||
/// its number (tests). A freed buffer's reads stay under its address, so a later buffer at the same
|
||||
/// address starts with them: count from a [`read_mark`] taken before that buffer exists.
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
static READS: std::sync::Mutex<std::collections::BTreeMap<usize, usize>> = std::sync::Mutex::new(std::collections::BTreeMap::new());
|
||||
type Reads = (u64, std::collections::BTreeMap<usize, Vec<u64>>);
|
||||
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
static READS: std::sync::Mutex<Reads> = std::sync::Mutex::new((0, std::collections::BTreeMap::new()));
|
||||
|
||||
/// How many times `bytes`, at its address, has been read as a PDF on any thread (tests).
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
pub fn reads_of(bytes: &[u8]) -> usize {
|
||||
READS.lock().ok().and_then(|r| r.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0)
|
||||
READS.lock().ok().and_then(|r| r.1.get(&(bytes.as_ptr() as usize)).map(Vec::len)).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The number the next read as a PDF gets, for [`reads_of_since`] (tests).
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
pub fn read_mark() -> u64 {
|
||||
READS.lock().map(|r| r.0).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// How many times `bytes`, at its address, has been read as a PDF on any thread since `mark` was
|
||||
/// taken with [`read_mark`] (tests). Reads made before `mark`, such as reads of a freed buffer
|
||||
/// that had the same address, are not counted.
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
pub fn reads_of_since(bytes: &[u8], mark: u64) -> usize {
|
||||
READS.lock().ok().and_then(|r| r.1.get(&(bytes.as_ptr() as usize)).map(|reads| reads.iter().filter(|&&n| n >= mark).count())).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// [`open_with_options`] without looking at the file's objects ([`hostile`]): the reader builds its
|
||||
@@ -384,8 +403,9 @@ pub fn reads_of(bytes: &[u8]) -> usize {
|
||||
fn open_structural_with_options(bytes: &[u8], password: Option<&str>, options: &craft::pdf::OpenOptions) -> Result<Pdf, PdfError> {
|
||||
#[cfg(any(test, feature = "read-count"))]
|
||||
if let Ok(mut reads) = READS.lock() {
|
||||
let n = reads.entry(bytes.as_ptr() as usize).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
let n = reads.0;
|
||||
reads.0 = n.saturating_add(1);
|
||||
reads.1.entry(bytes.as_ptr() as usize).or_default().push(n);
|
||||
}
|
||||
if is_postscript(bytes) {
|
||||
return Err(PdfError::PostScript);
|
||||
@@ -763,4 +783,18 @@ mod tests {
|
||||
assert_eq!(super::decoded_size(1 << 30), "1 GB");
|
||||
assert_eq!(super::decoded_size((1 << 30) + (1 << 20)), "1025 MB");
|
||||
}
|
||||
|
||||
/// Reads made before a mark, as of a freed buffer whose address a new one takes, are not
|
||||
/// counted from that mark; reads after it are.
|
||||
#[test]
|
||||
fn reads_since_a_mark_leave_out_earlier_reads_at_the_same_address() {
|
||||
let bytes = b"not a pdf".to_vec();
|
||||
let start = super::read_mark();
|
||||
let _ = super::open_structural_with_options(&bytes, None, &super::open_options());
|
||||
let mark = super::read_mark();
|
||||
assert_eq!(super::reads_of_since(&bytes, start), 1, "the read from the start");
|
||||
assert_eq!(super::reads_of_since(&bytes, mark), 0, "the read before the mark");
|
||||
let _ = super::open_structural_with_options(&bytes, None, &super::open_options());
|
||||
assert_eq!(super::reads_of_since(&bytes, mark), 1, "the read after the mark");
|
||||
}
|
||||
}
|
||||
@@ -1034,6 +1034,19 @@ mod tests {
|
||||
assert!(unread.is_empty(), "{unread:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hex_string_broken_by_a_non_hex_byte_hides_no_stream_after_it() {
|
||||
// A `<` followed by hex digits and then a byte that is neither a hex digit nor white space
|
||||
// is no hex string: the scan goes on from the next byte instead of skipping to a `>`.
|
||||
let bad = b"<< /Type /XRef /DecodeParms 9 0 R >> stream\nx\nendstream";
|
||||
for lead in [&b"<4G "[..], b"<41 4z ", b"<\x00 "] {
|
||||
let pdf = [lead, &bad[..]].concat();
|
||||
assert!(unsafe_file_streams(&pdf), "{}", String::from_utf8_lossy(&pdf));
|
||||
}
|
||||
// A hex string that ends is skipped, and the stream after it is still read.
|
||||
assert!(unsafe_file_streams(&[&b"<41 42> "[..], &bad[..]].concat()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_of_lt_in_an_image_a_string_or_a_comment_opens() {
|
||||
// #3924 review: every `<<` in a run of `<` (an image's flat area of grey 60) was read as a
|
||||
|
||||
@@ -193,8 +193,26 @@ fn the_same_file_and_passwords_get_fresh_keys_each_time() {
|
||||
|
||||
#[test]
|
||||
fn the_file_key_is_seeded_from_the_os_random_source() {
|
||||
// `RandomState` is no CSPRNG and its keys are fixed on the web: the seed must come from the OS.
|
||||
let src = include_str!("../encrypt.rs");
|
||||
assert!(!src.contains("RandomState"), "encrypt.rs seeds its keys from RandomState");
|
||||
assert!(src.contains("getrandom::fill"), "encrypt.rs doesn't seed its keys from the OS random source");
|
||||
// The OS bytes, the time and the file are the whole seed: equal inputs give equal streams, so
|
||||
// no other source (such as `RandomState`, whose keys are fixed on the web) is mixed in, and
|
||||
// other OS bytes alone give another stream. The exports set what the OS and the clock return.
|
||||
use crate::encrypt::TEST_SEED_SOURCES;
|
||||
let mut opts = PdfOptions::default();
|
||||
opts.settings.compatibility = Compatibility::Pdf20;
|
||||
let plain = export(&doc(), &opts).unwrap();
|
||||
opts.settings.security = security("pw", "own");
|
||||
let protect_with = |os: Result<[u8; 32], getrandom::Error>| {
|
||||
TEST_SEED_SOURCES.with(|c| c.set(Some((os, 1_700_000_000))));
|
||||
let out = protect(plain.clone(), &opts.settings);
|
||||
TEST_SEED_SOURCES.with(|c| c.set(None));
|
||||
out
|
||||
};
|
||||
let dict = |os: [u8; 32]| match protect_with(Ok(os)) {
|
||||
Ok(bytes) => encrypt_dict(&bytes),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
};
|
||||
assert_eq!(dict([7; 32]), dict([7; 32]));
|
||||
assert_ne!(dict([7; 32]), dict([8; 32]));
|
||||
// A failed OS read is an error, not a weaker seed.
|
||||
assert!(protect_with(Err(getrandom::Error::UNSUPPORTED)).is_err());
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use kurbo::{Point, Rect, Shape};
|
||||
use vectorcraft_doc::{Document, FILE_FONT_MIME, TextObject};
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
use crate::tests::live_text::{SOURCE_SERIF, outlines, texts, uninstalled_serif};
|
||||
use crate::tests::live_text::{SOURCE_SERIF, outlines, renamed, texts, uninstalled_serif};
|
||||
use crate::*;
|
||||
|
||||
/// Lines of (x, y from the top, size, text): kerned pairs, a long line, two sizes.
|
||||
@@ -274,3 +274,29 @@ fn two_glyphs_for_one_character_both_survive_import() {
|
||||
};
|
||||
close(&glyph_ink(db, &imported), "imported");
|
||||
}
|
||||
|
||||
/// The license flags (OS/2 `fsType`) of the font a PDF carries go with the font the document keeps:
|
||||
/// a restricted font (0x0002) still draws its type, and a PDF saved from the document draws that
|
||||
/// type as outlines with the license warning instead of embedding the font again.
|
||||
#[test]
|
||||
fn a_restricted_font_the_file_carries_is_not_embedded_again() {
|
||||
let mut font = renamed(SOURCE_SERIF, &[("SourceSerif4", "SourceSerif7"), ("Source Serif 4", "Source Serif 7")]);
|
||||
let tables = usize::from(u16::from_be_bytes([font[4], font[5]]));
|
||||
let os2 = (0..tables).map(|i| 12 + 16 * i).find(|r| &font[*r..*r + 4] == b"OS/2").unwrap();
|
||||
let at = u32::from_be_bytes(font[os2 + 8..os2 + 12].try_into().unwrap()) as usize;
|
||||
font[at + 8..at + 10].copy_from_slice(&0x0002u16.to_be_bytes());
|
||||
|
||||
let carried = import(&page_pdf(font));
|
||||
let t = texts(&carried.document);
|
||||
assert!(t.iter().any(|t| t.file_fonts.is_some()), "the file's font draws its type");
|
||||
|
||||
let saved = export_with_report(&carried.document, &PdfOptions::default()).unwrap();
|
||||
assert!(saved.warnings.iter().any(|w| w.contains("Source Serif 7") && w.contains("doesn't allow embedding")), "{:?}", saved.warnings);
|
||||
let back = import(&saved.bytes);
|
||||
assert!(
|
||||
texts(&back.document).is_empty(),
|
||||
"no type in the saved file: {:?}",
|
||||
texts(&back.document).iter().map(TextObject::plain_text).collect::<Vec<_>>()
|
||||
);
|
||||
assert!(!back.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "no font in the saved file");
|
||||
}
|
||||
@@ -272,7 +272,8 @@ fn a_page_without_area_gets_the_size_viewers_give_it() {
|
||||
let bytes = pdf(&[PdfPage { media: [0.0, 0.0, 0.0, 0.0], ..PdfPage::new(0.0, 0.0, "") }], None);
|
||||
let i = info(&bytes, None).unwrap();
|
||||
let (w, h) = (i.pages[0].width, i.pages[0].height);
|
||||
assert!(w > 0.0 && h > 0.0);
|
||||
// US Letter, 8.5 × 11 in.
|
||||
assert_eq!((w, h), (612.0, 792.0));
|
||||
for crop in [CropTo::Crop, CropTo::Media, CropTo::Art] {
|
||||
let ab = open(&bytes, ImportOptions { crop, ..Default::default() }).artboards[0].rect;
|
||||
assert_eq!((ab.width(), ab.height()), (w, h), "{crop:?}");
|
||||
|
||||
@@ -271,7 +271,7 @@ fn invisible_text_is_type_whatever_its_glyphs_look_like() {
|
||||
}
|
||||
|
||||
/// `font` with each of `names` (`from`, `to`, the same length) replaced, in ASCII and UTF-16.
|
||||
fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec<u8> {
|
||||
pub(crate) fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec<u8> {
|
||||
let mut bytes = font.to_vec();
|
||||
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
for &(from, to) in names {
|
||||
|
||||
@@ -61,7 +61,13 @@ pub(crate) fn effect_bounds_with(
|
||||
/// reach of its own and its members' raster effects, measured as [`Node::visual_bounds_with`]
|
||||
/// measures art without effects: what Object › Rasterize makes its image over.
|
||||
pub fn drawn_bounds(doc: &Document, n: &Node) -> Option<Rect> {
|
||||
fx::painted_reach(&doc.symbol_boxes(), n)
|
||||
drawn_bounds_with(&doc.symbol_boxes(), n)
|
||||
}
|
||||
|
||||
/// [`drawn_bounds`] with symbol instances measured by their art in `symbols` (made with
|
||||
/// [`Document::symbol_boxes`]).
|
||||
pub fn drawn_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
fx::painted_reach(symbols, n)
|
||||
}
|
||||
|
||||
/// For a path or compound path whose own Rasterize effect is followed by Transform effects that
|
||||
|
||||
@@ -294,7 +294,9 @@ mod renderer;
|
||||
mod text_geom;
|
||||
mod threads;
|
||||
|
||||
pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage};
|
||||
pub use bounds::{
|
||||
drawn_bounds, drawn_bounds_with, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage,
|
||||
};
|
||||
pub use frame::FrameStats;
|
||||
use frame::{
|
||||
ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey,
|
||||
|
||||
+60
-11
@@ -19,7 +19,7 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) ->
|
||||
}
|
||||
// Closed endpoint rounding must not consume a substantial part of a subpixel band.
|
||||
let fine = (tol / 8.0).min(width / 32.0).max(1e-4);
|
||||
if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) {
|
||||
if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, &corners(line), st, width, fine)) {
|
||||
return band;
|
||||
}
|
||||
let outline = effects::stroke::line_outline(line, st, width, fine);
|
||||
@@ -49,21 +49,65 @@ fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option<BezPath> {
|
||||
lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines)
|
||||
}
|
||||
|
||||
/// The points where `line` has a corner: where two of its segments meet with tangents that are not
|
||||
/// in line ([`SMOOTH`]), or where a segment has no direction there. One list for each subpath, in
|
||||
/// order, each sorted by [`point_order`]. [`draw_sub`] leaves these points where they are, so the
|
||||
/// lines a curve is drawn with have each corner at the same point, and draws one subpath for each.
|
||||
fn corners(line: &BezPath) -> Vec<Vec<Point>> {
|
||||
let tangents = |seg: PathSeg| {
|
||||
let c = match seg {
|
||||
PathSeg::Line(l) => CubicBez::new(l.p0, l.p0, l.p1, l.p1),
|
||||
other => cubic(other)?,
|
||||
};
|
||||
Some((start_tangent(&c)?, end_tangent(&c)?))
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
// A span of `f64::INFINITY` gives every segment no steps: only the segments are wanted.
|
||||
for sub in subpaths(line.elements(), f64::INFINITY, 1.0).unwrap_or_default() {
|
||||
let mut here = Vec::new();
|
||||
let n = sub.segs.len();
|
||||
let first = if sub.closed { 0 } else { 1 };
|
||||
for i in first..n {
|
||||
let before = if i == 0 { n - 1 } else { i - 1 };
|
||||
let (Some((a, _)), Some((b, _))) = (sub.segs.get(before), sub.segs.get(i)) else { continue };
|
||||
let smooth = match (tangents(*a).map(|t| t.1), tangents(*b).map(|t| t.0)) {
|
||||
(Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(),
|
||||
_ => false,
|
||||
};
|
||||
if !smooth {
|
||||
here.push(b.start());
|
||||
}
|
||||
}
|
||||
here.sort_by(point_order);
|
||||
out.push(here);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Points in order of `x`, then `y` ([`corners`]).
|
||||
fn point_order(a: &Point, b: &Point) -> std::cmp::Ordering {
|
||||
a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))
|
||||
}
|
||||
|
||||
/// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill
|
||||
/// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet
|
||||
/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the
|
||||
/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as
|
||||
/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross. Elsewhere the
|
||||
/// stroke's join is drawn at the corners of the same subpath of the path (`corners`, one list for
|
||||
/// each subpath of `lines`, [`corners`]) and a round join where the lines a
|
||||
/// curve is drawn with meet. An open subpath ends in the stroke's caps, with round parts drawn as
|
||||
/// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a
|
||||
/// point that isn't finite, or is closed and no wider or taller than the stroke: those take
|
||||
/// [`effects::stroke::line_outline`].
|
||||
fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option<BezPath> {
|
||||
fn thin_band(lines: &BezPath, corners: &[Vec<Point>], st: &StrokeLayer, width: f64, fine: f64) -> Option<BezPath> {
|
||||
let h = width / 2.0;
|
||||
// The angle between two points of an arc of radius `h` drawn as lines within `fine` of it.
|
||||
let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3);
|
||||
let mut out = BezPath::new();
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
let mut closed = false;
|
||||
let flush = |pts: &mut Vec<Point>, closed: bool, out: &mut BezPath| -> Option<()> {
|
||||
// The subpath being read; `None` before the first move.
|
||||
let mut sub: Option<usize> = None;
|
||||
let flush = |pts: &mut Vec<Point>, closed: bool, sub: Option<usize>, out: &mut BezPath| -> Option<()> {
|
||||
if pts.is_empty() {
|
||||
return Some(());
|
||||
}
|
||||
@@ -80,14 +124,15 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
return None;
|
||||
}
|
||||
}
|
||||
band_sub(out, pts, closed, st, h, step);
|
||||
band_sub(out, pts, corners.get(sub?)?, closed, st, h, step);
|
||||
pts.clear();
|
||||
Some(())
|
||||
};
|
||||
for el in lines.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut pts, closed, &mut out)?;
|
||||
flush(&mut pts, closed, sub, &mut out)?;
|
||||
sub = Some(sub.map_or(0, |s| s + 1));
|
||||
closed = false;
|
||||
pts.push(p);
|
||||
}
|
||||
@@ -100,7 +145,7 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None,
|
||||
}
|
||||
}
|
||||
flush(&mut pts, closed, &mut out)?;
|
||||
flush(&mut pts, closed, sub, &mut out)?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -108,8 +153,9 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
/// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side,
|
||||
/// the end cap, its right side backward and the start cap; for a closed one its left side and its
|
||||
/// right side backward, as two contours. `h` is half the width and `step` the angle between the
|
||||
/// points of a round join or cap.
|
||||
fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) {
|
||||
/// points of a round join or cap. A sharp turn takes the stroke's join at one of this subpath's
|
||||
/// `corners` (sorted by [`point_order`]) and a round join elsewhere.
|
||||
fn band_sub(out: &mut BezPath, pts: &[Point], corners: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) {
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
let n = pts.len();
|
||||
let chords = if closed { n } else { n - 1 };
|
||||
@@ -143,7 +189,10 @@ fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h:
|
||||
inner.push(p);
|
||||
inner.push(p - nb * sign);
|
||||
outer.push(p + na * sign);
|
||||
match st.join {
|
||||
// Only the path's corners take the stroke's join; where the lines of a curve turn sharply
|
||||
// the stroke along the curve is round.
|
||||
let kind = if corners.binary_search_by(|c| point_order(c, &p)).is_ok() { st.join } else { LineJoin::Round };
|
||||
match kind {
|
||||
LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign),
|
||||
LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)),
|
||||
LineJoin::Miter | LineJoin::Bevel => {}
|
||||
|
||||
@@ -190,7 +190,8 @@ fn linear_gradient_goes_white_to_black() {
|
||||
assert!(r.pixel(2, 50)[0] > 240);
|
||||
assert!(r.pixel(97, 50)[0] < 15);
|
||||
let m = r.pixel(50, 50)[0] as i32;
|
||||
assert!((m - 128).abs() < 12, "{m}");
|
||||
// Pixel centre x = 50.5: 255 · (1 - 0.505) = 126.
|
||||
assert!((m - 126).abs() <= 2, "{m}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2455,8 +2455,8 @@ fn proof_previews_draw_changes_as_a_new_renderer_does() {
|
||||
}
|
||||
|
||||
/// A thumbnail of an object under a filter that treats color channels apart (Color Halftone) is
|
||||
/// made again when the document's color mode changes: CMYK documents screen ink channels, RGB
|
||||
/// documents light ones.
|
||||
/// made again when the document's color mode changes. RGB documents screen three ink planes.
|
||||
/// CMYK documents screen four ink planes.
|
||||
#[test]
|
||||
fn filtered_thumbnails_follow_the_color_mode() {
|
||||
let _fonts = fonts_steady();
|
||||
@@ -2464,9 +2464,9 @@ fn filtered_thumbnails_follow_the_color_mode() {
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
d.color_mode = vectorcraft_doc::ColorMode::Cmyk;
|
||||
let halftone = effect("pixelate.colorHalftone", serde_json::json!({"maxRadius": 4}));
|
||||
let orange = filled(&mut d, rectangle(Rect::new(20.0, 20.0, 180.0, 80.0)), Paint::solid(Color::rgb(1.0, 0.5, 0.0)), vec![halftone]);
|
||||
let id = orange.id;
|
||||
let mut d = with_art(d, vec![orange]);
|
||||
let gray = filled(&mut d, rectangle(Rect::new(20.0, 20.0, 180.0, 80.0)), Paint::solid(Color::rgb(0.5, 0.5, 0.5)), vec![halftone]);
|
||||
let id = gray.id;
|
||||
let mut d = with_art(d, vec![gray]);
|
||||
let mut r = Renderer::new();
|
||||
let before = r.render_thumbnail(&d, id, 128).unwrap().pixels;
|
||||
d.color_mode = vectorcraft_doc::ColorMode::Rgb;
|
||||
|
||||
@@ -133,6 +133,148 @@ fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() {
|
||||
assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}");
|
||||
}
|
||||
|
||||
/// A path with a bend at (10, 0) and then six smooth anchors `gap` apart, each with handles
|
||||
/// `handle` and 1.7 times `handle` long, scaled by `zoom`, and its points flattened within 0.001.
|
||||
fn close_smooth_anchors(gap: f64, handle: f64, zoom: f64) -> (BezPath, Vec<kurbo::Point>) {
|
||||
let path = close_smooth_path(gap, handle, zoom);
|
||||
let mut line = Vec::new();
|
||||
vectorcraft_geom::flatten(path.iter(), 1e-3, |el| {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el {
|
||||
line.push(p);
|
||||
}
|
||||
});
|
||||
(path, line)
|
||||
}
|
||||
|
||||
/// How far `q` is from the nearest point of `path`.
|
||||
fn from_curve(path: &BezPath, q: kurbo::Point) -> f64 {
|
||||
use kurbo::ParamCurveNearest;
|
||||
path.segments().map(|s| s.nearest(q, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// The path of [`close_smooth_anchors`].
|
||||
fn close_smooth_path(gap: f64, handle: f64, zoom: f64) -> BezPath {
|
||||
use vectorcraft_geom::path::{Anchor, AnchorKind, PathData, SubPath};
|
||||
let dir = kurbo::Vec2::new(0.8, 0.6);
|
||||
let mut anchors = vec![
|
||||
Anchor::corner(kurbo::Point::new(0.0, 0.0)),
|
||||
Anchor::with_handles(kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 5.0)),
|
||||
];
|
||||
let mut x = 10.0;
|
||||
for i in 0..6 {
|
||||
x += gap;
|
||||
let p = kurbo::Point::new(x, 1.0 + if i % 2 == 0 { 0.3 } else { -0.2 } * gap);
|
||||
anchors.push(Anchor { p, h_in: p - dir * handle, h_out: p + dir * handle * 1.7, kind: AnchorKind::Smooth });
|
||||
}
|
||||
anchors.push(Anchor::smooth(kurbo::Point::new(x + 20.0, 0.0), kurbo::Point::new(x + 25.0, -4.0)));
|
||||
kurbo::Affine::scale(zoom) * PathData::single(SubPath::new(anchors, false)).to_bezpath()
|
||||
}
|
||||
|
||||
/// A thin stroke along smooth anchors that sit close together after a bend follows the curve: its
|
||||
/// outline has no point farther than a stroke's width from the curve, and covers the curve. The
|
||||
/// lines such a curve is drawn with are short beside the stroke and turn sharply, so offsetting
|
||||
/// them drew the stroke's miter joins as spikes.
|
||||
#[test]
|
||||
fn thin_strokes_follow_smooth_anchors_close_together() {
|
||||
for gap in [0.1, 1.0] {
|
||||
let (path, line) = close_smooth_anchors(gap, 1.0, 1.0);
|
||||
for w in [0.6, 0.9] {
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&path, &st, w, 0.25);
|
||||
for el in o.elements() {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el {
|
||||
let d = from_curve(&path, p);
|
||||
assert!(d <= w, "gap {gap}, width {w}: outline point {p:?} is {d} from the curve");
|
||||
}
|
||||
}
|
||||
for p in line.iter().step_by(7) {
|
||||
assert!(o.winding(*p) != 0, "gap {gap}, width {w}: the curve at {p:?} is not covered");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin stroke's outline stays within the stroke's width of its curve where the lines the curve is
|
||||
/// drawn with turn sharply, as near a cusp: they meet with a round join, not the stroke's miter.
|
||||
/// 200 cubic curves, each about 100 device pixels across.
|
||||
#[test]
|
||||
fn thin_strokes_meet_round_where_a_curves_lines_turn_sharply() {
|
||||
let mut seed: u64 = 7;
|
||||
let mut r = |lo: f64, hi: f64| {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64)
|
||||
};
|
||||
let w = 0.5;
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
st.join = LineJoin::Miter;
|
||||
st.miter_limit = 10.0;
|
||||
for _ in 0..200 {
|
||||
let (x, y) = (r(20.0, 980.0), r(20.0, 980.0));
|
||||
let mut q = [kurbo::Point::ZERO; 3];
|
||||
for p in &mut q {
|
||||
*p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71);
|
||||
}
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((x * 1.71, y * 1.71));
|
||||
path.curve_to(q[0], q[1], q[2]);
|
||||
let o = raster_stroke_outline(&path, &st, w, 0.25);
|
||||
for el in o.elements() {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el {
|
||||
let d = from_curve(&path, p);
|
||||
assert!(d <= w, "outline point {p:?} is {d} from the curve {path:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin stroke along smooth anchors close together, with handles long beside the gaps between
|
||||
/// them, covers what the curve's own outline covers: at every point of a grid more than 0.25 pixels
|
||||
/// nearer or farther than half the stroke's width from the curve, both outlines agree. The miter
|
||||
/// joins drawn where the curve's lines turned sharply covered points well outside the stroke.
|
||||
#[test]
|
||||
fn thin_strokes_along_long_handles_cover_the_curve_outline() {
|
||||
let tol = 0.25;
|
||||
for (gap, w) in [(1.0, 0.6), (1.0, 0.9), (0.1, 0.6)] {
|
||||
let path = close_smooth_path(gap, 10.0, 4.0);
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&path, &st, w, tol);
|
||||
let fine = (tol / 8.0).min(w / 32.0);
|
||||
let mut want = BezPath::new();
|
||||
vectorcraft_geom::flatten(crate::effects::stroke::line_outline(&path, &st, w, fine).iter(), fine, |el| want.push(el));
|
||||
let bb = want.bounding_box().inflate(w, w);
|
||||
for i in 0..90 {
|
||||
for j in 0..90 {
|
||||
let q = kurbo::Point::new(bb.x0 + bb.width() * f64::from(i) / 90.0, bb.y0 + bb.height() * f64::from(j) / 90.0);
|
||||
let d = from_curve(&path, q);
|
||||
if (d - w / 2.0).abs() > 0.25 {
|
||||
assert_eq!(o.winding(q) != 0, want.winding(q) != 0, "gap {gap}, width {w}: at {q:?}, {d} from the curve");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A corner of one subpath does not change the join where the lines of another subpath's curve
|
||||
/// meet at the same point: the first subpath's outline is the same with or without the second.
|
||||
#[test]
|
||||
fn thin_strokes_take_corners_from_their_own_subpath() {
|
||||
let w = 0.5;
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
st.join = LineJoin::Miter;
|
||||
st.miter_limit = 10.0;
|
||||
let mut alone = BezPath::new();
|
||||
alone.move_to((-1.0, 0.0));
|
||||
alone.line_to((0.0, 0.0));
|
||||
alone.curve_to((0.000001, 0.0), (-1.0, 0.5), (-2.0, 1.0));
|
||||
let mut both = alone.clone();
|
||||
both.move_to((-10.0, -10.0));
|
||||
both.line_to((0.0, 0.0));
|
||||
both.line_to((-10.0, 10.0));
|
||||
let one = raster_stroke_outline(&alone, &st, w, 0.25);
|
||||
let two = raster_stroke_outline(&both, &st, w, 0.25);
|
||||
assert_eq!(two.elements().get(..one.elements().len()), Some(one.elements()), "the second subpath changed the first one's outline");
|
||||
}
|
||||
|
||||
/// Independently integrate coverage in radial/angle bins of an original notched ring. Checking
|
||||
/// only the outline geometry misses raster flattening that cancels its two nearby contours.
|
||||
#[test]
|
||||
|
||||
@@ -49,7 +49,8 @@ fn linear_gradient_left_to_right() {
|
||||
assert_rgb(&img, 1, 50, [255, 0, 0], 12);
|
||||
assert_rgb(&img, 98, 50, [0, 0, 255], 12);
|
||||
let mid = img.over_white(50, 50);
|
||||
assert!(mid[0].abs_diff(128) < 20 && mid[2].abs_diff(128) < 20 && mid[1] < 10, "mid {mid:?}");
|
||||
// Pixel centre x = 50.5: red 255 · 0.495 = 126, blue 255 · 0.505 = 129.
|
||||
assert!(mid[0].abs_diff(126) <= 2 && mid[2].abs_diff(129) <= 2 && mid[1] <= 2, "mid {mid:?}");
|
||||
// Red decreases monotonically along x; rows are identical (horizontal gradient).
|
||||
let reds: Vec<u8> = (0..100).step_by(5).map(|x| img.over_white(x, 50)[0]).collect();
|
||||
assert!(reds.windows(2).all(|w| w[1] <= w[0]), "{reds:?}");
|
||||
|
||||
@@ -84,6 +84,16 @@ fn a_patch_is_cut_no_finer_than_its_colour_changes() {
|
||||
let d = doc(2, 2, |_, c| Color::rgb8(100 + c as u8, 100 + c as u8, 100 + c as u8));
|
||||
let svg = export(&d, &ExportOptions::default());
|
||||
assert!(pieces(&svg) <= 4, "{} pieces", pieces(&svg));
|
||||
// Each piece takes its patch's middle color: 100.5 and 101.5 round to 101 and 102.
|
||||
let mut fills: Vec<&str> = svg.split("fill=\"").skip(1).filter_map(|s| s.split('"').next()).filter(|f| f.starts_with('#')).collect();
|
||||
fills.sort_unstable();
|
||||
fills.dedup();
|
||||
assert_eq!(fills, ["#656565", "#666666"], "{svg}");
|
||||
// The left column's pieces take 101 and the right column's 102, in both rows.
|
||||
let img = resvg_render(&svg);
|
||||
for (x, y, want) in [(60, 60, 101), (60, 140, 101), (140, 60, 102), (140, 140, 102)] {
|
||||
assert_eq!(&img.pixel(x, y)[..3], &[want; 3], "({x}, {y}) {svg}");
|
||||
}
|
||||
assert_looks_alike(&d, &svg, in_square, 2, 0.0);
|
||||
}
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ fn ruby_is_half_the_base_size_by_default_and_size_follows_the_span() {
|
||||
whole.ruby[0].size_percent = 100.0;
|
||||
let half = ruby_ink(&layout(db(), &half));
|
||||
let whole = ruby_ink(&layout(db(), &whole));
|
||||
assert!(half.height() < whole.height() * 0.75, "{} vs {}", half.height(), whole.height());
|
||||
assert!((half.height() / whole.height() - 0.5).abs() < 1e-6, "{} vs {}", half.height(), whole.height());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -536,21 +536,28 @@ fn the_menu_family_list_now_does_not_wait_for_the_scan() {
|
||||
db.scan_in_background();
|
||||
// The scan can't end until the pipe is opened for writing, so a list that waited for it would
|
||||
// hold the installed fonts. This thread lets the scan go on once the calls return, or after 10 s
|
||||
// if they are still waiting, so that such a test fails instead of hanging.
|
||||
// if they are still waiting, so that such a test fails instead of hanging. It opens the pipe
|
||||
// for reading and writing, which doesn't wait for a reader, and repeats that until the scan has
|
||||
// ended: a single open for writing waits for any reader and lets only the readers already
|
||||
// waiting go, so the test hung when the scan reached the pipe later, or ran on this thread
|
||||
// because its own thread didn't start.
|
||||
let (returned, waiting) = std::sync::mpsc::channel::<()>();
|
||||
let release = pipe.clone();
|
||||
let guard = std::thread::spawn(move || {
|
||||
let _ = waiting.recv_timeout(std::time::Duration::from_secs(10));
|
||||
// The pipe is opened and closed with nothing written.
|
||||
drop(std::fs::OpenOptions::new().write(true).open(&release).unwrap());
|
||||
while !db.installed_fonts_ready() {
|
||||
// The pipe is opened and closed with nothing written.
|
||||
drop(std::fs::OpenOptions::new().read(true).write(true).open(&release).unwrap());
|
||||
std::thread::yield_now();
|
||||
}
|
||||
});
|
||||
let ready = db.installed_fonts_ready();
|
||||
let listed = db.menu_family_list_now();
|
||||
drop(returned);
|
||||
guard.join().unwrap();
|
||||
assert!(!ready && !has(&listed, FAMILY), "before the scan ends, only the fonts already loaded");
|
||||
// Waits for the scan.
|
||||
assert!(has(&db.menu_family_list(), FAMILY));
|
||||
guard.join().unwrap();
|
||||
assert!(db.installed_fonts_ready());
|
||||
assert_ne!(db.generation(), generation, "a menu built from the short list is built again");
|
||||
assert!(has(&db.menu_family_list_now(), FAMILY));
|
||||
|
||||
@@ -562,8 +562,13 @@ fn caret_up_down_keeps_column() {
|
||||
let (top, _) = caret_position(&l, b);
|
||||
let down = caret_vertical(&l, b, 1, top.x);
|
||||
assert_eq!(l.line_of(down), 3);
|
||||
// The caret lands on the stop of line 3 nearest the column, not on a neighbor.
|
||||
let (t2, _) = caret_position(&l, down);
|
||||
assert!((t2.x - top.x).abs() < 12.0, "{} vs {}", t2.x, top.x);
|
||||
let nearest = (l.lines[3].start..=l.lines[3].end)
|
||||
.filter(|&i| COPY.is_char_boundary(i) && l.line_of(i) == 3)
|
||||
.map(|i| (caret_position(&l, i).0.x - top.x).abs())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
assert!(((t2.x - top.x).abs() - nearest).abs() < 1e-6, "{} vs {} (nearest stop {nearest} away)", t2.x, top.x);
|
||||
let up = caret_vertical(&l, down, -1, top.x);
|
||||
assert_eq!(up, b);
|
||||
assert_eq!(caret_vertical(&l, b, -10, top.x), 0);
|
||||
@@ -1267,34 +1272,32 @@ fn hyphenation_zone_breaks_before_the_word_with_the_single_line_composer() {
|
||||
assert_eq!(line_texts(&every, &layout(db(), &every)), without);
|
||||
}
|
||||
|
||||
/// The default Hyphenation options keep the line breaks of hyphenated text: the copy twice over
|
||||
/// at three widths, ragged and justified, with either composer. The constant is an FNV-1a hash of
|
||||
/// each line's end and whether it ends with a hyphen. It changed once since: justified lines
|
||||
/// follow the default Justification options (word spacing up to 133%, where the composer used
|
||||
/// to stretch spaces to 150%), and the every-line composer no longer gives up on loose lines.
|
||||
/// With the default Hyphenation options, ragged and justified, with either composer: "The
|
||||
/// language" in a frame that holds "The lan-" breaks as "The lan-" and "guage", only the first
|
||||
/// line ends with a hyphen. The 6-letter "garden" (longer than the default 5 letters) breaks the
|
||||
/// same way, as "The gar-" and "den".
|
||||
#[test]
|
||||
fn default_hyphenation_options_keep_the_line_breaks() {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
let mut mix = |v: u64| {
|
||||
for b in v.to_le_bytes() {
|
||||
hash = (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
let ends_with_hyphen = |l: &TextLayout| -> Vec<bool> {
|
||||
l.lines.iter().map(|li| li.glyph_end > li.glyph_start && l.glyphs.get(li.glyph_end - 1).is_some_and(|g| g.len == 0)).collect()
|
||||
};
|
||||
for width in [150.0, 190.0, 240.0] {
|
||||
for justify in [Justify::Left, Justify::JustifyLeft] {
|
||||
for composer in [Composer::SingleLine, Composer::EveryLine] {
|
||||
let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, width, 4000.0), justify);
|
||||
t.para.hyphenate = true;
|
||||
t.para.composer = composer;
|
||||
let l = layout(db(), &t);
|
||||
for li in &l.lines {
|
||||
let hyphenated = li.glyph_end > li.glyph_start && l.glyphs.get(li.glyph_end - 1).is_some_and(|g| g.len == 0);
|
||||
mix(li.end as u64 * 2 + u64::from(hyphenated));
|
||||
}
|
||||
}
|
||||
for justify in [Justify::Left, Justify::JustifyLeft] {
|
||||
for composer in [Composer::SingleLine, Composer::EveryLine] {
|
||||
let mut t = the_language("language", composer);
|
||||
t.para.justify = justify;
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(line_texts(&t, &l), ["The lan", "guage"], "{justify:?} {composer:?}");
|
||||
assert_eq!(ends_with_hyphen(&l), [true, false], "{justify:?} {composer:?}");
|
||||
let w = natural_width("The gar-", 12.0).max(natural_width("garden", 12.0)) + 1.0;
|
||||
assert!(w < natural_width("The garden", 12.0));
|
||||
let mut t = area("The garden", style(12.0), Rect::new(0.0, 0.0, w, 400.0), justify);
|
||||
t.para.hyphenate = true;
|
||||
t.para.composer = composer;
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(line_texts(&t, &l), ["The gar", "den"], "{justify:?} {composer:?}");
|
||||
assert_eq!(ends_with_hyphen(&l), [true, false], "{justify:?} {composer:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(hash, 4_188_642_633_634_327_633);
|
||||
}
|
||||
|
||||
/// The longest run of consecutive lines of `l` that end with a hyphen.
|
||||
|
||||
@@ -49,9 +49,10 @@ fn a_light_straight_in_front_casts_the_silhouette_behind_the_object() {
|
||||
for (got, want) in [(b.x0, 100.0), (b.y0, 100.0), (b.x1, 200.0), (b.y1, 200.0)] {
|
||||
assert!((got - want).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
// Every face of the box projects into the square, and the nonzero union fills it whole.
|
||||
// Every face of the box projects into the square, and the nonzero union fills it whole. Each
|
||||
// sample stands for 1 pt² and none lies on the square's edge, so the count is exact.
|
||||
let area = covered(&path, Rect::new(90.0, 90.0, 210.0, 210.0), 120);
|
||||
assert!((area - 10_000.0).abs() < 300.0, "{area}");
|
||||
assert_eq!(area, 10_000.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -899,7 +899,7 @@ fn a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none() {
|
||||
assert_eq!(got, id);
|
||||
// The arc of a 10 pt radius at a 120° corner spans 10 pt between its ends.
|
||||
let (wide, high) = (b[2] - b[0], b[3] - b[1]);
|
||||
assert!(wide.max(high) <= 10.5 && wide.max(high) > 5.0, "{b:?}");
|
||||
assert!((wide.max(high) - 10.0).abs() < 1e-6, "{b:?}");
|
||||
let centre = Point::new((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0);
|
||||
assert!(centre.distance(at) < 15.0, "{b:?} {at:?}");
|
||||
// Sheared by 30°: the rectangle's 120° corners (1 and 3) hide above 100°.
|
||||
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user