mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 19:04:25 +01:00
Merge main into feat/palette-use-counts
This commit is contained in:
commit
c0b1eb8599
146 files changed
+9327
-1007
No files matched your search
Generated
+20
@@ -1203,6 +1203,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -1214,6 +1224,14 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9101c4fc226f5f111b5a890a6c5c19bf3991fd76#9101c4fc226f5f111b5a890a6c5c19bf3991fd76"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
@@ -6710,6 +6728,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-dxf",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-plotter",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"serde_json",
|
||||
@@ -7098,6 +7117,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-mime",
|
||||
"craft-svg",
|
||||
"data-url",
|
||||
"flate2",
|
||||
|
||||
@@ -28,9 +28,11 @@ craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "431f704478962677ec47e512754464d372901830", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "9101c4fc226f5f111b5a890a6c5c19bf3991fd76" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
|
||||
@@ -137,6 +137,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-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.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::portal_save;
|
||||
#[cfg(windows)]
|
||||
use super::windows_screen_color;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
|
||||
@@ -354,7 +356,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
@@ -413,6 +415,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
|
||||
#[cfg(windows)]
|
||||
screen_color: Some(windows_screen_color::sampler(sampled_ui)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
|
||||
@@ -77,6 +77,7 @@ mod window_frame;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
mod windows_screen_color;
|
||||
mod windows_stylus;
|
||||
mod xwayland;
|
||||
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system
|
||||
//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all
|
||||
//! the monitors (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics>),
|
||||
//! into a bitmap with `BitBlt` from the screen's device context
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc>), then covers
|
||||
//! the virtual screen with a borderless topmost window that shows that copy under a crosshair
|
||||
//! cursor. The window has its own message loop on that thread, so the UI keeps drawing.
|
||||
//!
|
||||
//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other
|
||||
//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer
|
||||
//! `None`. Each
|
||||
//! click is answered when its button is released, so the release does not reach the window
|
||||
//! underneath. The color comes from the copy taken before the window was shown, so the window
|
||||
//! never samples itself, and moving content shows the frame it had when the copy was taken.
|
||||
//!
|
||||
//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display
|
||||
//! does not use Advanced Color
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles>). The colors
|
||||
//! of HDR and wide-gamut displays are not converted.
|
||||
//!
|
||||
//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy
|
||||
//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the
|
||||
//! main one has negative coordinates
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows>).
|
||||
//!
|
||||
//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
/// The status message for every failure; the details go to the log.
|
||||
const FAILED: &str = "the screen color sampler failed";
|
||||
|
||||
/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320
|
||||
/// monitors. VectorCraft's own limit.
|
||||
const MAX_SNAPSHOT_BYTES: u64 = 1 << 30;
|
||||
|
||||
/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read.
|
||||
const CLR_INVALID: u32 = 0xFFFF_FFFF;
|
||||
|
||||
/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of
|
||||
/// or above the main one) and its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct VirtualScreen {
|
||||
left: i32,
|
||||
top: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
impl VirtualScreen {
|
||||
/// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its
|
||||
/// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the
|
||||
/// coordinates Windows can address.
|
||||
fn new(left: i32, top: i32, width: i32, height: i32) -> Result<Self, String> {
|
||||
if width <= 0 || height <= 0 {
|
||||
return Err(format!("the virtual screen is {width} × {height} pixels"));
|
||||
}
|
||||
let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4);
|
||||
if bytes > MAX_SNAPSHOT_BYTES {
|
||||
return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit"));
|
||||
}
|
||||
if left.checked_add(width).is_none() || top.checked_add(height).is_none() {
|
||||
return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range"));
|
||||
}
|
||||
Ok(Self { left, top, width, height })
|
||||
}
|
||||
|
||||
/// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the
|
||||
/// virtual screen.
|
||||
fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> {
|
||||
let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?);
|
||||
((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py))
|
||||
}
|
||||
}
|
||||
|
||||
/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any
|
||||
/// other value with its high byte set.
|
||||
fn srgb(colorref: u32) -> Option<[f32; 3]> {
|
||||
if colorref == CLR_INVALID {
|
||||
return None;
|
||||
}
|
||||
let [r, g, b, high] = colorref.to_le_bytes();
|
||||
(high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0))
|
||||
}
|
||||
|
||||
/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit
|
||||
/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup>), so a coordinate past
|
||||
/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value
|
||||
/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg>) in client
|
||||
/// coordinates.
|
||||
fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) {
|
||||
let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16));
|
||||
(widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1))
|
||||
}
|
||||
|
||||
/// A mouse button: the left one picks, and any other one cancels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Button {
|
||||
Left,
|
||||
Right,
|
||||
/// The middle button or a side button.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What the person did in the sampler's window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Input {
|
||||
Down(Button),
|
||||
Up(Button),
|
||||
Escape,
|
||||
/// The window became the active window.
|
||||
Activated,
|
||||
/// The window stopped being the active window.
|
||||
Deactivated,
|
||||
/// Another window took the mouse capture.
|
||||
CaptureLost,
|
||||
/// The window was asked to close (Alt+F4).
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// What the sampler does next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Step {
|
||||
Wait,
|
||||
Pick,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// The mouse button last pressed in the window, and whether the window has been active.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Press {
|
||||
down: Option<Button>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Press {
|
||||
/// A release picks or cancels only after its button went down in the window. Losing the focus
|
||||
/// cancels only after the window had it, so a window that never became active still takes a
|
||||
/// click.
|
||||
fn step(&mut self, input: Input) -> Step {
|
||||
match input {
|
||||
Input::Down(button) => {
|
||||
self.down = Some(button);
|
||||
Step::Wait
|
||||
}
|
||||
Input::Up(button) if self.down == Some(button) => {
|
||||
if button == Button::Left {
|
||||
Step::Pick
|
||||
} else {
|
||||
Step::Cancel
|
||||
}
|
||||
}
|
||||
Input::Up(_) => Step::Wait,
|
||||
Input::Activated => {
|
||||
self.active = true;
|
||||
Step::Wait
|
||||
}
|
||||
Input::Deactivated if !self.active => Step::Wait,
|
||||
Input::Escape | Input::Deactivated | Input::CaptureLost | Input::Closed => Step::Cancel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The screen color sampler; `ui` is woken when it answers.
|
||||
#[cfg(windows)]
|
||||
pub fn sampler(ui: egui::Context) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ui = ui.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
let answer = overlay::run().map_err(|detail| {
|
||||
log::warn!("the screen color sampler gave no color: {detail}");
|
||||
FAILED.to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
FAILED.to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
/// The copy of the virtual screen and the window that shows it, on the sampler's thread.
|
||||
#[cfg(windows)]
|
||||
mod overlay {
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
BeginPaint, BitBlt, CAPTUREBLT, ClientToScreen, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, EndPaint, GetDC,
|
||||
GetPixel, HBITMAP, HDC, HGDIOBJ, PAINTSTRUCT, ReleaseDC, SRCCOPY, SelectObject,
|
||||
};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics, HCURSOR, IDC_CROSS,
|
||||
LoadCursorW, MSG, PostQuitMessage, RegisterClassExW, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_SHOW,
|
||||
SetCursor, SetForegroundWindow, ShowWindow, TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,
|
||||
WM_DPICHANGED, WM_ERASEBKGND, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_PAINT, WM_RBUTTONDOWN,
|
||||
WM_RBUTTONUP, WM_SETCURSOR, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
|
||||
};
|
||||
use windows::core::{PCWSTR, w};
|
||||
|
||||
use super::{Button, Input, Press, Step, VirtualScreen, message_point, srgb};
|
||||
|
||||
/// The window class of the sampler's window.
|
||||
const CLASS: PCWSTR = w!("VectorCraftScreenColor");
|
||||
|
||||
/// The picked color, `None` when canceled, or the details of a failure.
|
||||
type Picked = Result<Option<[f32; 3]>, String>;
|
||||
|
||||
/// A copy of the virtual screen in a memory device context. Dropping it frees the bitmap and
|
||||
/// the device context.
|
||||
struct Snapshot {
|
||||
dc: HDC,
|
||||
bitmap: HBITMAP,
|
||||
/// The bitmap the device context held before [`Snapshot::bitmap`] replaced it.
|
||||
old: HGDIOBJ,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Copies `screen` from the screen's device context, which is released on this thread, as
|
||||
/// `ReleaseDC` requires.
|
||||
fn take(screen: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `GetDC(None)` takes no pointers; the device context is released below.
|
||||
let screen_dc = unsafe { GetDC(None) };
|
||||
if screen_dc.is_invalid() {
|
||||
return Err("GetDC(NULL) gave no device context".into());
|
||||
}
|
||||
let copied = Self::copy(screen_dc, screen);
|
||||
// SAFETY: the device context `GetDC(None)` gave on this thread, released once.
|
||||
unsafe { ReleaseDC(None, screen_dc) };
|
||||
copied
|
||||
}
|
||||
|
||||
fn copy(screen_dc: HDC, s: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `screen_dc` is a live device context; a failure answers a null handle.
|
||||
let dc = unsafe { CreateCompatibleDC(Some(screen_dc)) };
|
||||
if dc.is_invalid() {
|
||||
return Err("CreateCompatibleDC failed".into());
|
||||
}
|
||||
// SAFETY: as above; the size was checked by `VirtualScreen::new`.
|
||||
let bitmap = unsafe { CreateCompatibleBitmap(screen_dc, s.width, s.height) };
|
||||
if bitmap.is_invalid() {
|
||||
// SAFETY: the device context made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err(format!("CreateCompatibleBitmap gave no {} × {} bitmap", s.width, s.height));
|
||||
}
|
||||
// SAFETY: both handles are live and made above.
|
||||
let old = unsafe { SelectObject(dc, bitmap.into()) };
|
||||
if old.is_invalid() {
|
||||
// SAFETY: the handles made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteObject(bitmap.into());
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err("SelectObject failed".into());
|
||||
}
|
||||
let snapshot = Self { dc, bitmap, old };
|
||||
// SAFETY: both device contexts are live; the rectangle is the virtual screen.
|
||||
unsafe { BitBlt(dc, 0, 0, s.width, s.height, Some(screen_dc), s.left, s.top, SRCCOPY | CAPTUREBLT) }
|
||||
.map_err(|e| format!("BitBlt of the virtual screen failed: {e}"))?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// The `COLORREF` of the copy's pixel (`x`, `y`).
|
||||
fn colorref(&self, x: i32, y: i32) -> u32 {
|
||||
// SAFETY: the device context is live while `self` is; GetPixel checks the coordinates.
|
||||
unsafe { GetPixel(self.dc, x, y) }.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Snapshot {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the handles `copy` made, freed once, the bitmap after the device context
|
||||
// lets go of it.
|
||||
unsafe {
|
||||
SelectObject(self.dc, self.old);
|
||||
let _ = DeleteObject(self.bitmap.into());
|
||||
let _ = DeleteDC(self.dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sampler shown on this thread.
|
||||
struct Session {
|
||||
snapshot: Snapshot,
|
||||
screen: VirtualScreen,
|
||||
cursor: HCURSOR,
|
||||
press: Press,
|
||||
/// The pointer position, in screen coordinates, of the message being dispatched (`MSG.pt`).
|
||||
message_pt: Option<POINT>,
|
||||
/// The answer, set once.
|
||||
answer: Option<Picked>,
|
||||
/// The window has been destroyed.
|
||||
destroyed: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` on this thread's session, or answers `None` when there is none or it is in use.
|
||||
/// Win32 calls that send messages to the window (which come back to [`window_proc`]) are made
|
||||
/// outside it.
|
||||
fn with<R>(f: impl FnOnce(&mut Session) -> R) -> Option<R> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok()?.as_mut().map(f))
|
||||
}
|
||||
|
||||
fn put(session: Option<Session>) -> Option<Session> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok().map(|mut s| std::mem::replace(&mut *s, session)))?
|
||||
}
|
||||
|
||||
/// Shows the sampler and waits for the person; answers on this thread.
|
||||
pub(super) fn run() -> Picked {
|
||||
// SAFETY: `GetSystemMetrics` takes no pointers.
|
||||
let (left, top, width, height) = unsafe {
|
||||
(
|
||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
)
|
||||
};
|
||||
let screen = VirtualScreen::new(left, top, width, height)?;
|
||||
let snapshot = Snapshot::take(screen)?;
|
||||
register()?;
|
||||
// SAFETY: a system cursor, loaded by its id.
|
||||
let cursor = unsafe { LoadCursorW(None, IDC_CROSS) }.map_err(|e| format!("LoadCursorW: {e}"))?;
|
||||
// Each sampler runs on a thread of its own, so the thread has no session yet.
|
||||
let _ = put(Some(Session { snapshot, screen, cursor, press: Press::default(), message_pt: None, answer: None, destroyed: false }));
|
||||
let shown = show(screen, cursor);
|
||||
if let Ok(hwnd) = shown {
|
||||
pump();
|
||||
if with(|s| s.destroyed) == Some(false) {
|
||||
// SAFETY: the window made by `show` on this thread, not yet destroyed.
|
||||
let _ = unsafe { DestroyWindow(hwnd) };
|
||||
}
|
||||
}
|
||||
let session = put(None);
|
||||
shown?;
|
||||
session.and_then(|s| s.answer).unwrap_or(Ok(None))
|
||||
}
|
||||
|
||||
/// Registers the window class once for the process.
|
||||
fn register() -> Result<(), String> {
|
||||
static REGISTERED: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
REGISTERED
|
||||
.get_or_init(|| {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
let class = WNDCLASSEXW {
|
||||
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
hInstance: instance.into(),
|
||||
lpszClassName: CLASS,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `class` is a complete `WNDCLASSEXW` whose strings are static.
|
||||
if unsafe { RegisterClassExW(&class) } == 0 {
|
||||
return Err(format!("RegisterClassExW: {}", windows::core::Error::from_thread()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Shows the window over the virtual screen in front of every other window and takes the mouse.
|
||||
fn show(s: VirtualScreen, cursor: HCURSOR) -> Result<HWND, String> {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
// SAFETY: the class was registered by `register`; the strings are static.
|
||||
let hwnd = unsafe {
|
||||
CreateWindowExW(
|
||||
WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
|
||||
CLASS,
|
||||
w!("Sample Color from Screen"),
|
||||
WS_POPUP,
|
||||
s.left,
|
||||
s.top,
|
||||
s.width,
|
||||
s.height,
|
||||
None,
|
||||
None,
|
||||
Some(instance.into()),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.map_err(|e| format!("CreateWindowExW: {e}"))?;
|
||||
// SAFETY: the window made above, on this thread.
|
||||
unsafe {
|
||||
let _ = ShowWindow(hwnd, SW_SHOW);
|
||||
let _ = SetForegroundWindow(hwnd);
|
||||
SetCapture(hwnd);
|
||||
SetCursor(Some(cursor));
|
||||
}
|
||||
Ok(hwnd)
|
||||
}
|
||||
|
||||
/// The window's message loop, until the window is destroyed.
|
||||
fn pump() {
|
||||
let mut msg = MSG::default();
|
||||
// SAFETY: `msg` is a valid `MSG` for each call. `GetMessageW` answers 0 for `WM_QUIT` and -1
|
||||
// for an error; both end the loop.
|
||||
while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
|
||||
with(|s| s.message_pt = Some(msg.pt));
|
||||
// SAFETY: the message `GetMessageW` just filled in.
|
||||
unsafe {
|
||||
let _ = TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers once, then lets go of the mouse and destroys the window.
|
||||
fn finish(hwnd: HWND, answer: impl FnOnce(&mut Session) -> Picked) {
|
||||
let first = with(|s| {
|
||||
let first = s.answer.is_none();
|
||||
if first {
|
||||
s.answer = Some(answer(s));
|
||||
}
|
||||
first
|
||||
});
|
||||
if first == Some(true) {
|
||||
// SAFETY: the window on this thread; both calls send messages that `window_proc`
|
||||
// handles outside the session.
|
||||
unsafe {
|
||||
let _ = ReleaseCapture();
|
||||
let _ = DestroyWindow(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy's color at the point where the left button was released: `lparam` of that
|
||||
/// `WM_LBUTTONUP`, in `hwnd`'s client coordinates, not where the pointer is now. The pointer's
|
||||
/// current position stands in for `MSG.pt` only when the release was not dispatched by
|
||||
/// [`pump`].
|
||||
fn pick(s: &mut Session, hwnd: HWND, lparam: LPARAM) -> Picked {
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread and a valid `POINT`; the call sends no message.
|
||||
unsafe { ClientToScreen(hwnd, &mut origin) }.ok().map_err(|e| format!("ClientToScreen: {e}"))?;
|
||||
let pt = match s.message_pt {
|
||||
Some(pt) => pt,
|
||||
None => {
|
||||
let mut now = POINT::default();
|
||||
// SAFETY: `now` is a valid `POINT`.
|
||||
unsafe { GetCursorPos(&mut now) }.map_err(|e| format!("GetCursorPos: {e}"))?;
|
||||
now
|
||||
}
|
||||
};
|
||||
let near = (pt.x.wrapping_sub(origin.x), pt.y.wrapping_sub(origin.y));
|
||||
let (cx, cy) = message_point(lparam.0, near);
|
||||
let at = POINT { x: cx.saturating_add(origin.x), y: cy.saturating_add(origin.y) };
|
||||
let (x, y) = s.screen.pixel(at.x, at.y).ok_or_else(|| format!("the release at ({}, {}) is outside the virtual screen", at.x, at.y))?;
|
||||
let colorref = s.snapshot.colorref(x, y);
|
||||
srgb(colorref).map(Some).ok_or_else(|| format!("GetPixel({x}, {y}) answered {colorref:#010x}"))
|
||||
}
|
||||
|
||||
/// Draws the copy where the virtual screen is, wherever the window's client area is.
|
||||
fn paint(hwnd: HWND) {
|
||||
let copy = with(|s| (s.snapshot.dc, s.screen));
|
||||
let mut ps = PAINTSTRUCT::default();
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread, with a `PAINTSTRUCT` for `BeginPaint` and `EndPaint`;
|
||||
// the copy's device context lives as long as the session.
|
||||
unsafe {
|
||||
let _ = ClientToScreen(hwnd, &mut origin);
|
||||
let target = BeginPaint(hwnd, &mut ps);
|
||||
if let Some((dc, s)) = copy
|
||||
&& !target.is_invalid()
|
||||
{
|
||||
let _ = BitBlt(target, s.left.saturating_sub(origin.x), s.top.saturating_sub(origin.y), s.width, s.height, Some(dc), 0, 0, SRCCOPY);
|
||||
}
|
||||
let _ = EndPaint(hwnd, &ps);
|
||||
}
|
||||
}
|
||||
|
||||
/// What `msg` means for the sampler.
|
||||
fn input(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> Option<Input> {
|
||||
match msg {
|
||||
WM_LBUTTONDOWN => Some(Input::Down(Button::Left)),
|
||||
WM_LBUTTONUP => Some(Input::Up(Button::Left)),
|
||||
WM_RBUTTONDOWN => Some(Input::Down(Button::Right)),
|
||||
WM_RBUTTONUP => Some(Input::Up(Button::Right)),
|
||||
WM_MBUTTONDOWN | WM_XBUTTONDOWN => Some(Input::Down(Button::Other)),
|
||||
WM_MBUTTONUP | WM_XBUTTONUP => Some(Input::Up(Button::Other)),
|
||||
WM_KEYDOWN if wparam.0 == usize::from(VK_ESCAPE.0) => Some(Input::Escape),
|
||||
WM_ACTIVATE if wparam.0 & 0xFFFF == WA_INACTIVE as usize => Some(Input::Deactivated),
|
||||
WM_ACTIVATE => Some(Input::Activated),
|
||||
// `lParam` is the window that takes the capture.
|
||||
WM_CAPTURECHANGED if lparam.0 != hwnd.0 as isize => Some(Input::CaptureLost),
|
||||
WM_CLOSE => Some(Input::Closed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
// Activation also gives the window the keyboard focus, for Escape.
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
let result = if msg == WM_ACTIVATE { unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } } else { LRESULT(0) };
|
||||
if let Some(input) = input(hwnd, msg, wparam, lparam) {
|
||||
match with(|s| s.press.step(input)) {
|
||||
Some(Step::Pick) => finish(hwnd, |s| pick(s, hwnd, lparam)),
|
||||
Some(Step::Cancel) => finish(hwnd, |_| Ok(None)),
|
||||
Some(Step::Wait) | None => {}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
match msg {
|
||||
WM_SETCURSOR | WM_MOUSEMOVE => {
|
||||
// The cursor is set by hand: a window with the mouse capture gets no WM_SETCURSOR.
|
||||
if let Some(cursor) = with(|s| s.cursor) {
|
||||
// SAFETY: a system cursor loaded by `run`.
|
||||
unsafe { SetCursor(Some(cursor)) };
|
||||
}
|
||||
LRESULT(1)
|
||||
}
|
||||
// The copy covers the whole window.
|
||||
WM_ERASEBKGND => LRESULT(1),
|
||||
WM_PAINT => {
|
||||
paint(hwnd);
|
||||
LRESULT(0)
|
||||
}
|
||||
// The window keeps covering the virtual screen when it reaches a monitor of another scale.
|
||||
WM_DPICHANGED => LRESULT(0),
|
||||
WM_DESTROY => {
|
||||
with(|s| s.destroyed = true);
|
||||
// SAFETY: ends this thread's message loop.
|
||||
unsafe { PostQuitMessage(0) };
|
||||
LRESULT(0)
|
||||
}
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
_ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `COLORREF` is `0x00bbggrr`: red in the low byte. `CLR_INVALID` and other values with the high
|
||||
/// byte set are not colors.
|
||||
#[test]
|
||||
fn colorrefs_read_as_srgb() {
|
||||
assert_eq!(srgb(0x0000_00FF), Some([1.0, 0.0, 0.0]));
|
||||
assert_eq!(srgb(0x00FF_0000), Some([0.0, 0.0, 1.0]));
|
||||
assert_eq!(srgb(0x0056_3412), Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)));
|
||||
assert_eq!(srgb(0), Some([0.0; 3]));
|
||||
assert_eq!(srgb(0x00FF_FFFF), Some([1.0; 3]));
|
||||
assert_eq!(srgb(CLR_INVALID), None);
|
||||
assert_eq!(srgb(0x0100_0000), None);
|
||||
}
|
||||
|
||||
/// The pointer maps to the copy's pixels through the virtual screen's corner, which is negative
|
||||
/// when a monitor is left of or above the main one. A 1920 × 1080 monitor at 100% left of and
|
||||
/// lower than a 3840 × 2160 one at 150% gives a 5760 × 2160 virtual screen from (−1920, 0), in
|
||||
/// physical pixels on both.
|
||||
#[test]
|
||||
fn screen_points_map_to_pixels_of_the_copy() {
|
||||
let s = VirtualScreen::new(-1920, 0, 5760, 2160).unwrap();
|
||||
assert_eq!(s.pixel(-1920, 0), Some((0, 0)));
|
||||
assert_eq!(s.pixel(-1, 300), Some((1919, 300)));
|
||||
assert_eq!(s.pixel(0, 0), Some((1920, 0)));
|
||||
assert_eq!(s.pixel(3839, 2159), Some((5759, 2159)));
|
||||
for (x, y) in [(-1921, 0), (3840, 0), (0, -1), (0, 2160), (i32::MIN, 0), (i32::MAX, i32::MAX)] {
|
||||
assert_eq!(s.pixel(x, y), None, "({x}, {y})");
|
||||
}
|
||||
// A monitor above the main one.
|
||||
let s = VirtualScreen::new(-200, -1440, 2760, 2520).unwrap();
|
||||
assert_eq!(s.pixel(0, 0), Some((200, 1440)));
|
||||
assert_eq!(s.pixel(-200, -1440), Some((0, 0)));
|
||||
// A virtual screen at the far corner of the coordinates maps without overflowing.
|
||||
let s = VirtualScreen::new(i32::MIN, i32::MIN, 10, 10).unwrap();
|
||||
assert_eq!(s.pixel(i32::MIN + 9, i32::MIN), Some((9, 0)));
|
||||
assert_eq!(s.pixel(i32::MAX, 0), None);
|
||||
}
|
||||
|
||||
/// The release's own point picks, with signed coordinates: left of or above the client area
|
||||
/// they are negative. Past 32,767 pixels they are widened by the message's pointer position.
|
||||
#[test]
|
||||
fn the_release_point_comes_from_the_message() {
|
||||
let lparam = |x: i32, y: i32| ((y as u16 as isize) << 16) | x as u16 as isize;
|
||||
assert_eq!(message_point(lparam(100, 200), (140, 260)), (100, 200), "the lParam point wins over a nearby position");
|
||||
assert_eq!(message_point(lparam(65_636, 0), (65_636, 0)), (65_636, 0), "MSG.pt gives the high bits past 65,535 pixels");
|
||||
assert_eq!(message_point(lparam(100, 0), (100, 0)), (100, 0));
|
||||
assert_eq!(message_point(lparam(-5, -1), (10, 10)), (-5, -1));
|
||||
assert_eq!(message_point(lparam(0, 0), (0, 0)), (0, 0));
|
||||
assert_eq!(message_point(lparam(32_767, -32_768), (32_767, -32_768)), (32_767, -32_768));
|
||||
assert_eq!(message_point(lparam(40_010, 2_000), (40_000, 2_100)), (40_010, 2_000), "eight 8K monitors in a row");
|
||||
assert_eq!(message_point(lparam(61_439, 0), (61_000, 0)), (61_439, 0));
|
||||
assert_eq!(message_point(lparam(32_770, 0), (32_760, 0)), (32_770, 0));
|
||||
// A negative `lParam` on 64-bit Windows keeps only its low 32 bits as the point.
|
||||
assert_eq!(message_point(lparam(-3, -4) | !0xFFFF_FFFF, (0, 0)), (-3, -4));
|
||||
assert_eq!(message_point(lparam(5, 5), (i32::MAX, i32::MIN)), (i32::MAX, i32::MIN + 5), "saturates at the coordinate range");
|
||||
}
|
||||
|
||||
/// The size is checked before the copy is made: an empty, negative, oversized or out-of-range
|
||||
/// virtual screen is an error.
|
||||
#[test]
|
||||
fn the_copy_size_is_checked_first() {
|
||||
assert!(VirtualScreen::new(0, 0, 7680 * 8, 4320).is_ok(), "eight 8K monitors in a row");
|
||||
for (left, top, width, height) in [
|
||||
(0, 0, 0, 1080),
|
||||
(0, 0, 1920, 0),
|
||||
(0, 0, -1920, 1080),
|
||||
(0, 0, 7680 * 8, 4370),
|
||||
(0, 0, i32::MAX, i32::MAX),
|
||||
(i32::MAX - 100, 0, 1920, 1080),
|
||||
(0, i32::MAX - 100, 1920, 1080),
|
||||
] {
|
||||
assert!(VirtualScreen::new(left, top, width, height).is_err(), "{left} {top} {width} {height}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A left click picks when it is released; Escape, a click of any other button, closing the
|
||||
/// window and losing the mouse cancel; losing the focus cancels once the window had it. A
|
||||
/// release whose press began elsewhere does nothing.
|
||||
#[test]
|
||||
fn clicks_and_keys_pick_or_cancel() {
|
||||
let run = |inputs: &[Input]| {
|
||||
let mut press = Press::default();
|
||||
inputs.iter().map(|&i| press.step(i)).find(|&s| s != Step::Wait).unwrap_or(Step::Wait)
|
||||
};
|
||||
use Input::{Activated, CaptureLost, Closed, Deactivated, Escape};
|
||||
let (left_down, left_up) = (Input::Down(Button::Left), Input::Up(Button::Left));
|
||||
let (right_down, right_up) = (Input::Down(Button::Right), Input::Up(Button::Right));
|
||||
let (other_down, other_up) = (Input::Down(Button::Other), Input::Up(Button::Other));
|
||||
assert_eq!(run(&[Activated, left_down, left_up]), Step::Pick);
|
||||
assert_eq!(run(&[left_down, left_up]), Step::Pick, "a window that never became active still takes a click");
|
||||
assert_eq!(run(&[Activated, right_down, right_up]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, other_down, other_up]), Step::Cancel, "the middle and side buttons cancel");
|
||||
assert_eq!(run(&[Activated, other_down, left_up]), Step::Wait);
|
||||
assert_eq!(run(&[Activated, Escape]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, Deactivated]), Step::Cancel);
|
||||
assert_eq!(run(&[Deactivated]), Step::Wait);
|
||||
assert_eq!(run(&[CaptureLost]), Step::Cancel);
|
||||
assert_eq!(run(&[Closed]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, left_up, right_up, other_up]), Step::Wait, "releases of presses made before the window showed");
|
||||
assert_eq!(run(&[left_down, right_down, left_up]), Step::Wait, "the right button replaced the left one");
|
||||
assert_eq!(run(&[right_down, left_down, left_up]), Step::Pick);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-dxf = { workspace = true }
|
||||
craft-plotter = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
|
||||
+2
-428
@@ -1,428 +1,2 @@
|
||||
//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow
|
||||
//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the
|
||||
//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped,
|
||||
//! with the data their escapes carry.
|
||||
|
||||
/// The end-of-text character, the default label terminator.
|
||||
pub(super) const ETX: u8 = 3;
|
||||
const ESC: u8 = 0x1b;
|
||||
|
||||
/// The most digits of a number that count: longer ones are read as their first digits.
|
||||
const MAX_DIGITS: usize = 18;
|
||||
|
||||
/// What the bytes being read hold.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
/// HP-GL instructions.
|
||||
Hpgl,
|
||||
/// PCL or HP RTL: escape sequences and their data, nothing to draw.
|
||||
Pcl,
|
||||
/// After a Universal Exit Language: PJL lines until a language starts.
|
||||
Pjl,
|
||||
}
|
||||
|
||||
/// One item of a PE (Polyline Encoded) instruction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum PeItem {
|
||||
/// Select pen.
|
||||
Pen(i64),
|
||||
/// Rectangle mode: the following coordinates come in fours.
|
||||
Rect,
|
||||
/// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`).
|
||||
Point { x: f64, y: f64, up: bool, absolute: bool },
|
||||
}
|
||||
|
||||
/// The state of one PE instruction being read.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(super) struct Pe {
|
||||
seven_bit: bool,
|
||||
fraction_bits: u32,
|
||||
up: bool,
|
||||
absolute: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Lexer<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
mode: Mode,
|
||||
/// The file holds HP RTL or PCL raster image data.
|
||||
pub raster: bool,
|
||||
}
|
||||
|
||||
/// Is `c` a byte that separates numeric parameters (or white space between instructions)?
|
||||
fn separator(c: u8) -> bool {
|
||||
matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0)
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
pub fn new(b: &'a [u8]) -> Self {
|
||||
Self { b, at: 0, mode: Mode::Hpgl, raster: false }
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.b.get(self.at).copied()
|
||||
}
|
||||
|
||||
/// Whether everything has been read.
|
||||
pub fn done(&self) -> bool {
|
||||
self.at >= self.b.len()
|
||||
}
|
||||
|
||||
/// How many bytes have been read.
|
||||
pub fn pos(&self) -> usize {
|
||||
self.at
|
||||
}
|
||||
|
||||
/// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and
|
||||
/// escape sequences may come before it (anything else gives `None`, as the end does).
|
||||
pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if c == ESC {
|
||||
self.escape();
|
||||
continue;
|
||||
}
|
||||
match self.mode {
|
||||
Mode::Pcl => {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
Mode::Pjl => {
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c == b'@' {
|
||||
self.pjl_line();
|
||||
} else {
|
||||
self.mode = Mode::Hpgl;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Mode::Hpgl => {}
|
||||
}
|
||||
let next = self.b.get(self.at + 1).copied();
|
||||
if c.is_ascii_alphabetic()
|
||||
&& let Some(n) = next.filter(u8::is_ascii_alphabetic)
|
||||
{
|
||||
self.at += 2;
|
||||
return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]);
|
||||
}
|
||||
if strict && !(separator(c) || c == b';' || c < 0x20) {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows.
|
||||
fn pjl_line(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1);
|
||||
// A command names its language within its first 256 bytes; longer lines aren't copied.
|
||||
let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase();
|
||||
if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) {
|
||||
self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl };
|
||||
}
|
||||
self.at += end;
|
||||
}
|
||||
|
||||
/// An escape sequence at the current byte, with the data it carries.
|
||||
fn escape(&mut self) {
|
||||
self.at += 1;
|
||||
let Some(c) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
match c {
|
||||
// Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL,
|
||||
// `ESC%#A` to PCL or HP RTL).
|
||||
b'%' => {
|
||||
let (_, end) = self.value();
|
||||
match end {
|
||||
Some(b'X') => self.mode = Mode::Pjl,
|
||||
Some(b'B') => self.mode = Mode::Hpgl,
|
||||
Some(b'A') => self.mode = Mode::Pcl,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Reset: PCL follows, until a language switch.
|
||||
b'E' => self.mode = Mode::Pcl,
|
||||
// HP-GL device control: `ESC.` and a letter, with parameters up to a colon.
|
||||
b'.' => {
|
||||
let Some(kind) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
if !b"()YZBEJKLORUX".contains(&kind) {
|
||||
let rest = &self.b[self.at..self.b.len().min(self.at + 80)];
|
||||
if let Some(n) = rest.iter().position(|&c| c == b':')
|
||||
&& rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b','))
|
||||
{
|
||||
self.at += n + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Parameterized PCL: a group character, then values each ending in a letter (upper case
|
||||
// ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print
|
||||
// data) are followed by that many bytes of data. Without a group character (`ESC(8U`,
|
||||
// `ESC)0N`), one value and the letter ending it.
|
||||
0x21..=0x2f => {
|
||||
let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else {
|
||||
self.value();
|
||||
return;
|
||||
};
|
||||
self.at += 1;
|
||||
loop {
|
||||
let (v, end) = self.value();
|
||||
let Some(end) = end else { return };
|
||||
let upper = end.to_ascii_uppercase();
|
||||
if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') {
|
||||
let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize;
|
||||
if (c, group) == (b'*', b'b') && n > 0 {
|
||||
self.raster = true;
|
||||
}
|
||||
self.at += n;
|
||||
}
|
||||
if (c, group, end) == (b'*', b'r', b'A') {
|
||||
self.raster = true;
|
||||
}
|
||||
if !end.is_ascii_lowercase() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A two-character escape.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None`
|
||||
/// when that is not a letter or `@` (which is then left unread).
|
||||
fn value(&mut self) -> (f64, Option<u8>) {
|
||||
let v = self.number_here().unwrap_or(0.0);
|
||||
match self.peek() {
|
||||
Some(c) if c.is_ascii_alphabetic() || c == b'@' => {
|
||||
self.at += 1;
|
||||
(v, Some(c))
|
||||
}
|
||||
_ => (v, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit
|
||||
/// (its sign and point are read all the same).
|
||||
fn number_here(&mut self) -> Option<f64> {
|
||||
let mut neg = false;
|
||||
if let Some(c @ (b'+' | b'-')) = self.peek() {
|
||||
neg = c == b'-';
|
||||
self.at += 1;
|
||||
}
|
||||
let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64);
|
||||
let mut point = false;
|
||||
while let Some(c) = self.peek() {
|
||||
if c.is_ascii_digit() {
|
||||
if digits < MAX_DIGITS {
|
||||
if point {
|
||||
scale /= 10.0;
|
||||
v += f64::from(c - b'0') * scale;
|
||||
} else {
|
||||
v = v * 10.0 + f64::from(c - b'0');
|
||||
}
|
||||
} else if !point {
|
||||
// Past the digits that count, an integer part keeps its size.
|
||||
v *= 10.0;
|
||||
}
|
||||
digits += 1;
|
||||
} else if c == b'.' && !point {
|
||||
point = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
let v = v.min(f64::MAX);
|
||||
(digits > 0).then_some(if neg { -v } else { v })
|
||||
}
|
||||
|
||||
/// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon
|
||||
/// ending it is read).
|
||||
pub fn number(&mut self) -> Option<f64> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') {
|
||||
if let Some(v) = self.number_here() {
|
||||
return Some(v);
|
||||
}
|
||||
} else {
|
||||
if c == b';' {
|
||||
self.at += 1;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many.
|
||||
pub fn numbers(&mut self, out: &mut [f64]) -> usize {
|
||||
let mut n = 0;
|
||||
while let Some(v) = self.number() {
|
||||
if let Some(slot) = out.get_mut(n) {
|
||||
*slot = v;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
n.min(out.len())
|
||||
}
|
||||
|
||||
/// Read and drop the parameters of the instruction being read: numbers and quoted strings.
|
||||
pub fn params(&mut self) {
|
||||
loop {
|
||||
while self.number().is_some() {}
|
||||
if self.peek() != Some(b'"') {
|
||||
return;
|
||||
}
|
||||
self.quoted();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader
|
||||
/// doesn't know, written out in full).
|
||||
pub fn closed_params(&mut self) -> bool {
|
||||
while self.number().is_some() {}
|
||||
self.at > 0 && self.b.get(self.at - 1) == Some(&b';')
|
||||
}
|
||||
|
||||
/// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it
|
||||
/// is one.
|
||||
pub fn comment(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'"') => self.quoted(),
|
||||
Some(b';') => {
|
||||
self.at += 1;
|
||||
true
|
||||
}
|
||||
None => true,
|
||||
Some(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a label, up to and including `terminator` (or the end).
|
||||
pub fn label(&mut self, terminator: u8) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether
|
||||
/// there was one.
|
||||
pub fn quoted(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
let found = self.peek() == Some(b'"');
|
||||
if found {
|
||||
self.at += 1;
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
if self.peek() == Some(b';') {
|
||||
self.at += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end
|
||||
/// (the semicolon is read).
|
||||
pub fn char(&mut self) -> Option<u8> {
|
||||
let c = self.peek()?;
|
||||
self.at += 1;
|
||||
(c != b';').then_some(c)
|
||||
}
|
||||
|
||||
/// The next item of a PE instruction, `None` at its end (its semicolon is read).
|
||||
pub fn pe(&mut self, st: &mut Pe) -> Option<PeItem> {
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = raw & 0x7f;
|
||||
// Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored.
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
b';' => {
|
||||
self.at += 1;
|
||||
return None;
|
||||
}
|
||||
// Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up).
|
||||
b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => {
|
||||
self.at += 1;
|
||||
match c {
|
||||
b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()),
|
||||
b'<' => st.up = true,
|
||||
b'>' => match self.pe_value(st) {
|
||||
Some(n) => st.fraction_bits = n.clamp(0, 52) as u32,
|
||||
None => return self.end_pe(),
|
||||
},
|
||||
b'=' => st.absolute = true,
|
||||
b'7' => st.seven_bit = true,
|
||||
_ => return Some(PeItem::Rect),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let scale = 0.5f64.powi(st.fraction_bits as i32);
|
||||
let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() };
|
||||
let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute };
|
||||
(st.up, st.absolute) = (false, false);
|
||||
return Some(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`].
|
||||
fn end_pe(&mut self) -> Option<PeItem> {
|
||||
self.skip_pe();
|
||||
None
|
||||
}
|
||||
|
||||
/// The data of a PE instruction, up to and including its semicolon, unread: its data is never
|
||||
/// read as instructions.
|
||||
pub fn skip_pe(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no
|
||||
/// digit comes first, which is read).
|
||||
fn pe_value(&mut self, st: &Pe) -> Option<i64> {
|
||||
let (base, low, high): (u64, std::ops::RangeInclusive<u8>, std::ops::RangeInclusive<u8>) =
|
||||
if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) };
|
||||
let (mut v, mut place) = (0u64, 1u64);
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = if st.seven_bit { raw & 0x7f } else { raw };
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b';' {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
let (digit, last) = if low.contains(&c) {
|
||||
(u64::from(c - 63), false)
|
||||
} else if high.contains(&c) {
|
||||
(u64::from(c - high.start()), true)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
v = v.saturating_add(digit.saturating_mul(place));
|
||||
place = place.saturating_mul(base);
|
||||
if last {
|
||||
// The low bit is the sign.
|
||||
let n = i64::try_from(v >> 1).unwrap_or(i64::MAX);
|
||||
return Some(if v & 1 == 1 { -n } else { n });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//! Shared HP-GL byte lexer; drawing interpretation remains local.
|
||||
pub(super) use craft_plotter::hpgl::lex::{ETX, Lexer, Pe, PeItem};
|
||||
+107
-16
@@ -15,7 +15,8 @@ use crate::{AppearanceItem, Document, Node, NodeKind};
|
||||
pub struct Inks {
|
||||
/// Process inks C, M, Y, K (0..1).
|
||||
pub cmyk: [f32; 4],
|
||||
/// Spot ink (swatch name, tint 0..1).
|
||||
/// Spot ink (swatch name, tint 0..1). A spot ink named like a process plate ("Cyan",
|
||||
/// "Magenta", "Yellow", "Black") prints on that plate: its tint is in `cmyk` too.
|
||||
pub spot: Option<(String, f32)>,
|
||||
/// Registration: the tint (every process ink's) prints on every spot plate too.
|
||||
pub registration: bool,
|
||||
@@ -49,7 +50,20 @@ pub struct Plate {
|
||||
pub rgb: [f32; 3],
|
||||
}
|
||||
|
||||
/// The plates of `doc`: the four process plates plus one per spot swatch.
|
||||
/// Spot swatch `name` as art links to it: [`Document::swatch`] `name` when that is a spot swatch of
|
||||
/// a solid colour.
|
||||
fn spot_swatch<'a>(doc: &'a Document, name: &str) -> Option<&'a vectorcraft_color::Swatch> {
|
||||
doc.swatch(name).filter(|s| s.spot && s.paint.color().is_some())
|
||||
}
|
||||
|
||||
/// The index in [`PROCESS_PLATES`] of the process plate named `name`.
|
||||
fn process_plate(name: &str) -> Option<usize> {
|
||||
PROCESS_PLATES.iter().position(|p| *p == name)
|
||||
}
|
||||
|
||||
/// The plates of `doc`: the four process plates plus one per spot swatch that art can link to. A
|
||||
/// link names a swatch, which is the first swatch of that name ([`Document::swatch`]), so a spot
|
||||
/// swatch after another of its name, or named like a process plate, gets no plate.
|
||||
pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let mut v: Vec<Plate> = PROCESS_PLATES
|
||||
@@ -61,20 +75,29 @@ pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
Plate { name: (*n).into(), spot: false, rgb: c.cmyk_to_srgb(ink, false) }
|
||||
})
|
||||
.collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for sw in doc.swatches_iter() {
|
||||
if let (true, Paint::Solid { color, .. }) = (sw.spot, &sw.paint)
|
||||
&& !v.iter().any(|p| p.name == sw.name)
|
||||
// Only the first swatch of a name is the one [`spot_swatch`] finds.
|
||||
if !seen.insert(sw.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let (true, Some(color)) = (sw.spot, sw.paint.color())
|
||||
&& !PROCESS_PLATES.contains(&sw.name.as_str())
|
||||
{
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(*color, true)) });
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(color, true)) });
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]).
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]); `None` when
|
||||
/// [`Document::swatch`] `name` is not a spot swatch, or `name` is a process plate's, whose ink
|
||||
/// prints on that plate.
|
||||
pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
|
||||
let s = doc.swatch(name).filter(|s| s.spot)?;
|
||||
s.paint.color().map(|c| doc.linked_color(c, true))
|
||||
if process_plate(name).is_some() {
|
||||
return None;
|
||||
}
|
||||
spot_swatch(doc, name)?.paint.color().map(|c| doc.linked_color(c, true))
|
||||
}
|
||||
|
||||
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
|
||||
@@ -86,16 +109,22 @@ fn ink_amount(v: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate. A tint that is
|
||||
/// not a finite number prints no ink.
|
||||
/// its tint, and one linked to a spot swatch named like a process plate prints its tint on that
|
||||
/// process plate, as PDF and EPS export write it; one linked to the Registration swatch prints its
|
||||
/// tint on every plate. A tint that is not a finite number prints no ink.
|
||||
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
|
||||
if let Some((REGISTRATION, tint)) = link {
|
||||
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
|
||||
}
|
||||
if let Some((name, tint)) = link
|
||||
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
|
||||
&& spot_swatch(doc, name).is_some()
|
||||
{
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), ink_amount(tint))), registration: false };
|
||||
let tint = ink_amount(tint);
|
||||
let mut cmyk = [0.0; 4];
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = tint;
|
||||
}
|
||||
return Inks { cmyk, spot: Some((name.to_string(), tint)), registration: false };
|
||||
}
|
||||
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
|
||||
}
|
||||
@@ -106,11 +135,18 @@ pub type StopPlates = Option<[f32; 4]>;
|
||||
|
||||
/// [`inks`] of a colour that may print process plates `plates` with its spot tint. The plates
|
||||
/// print only beside a spot ink: a colour without a valid spot link, or linked to Registration,
|
||||
/// prints as [`inks`] separates it. A plate amount that is not a finite number prints no ink.
|
||||
/// prints as [`inks`] separates it. A spot ink named like a process plate prints its tint layered
|
||||
/// over that plate's amount; EPS export can't write that ink beside process plates in one DeviceN
|
||||
/// space, so it writes such a gradient in process colors with a warning. A plate amount that is
|
||||
/// not a finite number prints no ink.
|
||||
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
|
||||
let mut ink = inks(doc, c, color, link, intent);
|
||||
if let (Some(p), Some(_)) = (plates, &ink.spot) {
|
||||
ink.cmyk = p.map(ink_amount);
|
||||
if let (Some(p), Some((name, tint))) = (plates, &ink.spot) {
|
||||
let mut cmyk = p.map(ink_amount);
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = 1.0 - (1.0 - cmyk[i]) * (1.0 - tint);
|
||||
}
|
||||
ink.cmyk = cmyk;
|
||||
}
|
||||
ink
|
||||
}
|
||||
@@ -201,7 +237,7 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{NodeId, SymbolOverride};
|
||||
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch};
|
||||
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch, SwatchGroup};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
/// A document with spot swatch `Gold` and process swatch `Teal`.
|
||||
@@ -233,6 +269,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of `doc`'s spot plates, in order.
|
||||
fn spot_plates(doc: &Document) -> Vec<String> {
|
||||
plates(doc).into_iter().filter(|p| p.spot).map(|p| p.name).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_swatch_named_like_an_earlier_process_swatch_gets_no_plate() {
|
||||
// Art links to a swatch by name, which finds the earlier process `Teal`: the later spot
|
||||
// `Teal` in a colour group prints nothing, so it gets no plate.
|
||||
let mut d = gold_doc();
|
||||
let spot_teal = Swatch { name: "Teal".into(), paint: Paint::solid(Color::cmyk(0.9, 0.0, 0.4, 0.0)), global: true, spot: true };
|
||||
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![spot_teal.clone()] });
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let look = Color::cmyk(0.8, 0.0, 0.3, 0.0);
|
||||
let teal = inks(&d, &c, &look, Some(("Teal", 1.0)), Intent::RelativeColorimetric);
|
||||
assert_eq!(teal, Inks { cmyk: c.to_cmyk(&look, Intent::RelativeColorimetric), spot: None, registration: false });
|
||||
let stop = stop_inks(&d, &c, &look, Some(("Teal", 1.0)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
|
||||
assert_eq!(stop, teal, "a gradient stop linked to it separates as process too");
|
||||
assert_eq!(spot_color(&d, "Teal"), None);
|
||||
assert_eq!(spot_plates(&d), ["Gold"], "no plate for the spot swatch that no art reaches");
|
||||
// The first swatch of a name decides either way: a spot swatch first gets its plate, and a
|
||||
// later process swatch of the same name does not take it away.
|
||||
let mut d = gold_doc();
|
||||
d.swatches.retain(|s| s.name != "Teal");
|
||||
d.swatches.insert(0, spot_teal);
|
||||
let process_teal = Swatch { name: "Teal".into(), paint: Paint::solid(look), global: true, spot: false };
|
||||
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![process_teal] });
|
||||
assert_eq!(spot_plates(&d), ["Teal", "Gold"]);
|
||||
let teal = inks(&d, &c, &look, Some(("Teal", 0.5)), Intent::RelativeColorimetric);
|
||||
assert_eq!(teal, Inks { cmyk: [0.0; 4], spot: Some(("Teal".into(), 0.5)), registration: false });
|
||||
assert_eq!(spot_color(&d, "Teal"), Some(Color::cmyk(0.9, 0.0, 0.4, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_swatch_named_like_a_process_plate_prints_on_that_plate() {
|
||||
// A spot `Cyan` has the process Cyan plate's name, so art linked to it prints its tint on
|
||||
// that plate, as a Separation ink named `Cyan` in PDF and EPS export does, instead of a
|
||||
// spot amount that no plate prints.
|
||||
let mut d = gold_doc();
|
||||
let blue = Color::cmyk(1.0, 0.3, 0.0, 0.1);
|
||||
d.swatches.insert(0, Swatch { name: "Cyan".into(), paint: Paint::solid(blue), global: true, spot: true });
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let ink = inks(&d, &c, &blue, Some(("Cyan", 0.5)), Intent::RelativeColorimetric);
|
||||
assert_eq!(ink, Inks { cmyk: [0.5, 0.0, 0.0, 0.0], spot: Some(("Cyan".into(), 0.5)), registration: false });
|
||||
assert_eq!((ink.on_plate("Cyan"), ink.on_plate("Magenta"), ink.on_plate("Gold")), (0.5, 0.0, 0.0));
|
||||
let nan = inks(&d, &c, &blue, Some(("Cyan", f32::NAN)), Intent::RelativeColorimetric);
|
||||
assert_eq!(nan.cmyk, [0.0; 4], "a tint that is not a number prints no ink");
|
||||
// A gradient stop's own process plates still print, with the tint layered over its Cyan.
|
||||
let stop = stop_inks(&d, &c, &blue, Some(("Cyan", 0.5)), Some([0.2, 0.4, 0.0, 0.0]), Intent::RelativeColorimetric);
|
||||
assert!((stop.on_plate("Cyan") - 0.6).abs() < 1e-6, "{stop:?}");
|
||||
assert_eq!((stop.on_plate("Magenta"), stop.on_plate("Yellow"), stop.on_plate("Black")), (0.4, 0.0, 0.0));
|
||||
assert_eq!(spot_color(&d, "Cyan"), None);
|
||||
assert_eq!(spot_plates(&d), ["Gold"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_or_registration_tint_that_is_not_a_finite_number_prints_no_ink() {
|
||||
let d = gold_doc();
|
||||
|
||||
+119
-7
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
@@ -46,14 +46,21 @@ impl Default for OverprintBlack {
|
||||
}
|
||||
|
||||
impl OverprintBlack {
|
||||
/// Whether `p` is black: a solid colour (linked to one of the spot swatches `spots` only with
|
||||
/// [`Self::spot`]), or a gradient whose every stop is.
|
||||
/// Whether `p` is black: a solid color (linked to one of the spot swatches `spots` only with
|
||||
/// [`Self::spot`]), a gradient whose every stop is, or a freeform gradient with color points
|
||||
/// whose every point is (it draws from its points, not its stops).
|
||||
fn black(&self, p: &Paint, spots: &[String]) -> bool {
|
||||
let ink = |color: &Color, swatch: &Option<String>| {
|
||||
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
|
||||
};
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => {
|
||||
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
|
||||
}
|
||||
Paint::Gradient(g) => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| is_black_ink(&s.color, self.min_k, self.rich)),
|
||||
Paint::Solid { color, swatch, .. } => ink(color, swatch),
|
||||
// Only a freeform gradient draws its points; another kind draws its stops whatever it holds.
|
||||
Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
|
||||
Some(f) => f.points.iter().all(|pt| is_black_ink(&pt.color, self.min_k, self.rich)),
|
||||
// Without points of its own a freeform gradient places them from its stops.
|
||||
None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| ink(&s.color, &s.swatch)),
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -85,6 +92,52 @@ impl OverprintBlack {
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// [`Self::apply`] to every node of `a`'s subtree, copying only the nodes on the way to those
|
||||
/// that change. Returns whether anything changed.
|
||||
pub fn apply_deep(&self, a: &mut Arc<Node>, spots: &[String]) -> bool {
|
||||
match self.marked(a, spots) {
|
||||
Some(n) => {
|
||||
*a = n;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n`'s subtree with [`Self::apply`] done to each node, when that changes anything (`None`
|
||||
/// otherwise). Each node is visited once, and only the nodes on the way to a change are copied.
|
||||
fn marked(&self, n: &Arc<Node>, spots: &[String]) -> Option<Arc<Node>> {
|
||||
let members: Vec<(usize, Arc<Node>)> =
|
||||
n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.marked(c, spots)?))).collect();
|
||||
if members.is_empty() && !self.changes(n, spots) {
|
||||
return None;
|
||||
}
|
||||
let mut copy = Arc::clone(n);
|
||||
let m = Arc::make_mut(&mut copy);
|
||||
self.apply(m, spots);
|
||||
if let Some(children) = m.children_mut() {
|
||||
for (i, c) in members {
|
||||
if let Some(slot) = children.get_mut(i) {
|
||||
*slot = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(copy)
|
||||
}
|
||||
|
||||
/// Whether [`Self::apply`] changes a fill, stroke or character of `n` itself.
|
||||
fn changes(&self, n: &Node, spots: &[String]) -> bool {
|
||||
let on = !self.remove;
|
||||
let item = |it: &crate::AppearanceItem| {
|
||||
it.overprint() != on && (if it.is_fill() { self.fill } else { self.stroke }) && self.black(it.paint(), spots)
|
||||
};
|
||||
let run = |r: &crate::TextRun| {
|
||||
(self.fill && r.style.overprint_fill != on && self.black(&r.style.fill, spots))
|
||||
|| (self.stroke && r.style.overprint_stroke != on && self.black(&r.style.stroke, spots))
|
||||
};
|
||||
n.appearance.items.iter().any(item) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run))
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
@@ -236,6 +289,65 @@ mod tests {
|
||||
assert!(tx.runs[0].style.overprint_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_freeform_gradient_is_black_when_every_point_is() {
|
||||
use vectorcraft_color::freeform::{Freeform, FreeformPoint};
|
||||
let k = Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient { kind: GradientKind::Freeform, ..Default::default() });
|
||||
for s in &mut g.gradient.stops {
|
||||
s.color = k;
|
||||
}
|
||||
let points = vec![FreeformPoint::new(Point::ZERO, k), FreeformPoint::new(Point::new(10.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0))];
|
||||
g.freeform = Some(Freeform { points, ..Default::default() });
|
||||
let fill = |g: &vectorcraft_color::GradientPaint| Appearance::basic(Paint::Gradient(Box::new(g.clone())), Paint::None, 0.0);
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(!OverprintBlack::default().apply(&mut n, &[]), "a cyan point is drawn, whatever the stops");
|
||||
// Another kind of gradient draws its black stops, not the points it still holds.
|
||||
let mut linear = g.clone();
|
||||
linear.gradient.kind = GradientKind::Linear;
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&linear));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "a linear gradient is judged by its stops");
|
||||
if let Some(f) = &mut g.freeform {
|
||||
f.points[1].color = Color::gray(1.0);
|
||||
}
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "every point black");
|
||||
g.freeform = Some(Freeform::default());
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "no points: placed from the black stops");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_with_a_spot_linked_stop_is_black_only_with_spot() {
|
||||
let mut g = vectorcraft_color::GradientPaint::new(Default::default());
|
||||
for s in &mut g.gradient.stops {
|
||||
s.color = Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
g.gradient.stops[0].swatch = Some("Ink".into());
|
||||
let k = Paint::Gradient(Box::new(g));
|
||||
let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(k, Paint::None, 0.0));
|
||||
let spots = ["Ink".to_string()];
|
||||
assert!(!OverprintBlack::default().apply(&mut n, &spots), "a stop linked to a spot swatch is not process black");
|
||||
assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_deep_copies_only_the_nodes_that_change() {
|
||||
let k = cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let black = Arc::new(Node::path(NodeId(2), Default::default(), Appearance::basic(k, Paint::None, 0.0)));
|
||||
let cyan = Arc::new(Node::path(NodeId(3), Default::default(), Appearance::basic(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None, 0.0)));
|
||||
let mut group = Arc::new(Node::group(NodeId(1), vec![black.clone(), cyan.clone()]));
|
||||
let before = group.clone();
|
||||
assert!(OverprintBlack::default().apply_deep(&mut group, &[]));
|
||||
let members = group.children().unwrap();
|
||||
assert!(members[0].appearance.fill().unwrap().overprint && !black.has_overprint(), "the copy is marked, not the original");
|
||||
assert!(Arc::ptr_eq(&members[1], &cyan), "the cyan member is shared, not copied");
|
||||
assert!(!before.has_overprint());
|
||||
let marked = group.clone();
|
||||
assert!(!OverprintBlack::default().apply_deep(&mut group, &[]), "nothing left to change");
|
||||
assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_overprint_black_list_migrates() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
|
||||
@@ -82,7 +82,7 @@ pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_objec
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_map, staged_effects,
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
|
||||
without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
|
||||
@@ -608,21 +608,36 @@ fn transform_step(e: &Effect) -> Option<Affine> {
|
||||
|
||||
/// The Transform effects of `effects` that move the image of its last visible Rasterize effect
|
||||
/// instead of the art it is made from: the indices of the visible Transform effects listed after
|
||||
/// it that move the art, when from the first visible Transform effect after it on every visible
|
||||
/// effect is a Transform effect that moves the art once (no copies, not at random). Effects apply
|
||||
/// in the order they are listed, so the image is made of the art before those Transform effects
|
||||
/// and moves with them, its pixel grid and room around the art included. `None` when there is no
|
||||
/// such Transform effect, or the effects after the Rasterize effect hold anything else from there
|
||||
/// on.
|
||||
/// it that move or copy the art, when from the first visible Transform effect after it on every
|
||||
/// visible effect is a Transform effect that does not move at random, and at most one of them makes
|
||||
/// copies. Effects apply in the order they are listed, so the image is made of the art before those
|
||||
/// Transform effects and moves with them, its pixel grid and room around the art included; each copy
|
||||
/// carries the same image ([`stage_maps`]). `None` when there is no such Transform effect, or the
|
||||
/// effects after the Rasterize effect hold anything else from there on.
|
||||
pub fn rasterize_stage(effects: &[Effect]) -> Option<Vec<usize>> {
|
||||
let r = effects.iter().rposition(|e| e.visible && e.id == RASTERIZE)?;
|
||||
let first = r + 1 + effects.get(r + 1..)?.iter().position(|e| e.visible && e.id == "distort.transform")?;
|
||||
let mut at = vec![];
|
||||
let mut copying = false;
|
||||
for (i, e) in effects.iter().enumerate().skip(first).filter(|(_, e)| e.visible) {
|
||||
if e.id != "distort.transform" || transform_step(e).is_none() {
|
||||
if e.id != "distort.transform" {
|
||||
return None;
|
||||
}
|
||||
if crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).0 != Affine::IDENTITY {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
if !flag(&p, "objects", true) {
|
||||
continue;
|
||||
}
|
||||
if flag(&p, "random", false) {
|
||||
return None;
|
||||
}
|
||||
let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0);
|
||||
if copies > 0 {
|
||||
if copying {
|
||||
return None;
|
||||
}
|
||||
copying = true;
|
||||
}
|
||||
if copies > 0 || map != Affine::IDENTITY {
|
||||
at.push(i);
|
||||
}
|
||||
}
|
||||
@@ -641,22 +656,41 @@ pub fn staged_effects(effects: &[Effect], at: &[usize]) -> Vec<Effect> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The map the Transform effects at `at` of `effects` ([`rasterize_stage`]) move the Rasterize
|
||||
/// The maps the Transform effects at `at` of `effects` ([`rasterize_stage`]) place the Rasterize
|
||||
/// image by, for `staged`, the geometry the effects before them make: each one's map about its
|
||||
/// reference point on the bounds of the geometry it takes, as the geometry pass applies it, the
|
||||
/// last one outermost. `None` when `staged` is empty or the map is not a number.
|
||||
pub fn stage_map(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Affine> {
|
||||
/// last one outermost. A Transform effect with copies places the image once more for each copy
|
||||
/// the geometry pass makes, copy `k` through its map `k` times. The maps come in the order the
|
||||
/// images paint, the lowest first: the last copy lowest and the original on top, as copied objects
|
||||
/// stack. `None` when `staged` is empty or a map is not a number.
|
||||
pub fn stage_maps(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Vec<Affine>> {
|
||||
let mut cur = staged.clone();
|
||||
let mut b = staged.bounds()?;
|
||||
let mut map = Affine::IDENTITY;
|
||||
// The original's map first, then each copy's.
|
||||
let mut maps = vec![Affine::IDENTITY];
|
||||
for &i in at {
|
||||
let e = effects.get(i)?;
|
||||
let (m, _) = crate::distort::transform_map(b, &merged_params(&e.id, &e.params), 0);
|
||||
map = m * map;
|
||||
cur = cur.transformed(m);
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
let (m, copies) = crate::distort::transform_map(b, &p, 0);
|
||||
if copies == 0 {
|
||||
maps.iter_mut().for_each(|x| *x = m * *x);
|
||||
cur = cur.transformed(m);
|
||||
} else {
|
||||
// As many copies as the geometry pass makes: it stops early past its limits.
|
||||
let next = crate::distort::transform(&cur, b, &p, 0);
|
||||
let made = (next.anchor_count() / cur.anchor_count().max(1)).saturating_sub(1);
|
||||
let placed = maps.clone();
|
||||
let mut xf = Affine::IDENTITY;
|
||||
for _ in 0..made {
|
||||
xf = m * xf;
|
||||
maps.extend(placed.iter().map(|x| xf * *x));
|
||||
}
|
||||
cur = next;
|
||||
}
|
||||
b = cur.bounds().unwrap_or(b);
|
||||
}
|
||||
map.is_finite().then_some(map)
|
||||
maps.reverse();
|
||||
maps.iter().all(|m| m.is_finite()).then_some(maps)
|
||||
}
|
||||
|
||||
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
|
||||
|
||||
@@ -129,9 +129,10 @@ fn rasterize_before_a_transform_keeps_its_options() {
|
||||
assert_eq!(crate::rasterize_stage(&effects), Some(vec![1]));
|
||||
}
|
||||
|
||||
/// The Transform effects after the last Rasterize effect move its image when, from the first of
|
||||
/// them on, every visible effect is a Transform effect that moves the art once. Hidden ones, and
|
||||
/// ones with Transform Objects off, leave the image where it is.
|
||||
/// The Transform effects after the last Rasterize effect move or copy its image when, from the
|
||||
/// first of them on, every visible effect is a Transform effect that does not move at random and at
|
||||
/// most one of them makes copies. Hidden ones, and ones with Transform Objects off, leave the image
|
||||
/// where it is.
|
||||
#[test]
|
||||
fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
let rasterize = || fx(crate::RASTERIZE, json!({}));
|
||||
@@ -150,9 +151,16 @@ fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
// the image back.
|
||||
(vec![rasterize(), roughen.clone(), shadow.clone(), scale()], Some(vec![3])),
|
||||
(vec![rasterize(), scale(), roughen], None),
|
||||
(vec![rasterize(), scale(), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], None),
|
||||
(vec![rasterize(), scale(), shadow.clone()], None),
|
||||
// Each copy carries the image, even of a Transform effect that only copies in place.
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], Some(vec![1])),
|
||||
(vec![rasterize(), transform(json!({"copies": 2}))], Some(vec![1])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), scale()], Some(vec![1, 2])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2, "objects": false}))], None),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), transform(json!({"moveV": 10, "copies": 3}))], None),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "random": true}))], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2, "random": true}))], None),
|
||||
// The Transform effect before the Rasterize effect moves the art.
|
||||
(vec![scale(), rasterize()], None),
|
||||
(vec![scale(), rasterize(), rasterize(), scale()], Some(vec![3])),
|
||||
@@ -173,16 +181,62 @@ fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
fn the_image_moves_by_each_transform_about_the_art_it_takes() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"moveH": 5}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
assert_eq!(maps.len(), 1);
|
||||
// Twice the size about the center (20, 20), then 5 pt to the right.
|
||||
let want = Affine::translate((5.0, 0.0)) * Affine::translate((20.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-20.0, -20.0));
|
||||
assert!(map.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{map:?}");
|
||||
assert!(same_map(maps[0], want), "{maps:?}");
|
||||
// The second Transform effect turns about the center of what the first one made.
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"moveH": 100})), transform(json!({"rotate": 90}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = map * Point::new(20.0, 20.0);
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = maps[0] * Point::new(20.0, 20.0);
|
||||
assert!((c.x - 120.0).abs() < 1e-9 && (c.y - 20.0).abs() < 1e-9, "{c:?}");
|
||||
assert_eq!(crate::stage_map(&effects, &[1, 2], &PathData::default()), None);
|
||||
assert_eq!(crate::stage_maps(&effects, &[1, 2], &PathData::default()), None);
|
||||
}
|
||||
|
||||
/// Is `a` `b`, each coefficient within 1e-9?
|
||||
fn same_map(a: Affine, b: Affine) -> bool {
|
||||
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// Are `maps` `want`, in order?
|
||||
fn same_maps(maps: &[Affine], want: &[Affine]) -> bool {
|
||||
maps.len() == want.len() && maps.iter().zip(want).all(|(m, w)| same_map(*m, *w))
|
||||
}
|
||||
|
||||
/// A Transform effect with copies places the image once for the original and once for each copy,
|
||||
/// copy `k` through its map `k` times about the art before it, the last copy lowest and the
|
||||
/// original on top. A Transform effect after it moves every placement, about the bounds of all the
|
||||
/// copies.
|
||||
#[test]
|
||||
fn each_copy_carries_the_image() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let rasterize = fx(crate::RASTERIZE, json!({}));
|
||||
let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
let want = [Affine::translate((200.0, 0.0)), Affine::translate((100.0, 0.0)), Affine::IDENTITY];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// Turned 90° about the center (20, 20) each time: copy 2 turns 180°.
|
||||
let effects = [rasterize.clone(), transform(json!({"rotate": 90, "copies": 2}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
let turn = |deg: f64| Affine::translate((20.0, 20.0)) * Affine::rotate(-deg.to_radians()) * Affine::translate((-20.0, -20.0));
|
||||
let want = [turn(180.0), turn(90.0), Affine::IDENTITY];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// A scale after the copies doubles every placement about the center of all three, (120, 20).
|
||||
let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2})), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let scale = Affine::translate((120.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-120.0, -20.0));
|
||||
let want = [scale * Affine::translate((200.0, 0.0)), scale * Affine::translate((100.0, 0.0)), scale];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// A move before the copies moves the art they copy.
|
||||
let effects = [rasterize.clone(), transform(json!({"moveV": 5})), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let want = [Affine::translate((100.0, 5.0)), Affine::translate((0.0, 5.0))];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// Copies stop where the geometry pass stops them: none past its reach of 1e9 pt.
|
||||
let effects = [rasterize, transform(json!({"moveH": 1.0e7, "copies": 1000}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
assert_eq!(maps.len(), 100, "{}", maps.len());
|
||||
}
|
||||
|
||||
/// An SVG filter keeps its options: it paints in its own user space.
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example cut_path_select_bench` prints the time
|
||||
//! Cut Path at Selected Anchor Points takes to select the cut ends, on synthetic documents of 500,
|
||||
//! 2,000 and 5,000 open paths of 10 anchors each with the 8 anchors between the ends of each
|
||||
//! direct-selected, and on one path of 2,000 open subpaths selected the same way. For each it times two ways of building the same
|
||||
//! selection from the cut ends: clearing the selection and adding each path in turn (each add looks
|
||||
//! through the paths already added), and one `Selection::set` call followed by the anchors. It
|
||||
//! checks that both give the same selection, every field, before it times them, and then times the
|
||||
//! whole command once per run on the 2,000-path document.
|
||||
//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run
|
||||
//! builds the selection 20 times, and each row is the median time of one build. On Linux the times are the CPU time of the main thread, which runs everything, in
|
||||
//! ms; elsewhere they are wall times.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
|
||||
/// The anchors of each path, or of each subpath of the one compound path.
|
||||
const ANCHORS: usize = 10;
|
||||
|
||||
/// The builds of the selection in each timed run; a row gives the time of one build.
|
||||
const REPS: usize = 20;
|
||||
|
||||
/// What the command selects for one cut end: the path and its anchor (subpath, anchor).
|
||||
type Pick = (NodeId, (usize, usize));
|
||||
|
||||
/// A way of building the selection from the cut ends.
|
||||
type Rebuild = fn(&mut Selection, &[Pick]);
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
fn median(mut ms: Vec<f64>) -> f64 {
|
||||
ms.sort_by(f64::total_cmp);
|
||||
ms[ms.len() / 2]
|
||||
}
|
||||
|
||||
/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only).
|
||||
fn thread_cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise.
|
||||
fn measure(f: impl FnOnce()) -> f64 {
|
||||
match thread_cpu_ns() {
|
||||
Some(start) => {
|
||||
f();
|
||||
thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6)
|
||||
}
|
||||
None => {
|
||||
let t = Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection built by clearing it and adding each path in turn.
|
||||
fn one_by_one(sel: &mut Selection, picked: &[Pick]) {
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(*id);
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection built with one `Selection::set` call, as the command builds it.
|
||||
fn one_call(sel: &mut Selection, picked: &[Pick]) {
|
||||
sel.set(picked.iter().map(|(id, _)| *id));
|
||||
for (id, a) in picked {
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// An open subpath of [`ANCHORS`] corner anchors 10 pt apart along row `row`.
|
||||
fn row(row: usize) -> SubPath {
|
||||
let y = row as f64 * 20.0;
|
||||
SubPath::new((0..ANCHORS).map(|i| Anchor::corner(Point::new(i as f64 * 10.0, y))).collect(), false)
|
||||
}
|
||||
|
||||
/// A session with the paths in `paths` and every anchor of theirs but the two ends of each
|
||||
/// subpath direct-selected (a path with all its anchors selected counts as selected whole).
|
||||
fn fixture(paths: Vec<PathData>) -> Session {
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let l = doc.layers.first().map(|l| l.id);
|
||||
let mut items = vec![];
|
||||
for pd in paths {
|
||||
let id = doc.alloc_id();
|
||||
let refs: Vec<[usize; 2]> =
|
||||
pd.subpaths.iter().enumerate().flat_map(|(si, sp)| (1..sp.anchors.len().saturating_sub(1)).map(move |ai| [si, ai])).collect();
|
||||
doc.insert(l, usize::MAX, Node::path(id, pd, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
items.push(json!({"id": id.0, "anchors": refs}));
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(doc, None);
|
||||
exec(&mut s, "select.anchorsMany", json!({"items": items}));
|
||||
s
|
||||
}
|
||||
|
||||
/// The cut ends the command selects, in the order it selects them: read back from the selection it
|
||||
/// leaves, which holds each cut path once in that order.
|
||||
fn picked_after_cut(s: &Session) -> Vec<Pick> {
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
sel.objects.iter().flat_map(|id| sel.anchors[id].iter().map(move |a| (*id, *a))).collect()
|
||||
}
|
||||
|
||||
fn bench(name: &str, paths: impl Fn() -> Vec<PathData>) {
|
||||
let mut s = fixture(paths());
|
||||
exec(&mut s, "path.cutAtAnchors", json!({}));
|
||||
let picked = picked_after_cut(&s);
|
||||
let mut start = Selection::default();
|
||||
one_by_one(&mut start, &[(NodeId(u64::MAX), (0, 3))]);
|
||||
let (mut a, mut b) = (start.clone(), start.clone());
|
||||
one_by_one(&mut a, &picked);
|
||||
one_call(&mut b, &picked);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
assert_eq!(b, s.doc().unwrap().selection, "the command gives that selection");
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
for i in 0..iters() {
|
||||
let run = |f: Rebuild, out: &mut Vec<f64>| {
|
||||
let ms = measure(|| {
|
||||
for _ in 0..REPS {
|
||||
let mut sel = start.clone();
|
||||
f(&mut sel, black_box(&picked));
|
||||
black_box(&sel);
|
||||
}
|
||||
});
|
||||
out.push(ms / REPS as f64);
|
||||
};
|
||||
if i % 2 == 0 {
|
||||
run(one_by_one, &mut old);
|
||||
run(one_call, &mut new);
|
||||
} else {
|
||||
run(one_call, &mut new);
|
||||
run(one_by_one, &mut old);
|
||||
}
|
||||
}
|
||||
let (old, new) = (median(old), median(new));
|
||||
println!(" {name:<44} {:>7} {:>6} {old:>12.3} {new:>12.3} {:>8.1}x", picked.len(), b.objects.len(), old / new);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
|
||||
println!(" {:<44} {:>7} {:>6} {:>12} {:>12} {:>9}", "document", "picked", "ids", format!("add, {unit}"), format!("set, {unit}"), "speedup");
|
||||
for n in [500, 2_000, 5_000] {
|
||||
bench(&format!("{n} open paths, {ANCHORS} anchors each"), || (0..n).map(|i| PathData::single(row(i))).collect());
|
||||
}
|
||||
bench("one path of 2,000 open subpaths", || vec![PathData::new((0..2_000).map(row).collect())]);
|
||||
let whole: Vec<f64> = (0..iters())
|
||||
.map(|_| {
|
||||
let mut s = fixture((0..2_000).map(|i| PathData::single(row(i))).collect());
|
||||
measure(|| drop(black_box(exec(&mut s, "path.cutAtAnchors", json!({})))))
|
||||
})
|
||||
.collect();
|
||||
println!(" path.cutAtAnchors, 2,000 open paths, whole command: {:.3} {unit}", median(whole));
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example direction_handles_bench` prints the time
|
||||
//! Select › Object › Direction Handles takes to select every path of documents of 2,000, 10,000 and
|
||||
//! 20,000 rectangles, spread over two layers with one group. For each size it times, on the same
|
||||
//! paths and anchors, the selection built one path at a time (a clear, then an add per path) and
|
||||
//! the selection built with one `Selection::set` call, checks that the two are equal, and then
|
||||
//! times the whole `select.object.directionHandles` command.
|
||||
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
|
||||
//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
|
||||
//! row is the median in ms. A run of the two selection rows repeats the selection 1,000,000 / paths
|
||||
//! times and gives the time of one.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::DocBuilder;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7)
|
||||
}
|
||||
|
||||
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
|
||||
fn ms(f: impl FnOnce()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), Instant::now());
|
||||
f();
|
||||
match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f64>) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// `n` 10 pt squares: a tenth of them in one group and the rest loose, half on each of two layers.
|
||||
fn document(n: usize) -> Document {
|
||||
let mut b = DocBuilder::new(4000.0, 4000.0);
|
||||
let square = |b: &mut DocBuilder, i: usize| {
|
||||
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
|
||||
b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
|
||||
};
|
||||
let grouped = n / 10;
|
||||
let kids = (0..grouped).map(|i| square(&mut b, i)).collect();
|
||||
b.group(kids, false);
|
||||
for i in grouped..n {
|
||||
if i == n / 2 {
|
||||
b.layer("Layer 2");
|
||||
}
|
||||
let node = square(&mut b, i);
|
||||
b.add(node);
|
||||
}
|
||||
b.build()
|
||||
}
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects `items` with one `Selection::set` call and one extend of the anchors.
|
||||
fn with_set(sel: &mut Selection, items: Items) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<44} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
fn bench(n: usize) {
|
||||
println!("{n} paths");
|
||||
let mut s = Session::new();
|
||||
s.add_document(document(n), None);
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let start = s.doc().unwrap().selection.clone();
|
||||
s.execute("select.object.directionHandles", &json!({})).unwrap();
|
||||
let command = s.doc().unwrap().selection.clone();
|
||||
// The paths and anchors the command selects, in its order.
|
||||
let items: Items = command.objects.iter().map(|id| (*id, command.anchors[id].clone())).collect();
|
||||
assert_eq!(items.len(), n);
|
||||
|
||||
// Each run selects `reps` times, on copies made before the clock starts, and gives the time of one.
|
||||
let reps = (1_000_000 / n).max(1);
|
||||
let time = |f: fn(&mut Selection, Items)| -> (f64, Selection) {
|
||||
let mut last = Selection::default();
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut work: Vec<(Selection, Items)> = (0..reps).map(|_| (start.clone(), items.clone())).collect();
|
||||
let t = ms(|| {
|
||||
for (sel, it) in &mut work {
|
||||
f(sel, black_box(std::mem::take(it)));
|
||||
}
|
||||
});
|
||||
last = work.pop().unwrap().0;
|
||||
t / reps as f64
|
||||
})
|
||||
.collect();
|
||||
(median(runs), last)
|
||||
};
|
||||
let (old, a) = time(one_by_one);
|
||||
let (new, b) = time(with_set);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
let mut want = start.clone();
|
||||
with_set(&mut want, items.clone());
|
||||
assert_eq!(want.objects, command.objects);
|
||||
assert_eq!(want.anchors, command.anchors);
|
||||
row("selection, one add per path", old);
|
||||
row("selection, one set call", new);
|
||||
println!(" {:<44} {:>10.1}x", "ratio", old / new);
|
||||
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
ms(|| drop(black_box(s.execute("select.object.directionHandles", &json!({})).unwrap())))
|
||||
})
|
||||
.collect();
|
||||
row("select.object.directionHandles, whole command", median(runs));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
|
||||
for n in [2_000, 10_000, 20_000] {
|
||||
bench(n);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
//! be edited, selected or not. What it removes is worked out by
|
||||
//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
@@ -100,20 +102,21 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
compounds.dedup();
|
||||
let mut beside = Beside::replacing(d, &trimmed);
|
||||
let mut all = vec![];
|
||||
// The selection is read through a set and changed once at the end, so a trim of many
|
||||
// paths does not go through the selected objects once per path and per piece.
|
||||
let mut selected_ids: HashSet<NodeId> = sel.objects.iter().copied().collect();
|
||||
let mut joining: Vec<NodeId> = vec![];
|
||||
let mut gone: Vec<NodeId> = vec![];
|
||||
for (id, pieces) in plan {
|
||||
let selected = sel.contains(id);
|
||||
let selected = selected_ids.contains(&id);
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
let made = replace_with_pieces(d, &mut beside, id, pieces)?;
|
||||
// The pieces of a selected path are selected; what was not selected stays so.
|
||||
if made.is_empty() {
|
||||
sel.remove(id);
|
||||
gone.push(id);
|
||||
} else if selected {
|
||||
for n in &made {
|
||||
if !sel.contains(*n) {
|
||||
sel.add(*n);
|
||||
}
|
||||
}
|
||||
joining.extend(made.iter().copied().filter(|n| selected_ids.insert(*n)));
|
||||
}
|
||||
all.extend(made);
|
||||
}
|
||||
@@ -121,9 +124,15 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for c in compounds {
|
||||
if d.node(c).is_some_and(|n| n.children().is_some_and(|ch| ch.is_empty())) {
|
||||
d.remove(c)?;
|
||||
sel.remove(c);
|
||||
gone.push(c);
|
||||
}
|
||||
}
|
||||
sel.remove_all(gone);
|
||||
if let Some((first, rest)) = joining.split_first() {
|
||||
// `add` clears what any change to the object selection clears; the rest are new ids.
|
||||
sel.add(*first);
|
||||
sel.objects.extend_from_slice(rest);
|
||||
}
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "removed": removed }))
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! one undo step, and what takes no part.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
use vectorcraft_tools::addons::trim::plan::{self, Limits, Stretches};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -420,6 +421,139 @@ fn the_selection_stays_as_it_was_and_the_pieces_of_a_selected_path_are_selected(
|
||||
assert!(s.doc().unwrap().selection.is_empty(), "a removed path leaves the selection");
|
||||
}
|
||||
|
||||
/// Run the command with `p`, and check that it leaves the selection exactly as changing it one
|
||||
/// id at a time does: for each trimmed path in the plan's order, its anchors and segments let go,
|
||||
/// a path with no pieces left removed, and each piece of a selected path added; then each emptied
|
||||
/// compound path removed. Returns the selection.
|
||||
fn same_selection_as_one_id_at_a_time(s: &mut Session, p: Value) -> Selection {
|
||||
let st = s.doc().unwrap();
|
||||
let pick = super::pick(&p).unwrap();
|
||||
let root = crate::cmd::ordinary_isolation(st);
|
||||
let plan: Vec<(NodeId, usize)> =
|
||||
plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).unwrap().into_iter().map(|t| (t.id, t.pieces.len())).collect();
|
||||
let mut compounds: Vec<NodeId> = plan
|
||||
.iter()
|
||||
.filter_map(|(id, _)| st.doc.parent_of(*id))
|
||||
.filter(|c| matches!(st.doc.node(*c).map(|n| &n.kind), Some(NodeKind::Compound { .. })))
|
||||
.collect();
|
||||
compounds.dedup();
|
||||
let mut want = st.selection.clone();
|
||||
let made = ids(&s.execute(TRIM, &p).unwrap());
|
||||
assert_eq!(made.len(), plan.iter().map(|(_, n)| n).sum::<usize>());
|
||||
let mut made = made.into_iter();
|
||||
for (id, n) in plan {
|
||||
let selected = want.contains(id);
|
||||
want.anchors.remove(&id);
|
||||
want.segments.remove(&id);
|
||||
let pieces: Vec<NodeId> = made.by_ref().take(n).collect();
|
||||
if pieces.is_empty() {
|
||||
want.remove(id);
|
||||
} else if selected {
|
||||
for piece in pieces {
|
||||
if !want.contains(piece) {
|
||||
want.add(piece);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
for c in compounds {
|
||||
if st.doc.node(c).is_none() {
|
||||
want.remove(c);
|
||||
}
|
||||
}
|
||||
want.prune(&st.doc);
|
||||
assert_eq!(st.selection, want);
|
||||
st.selection.clone()
|
||||
}
|
||||
|
||||
/// Two lines across split by a rectangle, one of them selected; a selected line nothing crosses
|
||||
/// and a selected compound path of two such lines, which the rectangle removes whole; and a
|
||||
/// selected line elsewhere with an anchor and a segment direct-selected. Returns (the selected
|
||||
/// line across, the line removed whole, the compound path, the line elsewhere).
|
||||
fn trim_scene(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
|
||||
let (h, ..) = across_and_uprights(s);
|
||||
line(s, &[(0.0, 120.0), (300.0, 120.0)], false);
|
||||
let alone = line(s, &[(145.0, 200.0), (155.0, 200.0)], false);
|
||||
let c1 = line(s, &[(145.0, 170.0), (155.0, 170.0)], false);
|
||||
let c2 = line(s, &[(145.0, 180.0), (155.0, 180.0)], false);
|
||||
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let elsewhere = line(s, &[(0.0, 250.0), (10.0, 250.0), (20.0, 250.0)], false);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0, alone.0, compound.0]})).unwrap();
|
||||
s.edit("direct", |_, sel| {
|
||||
sel.anchors.insert(elsewhere, [(0, 1)].into());
|
||||
sel.anchors.insert(h, [(0, 0)].into());
|
||||
sel.segments.insert(elsewhere, [(0, 0)].into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(h, alone, compound, elsewhere)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_after_a_trim_is_the_one_changing_it_one_id_at_a_time_gives() {
|
||||
// A removed key object stops being the key.
|
||||
let mut s = session();
|
||||
let (h, alone, compound, elsewhere) = trim_scene(&mut s);
|
||||
s.edit("key", |_, sel| {
|
||||
sel.key = Some(alone);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
|
||||
assert_eq!(sel.key, None);
|
||||
assert!(!sel.contains(alone) && !sel.contains(compound));
|
||||
assert_eq!(&sel.objects[..2], [elsewhere, h]);
|
||||
assert_eq!(sel.objects.len(), 3, "{:?}", sel.objects);
|
||||
assert!(sel.anchors.contains_key(&elsewhere) && sel.segments.contains_key(&elsewhere) && !sel.anchors.contains_key(&h));
|
||||
// A key object that keeps its first piece stays the key.
|
||||
let mut s = session();
|
||||
let (h, alone, compound, _) = trim_scene(&mut s);
|
||||
s.edit("key", |_, sel| {
|
||||
sel.key = Some(h);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
|
||||
assert_eq!(sel.key, Some(h));
|
||||
assert!(!sel.contains(alone) && !sel.contains(compound));
|
||||
// Trimming only paths that are not selected leaves a targeted object targeted.
|
||||
let mut s = session();
|
||||
let (h, _, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
|
||||
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), Some(elsewhere)));
|
||||
assert!(exists(&s, h));
|
||||
// A selected path that gains a piece changes the object selection, which lets go of the target.
|
||||
let mut s = session();
|
||||
let (h, _, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
|
||||
assert_eq!((sel.objects.len(), sel.target), (3, None));
|
||||
// So does a selected path that is removed whole.
|
||||
let mut s = session();
|
||||
let (_, alone, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, alone.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 190, 20, 20]}));
|
||||
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_paths_far_from_the_trimmed_one_cost_no_crossing_search() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -57,6 +57,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.circleThroughPoints",
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line),
|
||||
cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral),
|
||||
cmd!(
|
||||
@@ -131,14 +140,21 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr
|
||||
/// [`add_look`] that selects the new object only when `select` is set; otherwise the selection
|
||||
/// stays as it was.
|
||||
pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>, select: bool) -> Result<Value> {
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0)
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0, true)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page):
|
||||
/// its bounding box turns with it, as after the Rotate tool.
|
||||
fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation))
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation), true)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object whose geometry must stay where it was computed: it is not
|
||||
/// pixel-aligned, even while the document's Align New Objects to Pixel Grid is on.
|
||||
fn add_art_unaligned(s: &mut Session, label: &str, kind: NodeKind) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
insert_look_turned(s, label, kind, look, None, true, 0.0, false)
|
||||
}
|
||||
|
||||
/// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it)
|
||||
@@ -162,8 +178,10 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or
|
||||
/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on.
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. With `align`, a new
|
||||
/// path or compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is
|
||||
/// on.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn insert_look_turned(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
@@ -172,6 +190,7 @@ fn insert_look_turned(
|
||||
name: Option<String>,
|
||||
select: bool,
|
||||
bbox_angle: f64,
|
||||
align: bool,
|
||||
) -> Result<Value> {
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let mode = s.draw_mode;
|
||||
@@ -181,7 +200,9 @@ fn insert_look_turned(
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::new(id, kind);
|
||||
look.apply(d, &mut n);
|
||||
super::object::align_new_object(d, &mut n);
|
||||
if align {
|
||||
super::object::align_new_object(d, &mut n);
|
||||
}
|
||||
n.name = name;
|
||||
n.bbox_angle = bbox_angle;
|
||||
let mut into = None;
|
||||
@@ -390,6 +411,71 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
|
||||
}
|
||||
|
||||
/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
|
||||
/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
|
||||
};
|
||||
let [a, b, c] = points;
|
||||
let (center, radius) = shapes::circle_through(a, b, c)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays through the points.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
|
||||
fn three_points(v: &Value) -> Option<[Point; 3]> {
|
||||
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
|
||||
_ => None,
|
||||
};
|
||||
match v.as_array().map(Vec::as_slice) {
|
||||
Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The positions of the selected anchor points, when there are exactly three. They are counted as
|
||||
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
|
||||
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
|
||||
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
|
||||
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
|
||||
fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
|
||||
let st = s.doc()?;
|
||||
if st.selection.segments.values().any(|set| !set.is_empty()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut points = Vec::with_capacity(4);
|
||||
for id in &st.selection.objects {
|
||||
let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { return Ok(None) };
|
||||
match st.selection.anchors.get(id) {
|
||||
Some(set) => {
|
||||
for &(si, ai) in set.iter().take(4) {
|
||||
let Some(a) = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)) else { return Ok(None) };
|
||||
points.push(a.p);
|
||||
}
|
||||
}
|
||||
None => points.extend(pd.anchors().take(4).map(|(_, _, a)| a.p)),
|
||||
}
|
||||
if points.len() > 3 {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(match points.as_slice() {
|
||||
&[a, b, c] => Some([a, b, c]),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
|
||||
/// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default.
|
||||
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
@@ -651,7 +737,7 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
s.paint.stroke_width.max(0.1),
|
||||
);
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
|
||||
}
|
||||
|
||||
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
|
||||
@@ -831,7 +917,8 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Lays the text out (and sizes an Auto Size frame).
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
}
|
||||
let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?;
|
||||
let made =
|
||||
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?;
|
||||
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
|
||||
let made = super::typecmd::with_bounds(s, id, made);
|
||||
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, TextKind};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, Selection, TextKind};
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
@@ -495,16 +495,17 @@ fn direction_handles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let total: usize = items.iter().map(|x| x.1.len()).sum();
|
||||
s.select(|_, sel| {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| select_anchors(sel, items))?;
|
||||
Ok(json!({ "anchors": total }))
|
||||
}
|
||||
|
||||
/// Replaces `sel` with the paths of `items` in order, each once, and direct-selects the anchors
|
||||
/// listed with each path. A path listed twice keeps its first place and its last anchor set.
|
||||
fn select_anchors(sel: &mut Selection, items: Vec<(NodeId, BTreeSet<(usize, usize)>)>) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.save";
|
||||
let st = s.doc()?;
|
||||
@@ -1026,3 +1027,6 @@ fn close_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({ "closed": n }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The selection that Select ▸ Object ▸ Direction Handles builds.
|
||||
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{NodeId, Selection, SymbolPart};
|
||||
|
||||
use super::select_anchors;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set, as one left by earlier selecting.
|
||||
fn busy() -> Selection {
|
||||
let mut sel = Selection::default();
|
||||
sel.set([NodeId(90), NodeId(91)]);
|
||||
sel.anchors.insert(NodeId(90), BTreeSet::from([(0, 0)]));
|
||||
sel.segments.insert(NodeId(91), BTreeSet::from([(0, 1)]));
|
||||
sel.key = Some(NodeId(91));
|
||||
sel.target = Some(NodeId(92));
|
||||
sel.slices = vec![NodeId(93)];
|
||||
sel.guides = vec![NodeId(94)];
|
||||
sel.key_guide = Some(NodeId(94));
|
||||
sel.key_anchor = Some((NodeId(90), (0, 0)));
|
||||
sel.symbol_part = Some(SymbolPart { instance: NodeId(95), path: vec![0, 1] });
|
||||
sel.on_path_member = Some(NodeId(96));
|
||||
sel.new_art = Arc::new(HashSet::from([NodeId(97)]));
|
||||
sel
|
||||
}
|
||||
|
||||
fn refs(n: usize) -> BTreeSet<(usize, usize)> {
|
||||
(0..n).map(|i| (0, i)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_anchors_gives_the_selection_one_by_one_selecting_gives() {
|
||||
let cases: Vec<Items> = vec![
|
||||
vec![],
|
||||
vec![(NodeId(1), refs(4))],
|
||||
(1..=500).map(|i| (NodeId(i), refs(4))).collect(),
|
||||
// A path listed again keeps its first place and its last anchors.
|
||||
vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2)), (NodeId(2), BTreeSet::new()), (NodeId(1), refs(3))],
|
||||
];
|
||||
for items in cases {
|
||||
for start in [Selection::default(), busy()] {
|
||||
let (mut want, mut got) = (start.clone(), start);
|
||||
one_by_one(&mut want, items.clone());
|
||||
select_anchors(&mut got, items.clone());
|
||||
assert_eq!(got, want, "{items:?}");
|
||||
}
|
||||
}
|
||||
let mut got = busy();
|
||||
select_anchors(&mut got, vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2))]);
|
||||
assert_eq!(got.objects, vec![NodeId(3), NodeId(1)]);
|
||||
assert_eq!(got.anchors[&NodeId(3)], refs(2));
|
||||
assert!(got.segments.is_empty() && got.slices.is_empty() && got.guides.is_empty());
|
||||
assert_eq!((got.key, got.target, got.key_guide, got.key_anchor, got.on_path_member), (None, None, None, None, None));
|
||||
assert!(got.symbol_part.is_none());
|
||||
assert_eq!(*got.new_art, HashSet::from([NodeId(97)]), "selecting leaves the new-art list alone");
|
||||
}
|
||||
@@ -399,9 +399,7 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<Value> {
|
||||
let compound = |n: &Node| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. });
|
||||
let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound)));
|
||||
let found: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
super::select::select_where(s, "document.find", p, |d, n| {
|
||||
found.contains(&n.id) && (members || !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
})
|
||||
super::select::select_where(s, "document.find", p, |_, n, parent| found.contains(&n.id) && (members || !parent.is_some_and(compound)))
|
||||
}
|
||||
|
||||
/// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed
|
||||
|
||||
@@ -1040,7 +1040,8 @@ impl RasterBudget {
|
||||
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
/// the member's new id. `Err` when such a member still holds a random Transform effect after the
|
||||
/// raster budget left part of it as it is: its new ids would give that effect another seed.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
@@ -1051,7 +1052,7 @@ fn expand_pieces(
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
) -> std::result::Result<std::collections::HashMap<NodeId, Vec<Listed>>, OverBudget> {
|
||||
let id = m.id;
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = std::collections::HashMap::new();
|
||||
@@ -1065,7 +1066,12 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes, skip, raster));
|
||||
let left = raster.left;
|
||||
let expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
if raster.left > left && has_seeded(c) {
|
||||
return Err(OverBudget);
|
||||
}
|
||||
listed = Some(expanded);
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
@@ -1086,7 +1092,7 @@ fn expand_pieces(
|
||||
expanded.insert(c.id, listed);
|
||||
}
|
||||
}
|
||||
expanded
|
||||
Ok(expanded)
|
||||
}
|
||||
|
||||
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
|
||||
@@ -1301,6 +1307,19 @@ fn carries_copies(n: &Node) -> bool {
|
||||
is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len()
|
||||
}
|
||||
|
||||
/// Does `n`, something in it, or the art of the symbol it places when a color adjustment makes it
|
||||
/// that art, hold a random Transform effect ([`has_seeded`])? The raster budget can then leave `n`
|
||||
/// as it is after part of it expanded ([`expand_pieces`], Crop Marks).
|
||||
fn holds_seeded(d: &Document, n: &Node) -> bool {
|
||||
has_seeded(n)
|
||||
|| match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if effects::has_adjustment(n) => {
|
||||
d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| has_seeded(&s.art))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
@@ -1331,12 +1350,22 @@ fn expanded_node(
|
||||
_ => None,
|
||||
};
|
||||
// The embedded images before the adjustment and the expansions of the copies
|
||||
// ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the
|
||||
// recolored copies and the images those add then go again.
|
||||
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n))
|
||||
// ([`copies_carrying_raster`]) and of the members that hold a random Transform effect, when the
|
||||
// raster budget may yet leave `n` as it is: the recolored copies and the images those add then
|
||||
// go again.
|
||||
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n) || holds_seeded(d, &n))
|
||||
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
|
||||
// What the raster budget had left before those expansions: it gets back what they took.
|
||||
let budget_before = (raster.images, raster.pixels);
|
||||
// `n` stays as it is: `out` lists nothing of it, and the document and the raster budget lose
|
||||
// what expanding it added and took.
|
||||
let leave = |d: &mut Document, out: &mut Vec<Listed>, raster: &mut RasterBudget| {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = &images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
(raster.images, raster.pixels) = budget_before;
|
||||
};
|
||||
if effects::has_adjustment(&n)
|
||||
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
|
||||
{
|
||||
@@ -1352,14 +1381,21 @@ fn expanded_node(
|
||||
let container = is_container(&n);
|
||||
// Crop Marks: the object and its marks become a group. The object expands on its own first,
|
||||
// with `id`: the canvas draws it with that id, which Random in a Transform effect takes its
|
||||
// seed from. Then the object and the marks get ids of their own.
|
||||
// seed from. Then the object and the marks get ids of their own. When the raster budget leaves
|
||||
// a random Transform effect in the object, `n` stays as it is: new ids would give that effect
|
||||
// another seed.
|
||||
if let Some(mut m) = effects::crop_marks_art(&n) {
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = vec![];
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
let left = raster.left;
|
||||
expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
if raster.left > left && has_seeded(c) {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
}
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1390,16 +1426,13 @@ fn expanded_node(
|
||||
let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster);
|
||||
// Raster effects whose image would go past the budget stay: so does the object, with what is
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol), and
|
||||
// so does a group or layer whose copies keep a random Transform effect the budget left.
|
||||
// so does a group or layer whose copies or members keep a random Transform effect the budget
|
||||
// left.
|
||||
let Ok(image) = copies.and_then(|copied| {
|
||||
changed |= copied;
|
||||
raster_image(d, &n, raster)
|
||||
}) else {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
(raster.images, raster.pixels) = budget_before;
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
};
|
||||
let mut v = n.clone();
|
||||
@@ -1413,18 +1446,20 @@ fn expanded_node(
|
||||
image => {
|
||||
let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) {
|
||||
// A 3D effect on a group or layer, or on type: the shaded faces of its solids.
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
Ok::<_, OverBudget>(effects::expand_leaf(d, &v, &mut stroke_art))
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster));
|
||||
m
|
||||
})
|
||||
effects::evaluate_container(Some(&*d), &v)
|
||||
.map(|mut m| {
|
||||
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster)?);
|
||||
Ok(m)
|
||||
})
|
||||
.transpose()
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& !effects::has_transform_art(&v)
|
||||
&& !effects::has_transform_copies(&v)
|
||||
{
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
Ok(effects::expand_leaf(d, &v, &mut stroke_art))
|
||||
} else {
|
||||
// Type, images, symbol instances, live objects (and paths whose Transform effect copies
|
||||
// them, each copy an object of its own, or changes their fills and strokes): through
|
||||
@@ -1440,12 +1475,18 @@ fn expanded_node(
|
||||
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
|
||||
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
|
||||
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
|
||||
outlined.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
outlined
|
||||
.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster)?;
|
||||
Ok(m)
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let Ok(m) = m else {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
};
|
||||
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
|
||||
// expands in turn, to an image.
|
||||
|
||||
@@ -1189,3 +1189,90 @@ fn copies_the_raster_budget_leaves_keep_their_random_moves() {
|
||||
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
|
||||
}
|
||||
}
|
||||
|
||||
/// A group whose Transform effect copies its symbol instance, which has a drop shadow and a random
|
||||
/// Transform effect that takes its seed from the instance's id: each copy's instance has that id.
|
||||
/// When the raster budget has no image left for a copy's shadow, with none left or with one for the
|
||||
/// first copy's, the group stays as it is: the copies keep the ids their random moves are drawn
|
||||
/// with, the group draws as before, and the document holds no image the first copy's expansion
|
||||
/// made, nor the budget its charge. With the whole budget, the group expands and each object gets
|
||||
/// an id of its own.
|
||||
#[test]
|
||||
fn a_member_the_raster_budget_leaves_keeps_its_random_move() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
for images in [0, 1, 1_024] {
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(g).cloned().unwrap();
|
||||
assert!(effects::outer_effects(&before).len() == before.appearance.effects.len(), "the copies carry no shadow of the group's");
|
||||
let art = effects::evaluate_container(Some(&d), &before).unwrap();
|
||||
let mut instances = 0;
|
||||
art.walk(&mut |n| instances += usize::from(n.id == id && super::has_seeded(n)));
|
||||
assert!(instances >= 2, "{images}: each copy's instance has the id and its random effect: {instances}");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
|
||||
if images < 2 {
|
||||
assert!(budget.left > 0, "{images}: a shadow is left");
|
||||
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
|
||||
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
|
||||
assert!(draw(&d) == drawn, "{images}: the group draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
|
||||
} else {
|
||||
assert_eq!(budget.left, 0, "no shadow is left");
|
||||
assert!(!out.is_empty(), "the group expands");
|
||||
let (mut ids, mut count, mut seeded) = (std::collections::HashSet::new(), 0, false);
|
||||
d.node(g).unwrap().walk(&mut |n| {
|
||||
ids.insert(n.id);
|
||||
count += 1;
|
||||
seeded |= super::has_seeded(n);
|
||||
});
|
||||
assert_eq!(ids.len(), count, "each object has an id of its own");
|
||||
assert!(!seeded, "no random Transform effect is left");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object with Crop Marks, a drop shadow and a random Transform effect that takes its seed from
|
||||
/// the object's id stays as it is when the raster budget has no image left for its shadow: the
|
||||
/// object keeps its id and its random move, and draws as before.
|
||||
#[test]
|
||||
fn crop_marks_the_raster_budget_leaves_keep_their_random_move() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "cropMarks", "params": {}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(id).cloned().unwrap();
|
||||
assert!(effects::crop_marks_art(&before).is_some(), "the object has crop marks");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images: 0, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, id, &[], &mut out, &mut budget);
|
||||
assert!(budget.left > 0, "the shadow is left");
|
||||
assert!(out.is_empty(), "nothing expands: {out:?}");
|
||||
assert_eq!(d.node(id), Some(&before), "the object stays as it is");
|
||||
assert!(draw(&d) == drawn, "the object draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (0, u64::MAX), "the budget is as it was");
|
||||
}
|
||||
@@ -830,3 +830,78 @@ fn flattening_keeps_the_group_in_the_clipping_layer_when_the_layer_below_differs
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// #6861: Layer opacity, blend modes, sublayers with transparency, and empty transparent layers:
|
||||
/// PDF/X-1a, PDF/X-3, and PDF 1.3 automatically flatten and reduce transparency without failing,
|
||||
/// and the output contains no transparency dictionary or soft mask.
|
||||
#[test]
|
||||
fn pdfx_flattens_layer_and_sublayer_transparency() {
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200, "colorMode": "cmyk"}));
|
||||
|
||||
// Bottom layer: base artwork
|
||||
let _layer1 = s.doc().unwrap().doc.layers[0].id.0;
|
||||
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}}));
|
||||
|
||||
// Middle layer with 50% opacity and Multiply blend mode
|
||||
let layer2 = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 0.0, "m": 1.0, "y": 0.0, "k": 0.0}}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer2], "opacity": 50, "blendMode": "multiply"}));
|
||||
|
||||
// Sublayer inside layer2 with 70% opacity
|
||||
let sublayer = run(&mut s, "layer.newSublayer", json!({"parent": layer2}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 60, "y": 60, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 0.0, "m": 0.0, "y": 1.0, "k": 0.0}}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [sublayer], "opacity": 70}));
|
||||
|
||||
// Empty layer with opacity (must not leave /CA or /ca in output)
|
||||
let empty_layer = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "transparency.set", json!({"ids": [empty_layer], "opacity": 40}));
|
||||
|
||||
for standard in ["pdfX1a", "pdfX3"] {
|
||||
let (text, warnings) = pdf(&mut s, json!({"standard": standard}));
|
||||
assert!(text.starts_with("%PDF-1.3"), "{standard}");
|
||||
assert!(warnings.iter().any(|w| w.contains("flattened")), "{standard}: expected flattening warning");
|
||||
for no in ["/SMask", "/S/Transparency", "/ca ", "/CA "] {
|
||||
assert!(!text.contains(no), "{standard}: forbidden token '{no}' found in text:\n{text}");
|
||||
}
|
||||
// Verify it can be imported back and renders artwork
|
||||
let v = s.execute("document.exportPdf", &json!({"standard": standard})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let imported = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
assert!(!imported.layers.is_empty());
|
||||
let rendered = drawn(&imported);
|
||||
let non_white = rendered.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().any(|c| *c < 240)).count();
|
||||
assert!(non_white > 1000, "{standard}: flattened artwork failed to render, only {non_white} pixels");
|
||||
}
|
||||
|
||||
// PDF 1.3 export with compatibility: 1.3
|
||||
let (text, warnings) = pdf(&mut s, json!({"compatibility": "1.3", "preserveEditing": false}));
|
||||
assert!(text.starts_with("%PDF-1.3"));
|
||||
assert!(warnings.iter().any(|w| w.contains("flattened")));
|
||||
for no in ["/SMask", "/S/Transparency", "/ca ", "/CA "] {
|
||||
assert!(!text.contains(no), "PDF 1.3: forbidden token '{no}' found in text");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_outlining_does_not_wrap_layer_transparency_into_groups() {
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let layer1 = s.doc().unwrap().doc.layers[0].id.0;
|
||||
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer1], "opacity": 60}));
|
||||
|
||||
let o = crate::cmd::FlattenOptions { text_to_outlines: true, ..Default::default() };
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let flattened = crate::cmd::flatten::flatten_expanded(&doc, &o).unwrap();
|
||||
let resulting_doc = flattened.as_ref().unwrap_or(&doc);
|
||||
assert_eq!(resulting_doc.layers.len(), 1);
|
||||
let l = &resulting_doc.layers[0];
|
||||
assert_eq!(l.opacity, 0.6);
|
||||
assert!(!matches!(l.children().unwrap()[0].kind, vectorcraft_doc::NodeKind::Group { .. }));
|
||||
}
|
||||
@@ -5,8 +5,8 @@ use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po,
|
||||
separate, shape_node, shapes, unique_key,
|
||||
Knockout, MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes,
|
||||
planes_cmyk, po, separate, shape_node, shapes, unique_key,
|
||||
};
|
||||
|
||||
// ---------- plan ----------
|
||||
@@ -756,27 +756,140 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Opt
|
||||
Ok(flatten_expanded(expanded.as_ref().unwrap_or(doc), o)?.or(expanded))
|
||||
}
|
||||
|
||||
fn has_layer_container_transparency(n: &Node) -> bool {
|
||||
!n.has_default_transparency() || n.children().into_iter().flatten().any(|c| c.is_layer() && has_layer_container_transparency(c))
|
||||
}
|
||||
|
||||
/// [`flatten_document`] for `doc` whose pattern tile images were expanded already
|
||||
/// ([`expand_transparent_tile_images`]).
|
||||
pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> {
|
||||
let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints;
|
||||
if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut roots = vec![];
|
||||
for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
|
||||
let children = l.children().map_or(&[][..], Vec::as_slice);
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(doc, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
let needs_flatten = outlining
|
||||
|| doc.layers.iter().any(|l| {
|
||||
(o.no_transparency.is_some() && has_layer_container_transparency(l)) || o.shows_transparency(doc, l) || o.draws_see_through_image(l)
|
||||
});
|
||||
if !needs_flatten {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
let changed = o.no_transparency.is_some() && normalize_layer_transparency(&mut d, o);
|
||||
let mut roots = vec![];
|
||||
for l in d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
|
||||
let children = l.children().map_or(&[][..], Vec::as_slice);
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(&d, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
if changed {
|
||||
if o.no_transparency.is_some() {
|
||||
for l in &mut d.layers {
|
||||
sanitize_container_transparency(Arc::make_mut(l));
|
||||
}
|
||||
}
|
||||
return Ok(Some(d));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
apply(&mut d, &mut vectorcraft_doc::Selection::default(), plan, o)?;
|
||||
if o.no_transparency.is_some() {
|
||||
for l in &mut d.layers {
|
||||
sanitize_container_transparency(Arc::make_mut(l));
|
||||
}
|
||||
}
|
||||
Ok(Some(d))
|
||||
}
|
||||
|
||||
/// Flatten and normalize container-level transparency (on layers and sublayers) into groups
|
||||
/// so that the flattener's plan includes them and leaves no container transparency behind.
|
||||
fn normalize_layer_transparency(d: &mut Document, o: &FlattenOptions) -> bool {
|
||||
if o.no_transparency.is_none() {
|
||||
return false;
|
||||
}
|
||||
let mut changed = false;
|
||||
let mut layers = std::mem::take(&mut d.layers);
|
||||
for l in &mut layers {
|
||||
changed |= normalize_node_transparency(d, Arc::make_mut(l));
|
||||
}
|
||||
d.layers = layers;
|
||||
changed
|
||||
}
|
||||
|
||||
fn clear_transparency(n: &mut Node) {
|
||||
n.opacity = 1.0;
|
||||
n.blend = BlendMode::Normal;
|
||||
n.isolate = false;
|
||||
n.knockout = Knockout::Neutral;
|
||||
n.knockout_shape = false;
|
||||
n.extras_mut().mask = None;
|
||||
n.appearance = Appearance::default().into();
|
||||
}
|
||||
|
||||
fn normalize_node_transparency(d: &mut Document, n: &mut Node) -> bool {
|
||||
let mut changed = false;
|
||||
let is_layer = n.is_layer();
|
||||
let clips = n.clips();
|
||||
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.is_layer() {
|
||||
changed |= normalize_node_transparency(d, Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let has_transparency = !n.has_default_transparency() || n.shows_own_transparency();
|
||||
|
||||
if is_layer && has_transparency {
|
||||
let children = n.children().map_or(&[][..], Vec::as_slice);
|
||||
let (guides, art): (Vec<_>, Vec<_>) = children.iter().cloned().partition(|c| c.is_ruler_guide());
|
||||
|
||||
if art.is_empty() {
|
||||
clear_transparency(n);
|
||||
n.set_clips(false);
|
||||
changed = true;
|
||||
} else {
|
||||
let mut g = Node::group(d.alloc_id(), art);
|
||||
if clips {
|
||||
g.set_clips(true);
|
||||
}
|
||||
g.opacity = n.opacity;
|
||||
g.blend = n.blend;
|
||||
g.isolate = n.isolate;
|
||||
g.knockout = n.knockout;
|
||||
g.knockout_shape = n.knockout_shape;
|
||||
g.appearance = n.appearance.clone();
|
||||
g.extras_mut().mask = n.extras_mut().mask.take();
|
||||
|
||||
n.set_clips(false);
|
||||
clear_transparency(n);
|
||||
|
||||
let mut new_children = vec![Arc::new(g)];
|
||||
new_children.extend(guides);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = new_children;
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
} else if is_layer && !n.visible {
|
||||
clear_transparency(n);
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
fn sanitize_container_transparency(n: &mut Node) {
|
||||
if n.is_container() {
|
||||
clear_transparency(n);
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.is_container() {
|
||||
sanitize_container_transparency(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- apply ----------
|
||||
|
||||
pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan: Plan, o: &FlattenOptions) -> Result<(Vec<NodeId>, usize, usize)> {
|
||||
|
||||
@@ -92,7 +92,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => defaults,
|
||||
};
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let orientation = orientation_param(p, C, cur.orientation)?;
|
||||
let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine),
|
||||
_ => (Default::default(), 0.0, !create_spine.creates_spine()),
|
||||
@@ -364,29 +364,91 @@ fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec<NodeId>)> {
|
||||
|
||||
pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.options";
|
||||
let Some((_, cur, _)) = selected_spec(s) else {
|
||||
let id = crate::cmd::object_param(p, "id", C)?;
|
||||
let target = match id {
|
||||
Some(id) => {
|
||||
let doc = &s.doc()?.doc;
|
||||
match doc.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { .. }) if !doc.is_editable(id) => return Err(bad(C, "the object is hidden or locked")),
|
||||
Some(NodeKind::Blend { spec, children }) => Some((id, (**spec).clone(), children.iter().map(|c| c.id).collect())),
|
||||
_ => return Err(bad(C, "not a blend")),
|
||||
}
|
||||
}
|
||||
None => selected_spec(s),
|
||||
};
|
||||
let Some((_, cur, _)) = target else {
|
||||
if ["easingType", "ramp", "colorShift"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())) {
|
||||
return Err(bad(C, "select a blend to set easing or color shift"));
|
||||
}
|
||||
// Nothing to set them on: the options new blends start with (easing is per blend).
|
||||
let d = s.prefs.blend_options.unwrap_or_default();
|
||||
let spacing = spacing_param(p, C, d.spacing)?;
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d });
|
||||
let orientation = orientation_param(p, C, d.orientation)?;
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation, ..d });
|
||||
return Ok(json!({ "defaults": true }));
|
||||
};
|
||||
if gives_easing(p) && any_without_spine(s) {
|
||||
let no_spine = if id.is_some() { cur.no_spine } else { any_without_spine(s) };
|
||||
if gives_easing(p) && no_spine {
|
||||
return Err(bad(C, "the blend has no spine"));
|
||||
}
|
||||
// Every value is checked before anything changes. Each blend then takes only the values that
|
||||
// were given and keeps its own for the rest, so editing several blends does not copy the first
|
||||
// one's options onto the others.
|
||||
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
|
||||
let has_count = given("value") || given("steps") || given("distance");
|
||||
let has_spacing = given("spacing") || has_count || p.get("smooth").and_then(Value::as_bool) == Some(true);
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let orientation = orientation_param(p, C, cur.orientation)?;
|
||||
let ease = ease_param(p, C, cur.ease)?;
|
||||
let color_shift = percent_param(p, C, "colorShift", cur.color_shift, -100.0)?;
|
||||
edit_blends(s, "Blend Options", |_, spec| {
|
||||
spec.spacing = spacing;
|
||||
spec.orientation = orientation;
|
||||
spec.ease = ease;
|
||||
spec.color_shift = color_shift;
|
||||
})
|
||||
let (has_orientation, has_kind, has_ramp, has_shift) = (given("orientation"), given("easingType"), given("ramp"), given("colorShift"));
|
||||
let set = |spec: &mut BlendSpec| {
|
||||
// A spacing mode without a count keeps the count of a blend already in that mode.
|
||||
let same_mode = std::mem::discriminant(&spacing) == std::mem::discriminant(&spec.spacing);
|
||||
if has_spacing && (has_count || !same_mode) {
|
||||
spec.spacing = spacing;
|
||||
}
|
||||
if has_orientation {
|
||||
spec.orientation = orientation;
|
||||
}
|
||||
if has_kind {
|
||||
spec.ease.kind = ease.kind;
|
||||
}
|
||||
if has_ramp {
|
||||
spec.ease.ramp = ease.ramp;
|
||||
}
|
||||
if has_shift {
|
||||
spec.color_shift = color_shift;
|
||||
}
|
||||
};
|
||||
let targets = match id {
|
||||
Some(id) => vec![id],
|
||||
None => selected_of(s, is_blend),
|
||||
};
|
||||
let doc = &s.doc()?.doc;
|
||||
let changes = |b: &NodeId| match doc.node(*b).map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => {
|
||||
let mut next = (**spec).clone();
|
||||
set(&mut next);
|
||||
next != **spec
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if !targets.iter().any(changes) {
|
||||
return ok();
|
||||
}
|
||||
match id {
|
||||
Some(id) => {
|
||||
s.edit("Blend Options", |d, _| {
|
||||
if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
set(spec);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
None => edit_blends(s, "Blend Options", |_, spec| set(spec)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn blend_set_easing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blend Options…",
|
||||
["Object", "Blend"],
|
||||
None,
|
||||
"{spacing?: smooth|steps|distance, value?: n, steps?: n, distance?: pt, orientation?: page|path, smooth?: bool, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct} set the options of the selected blends; easingType chooses the distribution, ramp sets its strength (0..100; 0 = even), colorShift (-100..100; 0 = even) shifts colours independently of shape/position easing (omitted ones keep their value; out of range is an error); with no blend selected, the options new blends start with (spacing and orientation only; a tool setting, not an undo step) → {defaults?: true}",
|
||||
"{id?: id, spacing?: smooth|steps|distance, value?: n, steps?: n, distance?: pt, orientation?: page|path, smooth?: bool, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct} set the options of the selected blends (or of the blend `id` alone; a hidden or locked one is an error); easingType chooses the distribution, ramp sets its strength (0..100; 0 = even), colorShift (-100..100; 0 = even) shifts colours independently of shape/position easing (each blend keeps its own value for every option omitted; out of range is an error and changes nothing; no undo step when nothing changes); with no blend selected and no `id`, the options new blends start with (spacing and orientation only; a tool setting, not an undo step) → {defaults?: true}",
|
||||
always,
|
||||
blend_options
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::mesh::whole;
|
||||
use super::{
|
||||
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
|
||||
bad, check_numbers, has_selection, json, named_ids, selected_roots, str_param, switch_or,
|
||||
bad, check_numbers, has_selection, json, named_ids, selected_roots, switch_or, text_param,
|
||||
};
|
||||
|
||||
pub(super) fn ids_json(ids: &[NodeId]) -> Value {
|
||||
@@ -128,8 +128,11 @@ pub(super) fn spacing_param(p: &Value, cmd: &str, current: BlendSpacing) -> Resu
|
||||
let smooth = switch_or(p, "smooth", false, cmd)?;
|
||||
let num = |k: &str| p.get(k).and_then(Value::as_f64);
|
||||
let steps = |k: &str, n: f64| whole(n, k, cmd).map(|n| BlendSpacing::Steps(n as u32));
|
||||
let mode = str_param(p, "spacing");
|
||||
let mode = text_param(p, "spacing", cmd)?;
|
||||
let value = num("value");
|
||||
if mode.is_none() && value.is_some() {
|
||||
return Err(bad(cmd, "`value` needs `spacing` (steps|distance)"));
|
||||
}
|
||||
let sp = match mode {
|
||||
Some("smooth") | Some("smoothColor") => BlendSpacing::SmoothColor,
|
||||
Some("steps") => match value {
|
||||
@@ -157,11 +160,15 @@ pub(super) fn spacing_param(p: &Value, cmd: &str, current: BlendSpacing) -> Resu
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn orientation_param(p: &Value, current: BlendOrientation) -> BlendOrientation {
|
||||
match str_param(p, "orientation") {
|
||||
Some("path") | Some("alignToPath") => BlendOrientation::AlignToPath,
|
||||
Some("page") | Some("alignToPage") => BlendOrientation::AlignToPage,
|
||||
_ => current,
|
||||
/// `orientation`: `page` or `path`; missing or null keeps `current`, and any other value is an error.
|
||||
pub(super) fn orientation_param(p: &Value, cmd: &str, current: BlendOrientation) -> Result<BlendOrientation> {
|
||||
match p.get("orientation").filter(|v| !v.is_null()) {
|
||||
None => Ok(current),
|
||||
Some(v) => match v.as_str() {
|
||||
Some("path") | Some("alignToPath") => Ok(BlendOrientation::AlignToPath),
|
||||
Some("page") | Some("alignToPage") => Ok(BlendOrientation::AlignToPage),
|
||||
_ => Err(bad(cmd, "orientation must be page or path")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -153,6 +153,20 @@ fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTre
|
||||
fonts
|
||||
}
|
||||
|
||||
/// The document whose links are copied beside the placed file `name` (`bytes`), which is copied
|
||||
/// as it is: a `.ai` file's editing data ([`super::place::document::editing_data`]), or the native
|
||||
/// document an EPS or PostScript file carries, which placing it reads. `None` for other files and
|
||||
/// for data that can't be read.
|
||||
fn editing_data(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
if let Some(doc) = super::place::document::editing_data(name, bytes) {
|
||||
return Some(doc);
|
||||
}
|
||||
if !super::place::document::is_postscript(bytes) {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_format::load(&vectorcraft_eps::native(bytes)?).ok()
|
||||
}
|
||||
|
||||
/// Collect dependencies depth-first so nested VectorCraft files are rewritten before
|
||||
/// their parents: each parent can record the final hash of the rewritten child.
|
||||
/// Cycles, excessive nesting, and unreadable children are reported, not fatal.
|
||||
@@ -200,7 +214,7 @@ impl<'a> Collector<'a> {
|
||||
self.warnings.push(message);
|
||||
}
|
||||
|
||||
/// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the
|
||||
/// Warns when a file that placed `.ai` or EPS file `source` links (`name`) was copied as `copy`: the
|
||||
/// copy of `source` finds it only by its name, beside it.
|
||||
/// `path` is the link's path as the warning names it.
|
||||
fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) {
|
||||
@@ -213,8 +227,8 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects the files `doc` links. `by_name`: `doc` is a placed `.ai` file's editing data,
|
||||
/// whose links are not rewritten, so its copy finds them by name beside it. `lookup`: the
|
||||
/// Collects the files `doc` links. `by_name`: `doc` is a placed `.ai` or EPS file's editing
|
||||
/// data, whose links are not rewritten, so its copy finds them by name beside it. `lookup`: the
|
||||
/// document whose links (with the same paths as `doc`'s) are looked for, and where from, when
|
||||
/// not `doc` from `source`.
|
||||
fn collect(
|
||||
@@ -311,12 +325,13 @@ impl<'a> Collector<'a> {
|
||||
if by_name {
|
||||
self.renamed(&mut lines, source, &shown, &file.name, &destination_file);
|
||||
}
|
||||
// A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file
|
||||
// read from its editing data links are copied beside it.
|
||||
// A placed PDF, .ai or EPS file is copied as it is, as an image is; the files a .ai
|
||||
// file read from its editing data, or an EPS file read from the native document it
|
||||
// carries, links are copied beside it.
|
||||
let pages = placed.get(&file.path);
|
||||
let placed_file = pages.is_some();
|
||||
check_carried_scripts(&file.name, &bytes, found_path)?;
|
||||
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
|
||||
if placed_file && let Some(mut art) = editing_data(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
} else {
|
||||
|
||||
@@ -1874,20 +1874,85 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
cut.finish(d)?;
|
||||
// Each cut leaves one of its two coincident anchors selected, so a drag pulls the ends apart.
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(id);
|
||||
sel.anchors.entry(id).or_default().insert(a);
|
||||
}
|
||||
select_cut_ends(sel, &picked);
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(super::draw2::ids_json(&ids))
|
||||
}
|
||||
|
||||
/// Replaces the selection with the anchors in `picked`: each id once, in the order it first
|
||||
/// appears, with every anchor listed for it. An empty `picked` clears the selection.
|
||||
fn select_cut_ends(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) {
|
||||
sel.set(picked.iter().map(|(id, _)| *id));
|
||||
for (id, a) in picked {
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `select_cut_ends` by clearing the selection and adding each id in turn, kept as the
|
||||
/// reference the one-call version must match.
|
||||
fn select_cut_ends_one_by_one(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) {
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(*id);
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set, the art made since the last deselect included.
|
||||
fn busy_selection() -> Selection {
|
||||
Selection {
|
||||
objects: vec![NodeId(90), NodeId(91)],
|
||||
anchors: [(NodeId(90), [(0, 3)].into())].into(),
|
||||
segments: [(NodeId(91), [(0, 1)].into())].into(),
|
||||
key: Some(NodeId(90)),
|
||||
target: Some(NodeId(91)),
|
||||
slices: vec![NodeId(92)],
|
||||
guides: vec![NodeId(93)],
|
||||
key_guide: Some(NodeId(93)),
|
||||
key_anchor: Some((NodeId(90), (0, 3))),
|
||||
symbol_part: Some(vectorcraft_doc::SymbolPart { instance: NodeId(94), path: vec![0, 2] }),
|
||||
on_path_member: Some(NodeId(95)),
|
||||
new_art: Arc::new([NodeId(90), NodeId(97)].into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cut ends of open paths, of an opened closed path, of a path of several subpaths (one id
|
||||
/// with several anchors, first seen before other ids), long lists and an empty one give the
|
||||
/// same selection, every field, as clearing it and adding each id in turn.
|
||||
#[test]
|
||||
fn selecting_cut_ends_matches_adding_them_one_by_one() {
|
||||
let n = NodeId;
|
||||
let mut cases: Vec<Vec<(NodeId, (usize, usize))>> = vec![
|
||||
vec![],
|
||||
vec![(n(1), (0, 0)), (n(2), (0, 0))],
|
||||
vec![(n(5), (0, 0))],
|
||||
vec![(n(7), (0, 0)), (n(3), (1, 0)), (n(8), (0, 0)), (n(3), (2, 0)), (n(7), (0, 0)), (n(3), (0, 0))],
|
||||
];
|
||||
let mut rng = Lcg(11);
|
||||
for len in [50, 2_000] {
|
||||
cases.push((0..len).map(|_| (n(rng.below(300) + 1), (rng.below(4) as usize, 0))).collect());
|
||||
}
|
||||
for picked in &cases {
|
||||
for start in [Selection::default(), busy_selection()] {
|
||||
let (mut ours, mut theirs) = (start.clone(), start.clone());
|
||||
select_cut_ends(&mut ours, picked);
|
||||
select_cut_ends_one_by_one(&mut theirs, picked);
|
||||
assert_eq!(ours, theirs, "{picked:?}");
|
||||
assert_eq!(ours.new_art, start.new_art);
|
||||
}
|
||||
}
|
||||
let mut sel = busy_selection();
|
||||
select_cut_ends(&mut sel, &cases[3]);
|
||||
assert_eq!(sel.objects, [n(7), n(3), n(8)]);
|
||||
assert_eq!(sel.anchors[&n(3)].iter().collect::<Vec<_>>(), [&(0, 0), &(1, 0), &(2, 0)]);
|
||||
assert_eq!((sel.anchors.len(), sel.key, sel.target, sel.symbol_part.is_some()), (3, None, None, false));
|
||||
}
|
||||
|
||||
/// `merge_coincident` removing each merged anchor from the vector straight away, kept as the
|
||||
/// reference the one-pass version must match.
|
||||
fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize {
|
||||
|
||||
@@ -548,6 +548,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.toggle",
|
||||
"select.update",
|
||||
"shape.arc",
|
||||
"shape.circleThroughPoints",
|
||||
"shape.ellipse",
|
||||
"shape.flare",
|
||||
"shape.line",
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Setup",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks knock out; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
has_doc,
|
||||
setup
|
||||
),
|
||||
@@ -82,11 +82,38 @@ pub(crate) fn settings_over(cmd: &str, mut v: Value, p: &Value) -> Result<PrintS
|
||||
Some(over @ Value::Object(_)) => merge(&mut v, over),
|
||||
Some(_) => return Err(bad(cmd, "settings must be an object")),
|
||||
}
|
||||
link_scale(cmd, &mut v, p.get("settings").and_then(|s| s.get("scale")).filter(|s| s.is_object()))?;
|
||||
let set = PrintSettings::deserialize(&v).map_err(|e| bad(cmd, format!("print settings: {e}")))?;
|
||||
set.check().map_err(|e| pdf_error(cmd, e))?;
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// Keep the custom scale's width and height equal in the merged settings `v` while `scale.linked`
|
||||
/// is on, after `over` (the request's `scale`) was merged in: the one side the request gives sets
|
||||
/// the other, and otherwise the height takes the width (as turning the link on does). A request
|
||||
/// that gives a different width and height without a `linked` key turns the link off; with
|
||||
/// `linked: true`, or with `linked: null` over a linked scale, it is refused.
|
||||
fn link_scale(cmd: &str, v: &mut Value, over: Option<&Value>) -> Result<()> {
|
||||
let given = |k: &str| over.and_then(|o| o.get(k)).filter(|x| !x.is_null());
|
||||
let (width, height) = (given("width").cloned(), given("height").cloned());
|
||||
let apart = matches!((&width, &height), (Some(w), Some(h)) if w.as_f64() != h.as_f64());
|
||||
let Some(scale) = v.get_mut("scale").and_then(Value::as_object_mut) else { return Ok(()) };
|
||||
if apart && over.and_then(|o| o.get("linked")).is_none() {
|
||||
scale.insert("linked".into(), Value::Bool(false));
|
||||
}
|
||||
if scale.get("linked") != Some(&Value::Bool(true)) {
|
||||
return Ok(());
|
||||
}
|
||||
if apart {
|
||||
return Err(bad(cmd, "scale: give one percentage, or the same width and height, while scale.linked is on (linked: false scales them apart)"));
|
||||
}
|
||||
let (from, to) = if width.is_none() && height.is_some() { ("height", "width") } else { ("width", "height") };
|
||||
if let Some(value) = scale.get(from).cloned() {
|
||||
scale.insert(to.into(), value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn to_json(set: &PrintSettings) -> Result<Value> {
|
||||
serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
@@ -378,11 +378,12 @@ pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool)
|
||||
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
|
||||
/// that is its only visible raster effect and is its own (not a fill's or a stroke's): made of `n`
|
||||
/// without that effect and without its transparency, which stays on the object. When Transform
|
||||
/// effects after the Rasterize effect move its image ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
|
||||
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
|
||||
/// effects after the Rasterize effect move or copy its image ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// the image is made of the art before them once and placed by each of their maps, as the canvas
|
||||
/// draws it: with copies, a group of the placements with the lowest first. `None` otherwise, when
|
||||
/// those Transform effects flatten every placement, or when the image can't be made.
|
||||
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let (whole, r, map) = rasterize_effect_art(d, n)?;
|
||||
let (whole, r, maps) = rasterize_effect_art(d, n)?;
|
||||
let p = json!({
|
||||
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
|
||||
"colorModel": r.color_model.id(),
|
||||
@@ -395,33 +396,58 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// image's transparency would need one too; upgrade when CMYK images carry alpha.
|
||||
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
|
||||
let mut image = image.into_node(d);
|
||||
if let Some(map) = map {
|
||||
image.transform(map, false);
|
||||
match maps.as_deref() {
|
||||
None => Some(image),
|
||||
Some([map]) => {
|
||||
image.transform(*map, false);
|
||||
Some(image)
|
||||
}
|
||||
Some(maps) => {
|
||||
// Each placement is an object of its own on the one image's pixels.
|
||||
let placed: Vec<Arc<Node>> = maps
|
||||
.iter()
|
||||
.map(|map| {
|
||||
let mut copy = d.reid(&image);
|
||||
copy.transform(*map, false);
|
||||
Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
Some(Node::group(d.alloc_id(), placed))
|
||||
}
|
||||
}
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
|
||||
/// that move the image, without the Rasterize effect and without its transparency; that effect's
|
||||
/// options; and the map those Transform effects move the image by. `None` when `n` has another
|
||||
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
|
||||
/// flatten the image.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
|
||||
/// that move or copy the image, without the Rasterize effect and without its transparency; that
|
||||
/// effect's options; and the maps those Transform effects place the image by, the lowest first,
|
||||
/// without those that flatten it. `None` when `n` has another raster effect, when the Rasterize
|
||||
/// effect is not its own, or when those Transform effects flatten every placement.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Vec<Affine>>)> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
|
||||
let (stage, maps) = match vectorcraft_render::rasterize_stage(d, n) {
|
||||
Some((stage, maps)) => {
|
||||
let maps: Vec<Affine> = maps.into_iter().filter(|m| places(*m)).collect();
|
||||
if maps.is_empty() {
|
||||
return None;
|
||||
}
|
||||
(Some(stage), Some(maps))
|
||||
}
|
||||
None => (None, None),
|
||||
};
|
||||
let n = stage.as_ref().unwrap_or(n);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
Some((whole, r, map))
|
||||
Some((whole, r, maps))
|
||||
}
|
||||
|
||||
/// Does `map`, one of those a Rasterize image is placed by ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// place it? Not when it flattens it to a line or a point: the canvas draws nothing there.
|
||||
fn places(map: Affine) -> bool {
|
||||
let det = map.determinant();
|
||||
det.is_finite() && det.abs() > 1e-12
|
||||
}
|
||||
|
||||
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
|
||||
@@ -658,27 +684,32 @@ fn walk_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenReport)
|
||||
.then(|| nodes.iter().map(|n| walk(out, n, report).map(Arc::new).unwrap_or_else(|| n.clone())).collect())
|
||||
}
|
||||
|
||||
/// `n` as an image when its Rasterize image moves with the Transform effects after it
|
||||
/// ([`vectorcraft_render::rasterize_stage`]): the image is made of the art before those Transform
|
||||
/// effects and moved by them, as the canvas draws it, which baking the geometry effects first would
|
||||
/// lose. A map that flattens the image leaves an empty group, as the canvas draws nothing. Inside
|
||||
/// groups, layers and opacity masks, the members are looked at the same way. `None` when nothing in
|
||||
/// `n` changes; hidden objects and template layers stay as they are.
|
||||
/// `n` as an image when its Rasterize image moves with the Transform effects after it, or as a
|
||||
/// group of that image's placements when they copy it ([`vectorcraft_render::rasterize_stage`]):
|
||||
/// the image is made of the art before those Transform effects and placed by them, as the canvas
|
||||
/// draws it, which baking the geometry effects first would lose. Maps that flatten every placement
|
||||
/// leave an empty group, as the canvas draws nothing. Inside groups, layers and opacity masks, the
|
||||
/// members are looked at the same way. `None` when nothing in `n` changes; hidden objects and
|
||||
/// template layers stay as they are.
|
||||
fn staged(out: &mut Document, n: &Node, report: &mut FlattenReport) -> Option<Node> {
|
||||
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, map)) = vectorcraft_render::rasterize_stage(out, n) {
|
||||
if let Some((_, maps)) = vectorcraft_render::rasterize_stage(out, n) {
|
||||
let mut v = n.clone();
|
||||
strip_raster(&mut v, false);
|
||||
let det = map.determinant();
|
||||
if !(det.is_finite() && det.abs() > 1e-12) {
|
||||
if !maps.iter().any(|m| places(*m)) {
|
||||
v.appearance = Default::default();
|
||||
v.kind = NodeKind::Group { children: vec![], clip: false };
|
||||
return Some(v);
|
||||
}
|
||||
let image = raster_image(out, n, false, false)?;
|
||||
report.record(n, &image);
|
||||
// The placements share one image: its resolution is the first one's.
|
||||
let first = match &image.kind {
|
||||
NodeKind::Group { children, clip: false } => children.first().map_or(&image, |c| &**c),
|
||||
_ => &image,
|
||||
};
|
||||
report.record(n, first);
|
||||
let mut m = replace_with_image(v, image);
|
||||
staged_mask(out, &mut m, report);
|
||||
return Some(m);
|
||||
|
||||
@@ -308,24 +308,30 @@ pub(crate) fn selectable(d: &Document, iso: Option<NodeId>) -> Vec<NodeId> {
|
||||
/// them, leaving out every hidden or locked object with what it holds. `f` returns whether to
|
||||
/// visit the objects inside the one it is given.
|
||||
pub(crate) fn walk_selectable(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if n.visible && !n.locked && f(n) {
|
||||
walk_selectable_in(d, iso, |n, _| f(n));
|
||||
}
|
||||
|
||||
/// [`walk_selectable`], handing `f` each object with the node that holds it in the tree: its
|
||||
/// layer, sublayer, group or other container, or `None` for a top-level layer.
|
||||
fn walk_selectable_in(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
fn inside(n: &Node, parent: Option<&Node>, f: &mut impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
if n.visible && !n.locked && f(n, parent) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
inside(c, f);
|
||||
inside(c, Some(n), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn find(n: &Node, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node) -> bool) {
|
||||
fn find(n: &Node, parent: Option<&Node>, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
if tops.contains(&n.id) {
|
||||
return inside(n, f);
|
||||
return inside(n, parent, f);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
find(c, tops, f);
|
||||
find(c, Some(n), tops, f);
|
||||
}
|
||||
}
|
||||
let tops: BTreeSet<NodeId> = selectable(d, iso).into_iter().collect();
|
||||
for l in &d.layers {
|
||||
find(l, &tops, &mut f);
|
||||
find(l, None, &tops, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1098,7 +1104,9 @@ fn select_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "give `fill`, `stroke` or both"));
|
||||
}
|
||||
let reads_as = |paint: Paint, hex: Option<&str>| hex.is_none_or(|h| paint.color().is_some_and(|c| c.to_hex() == h));
|
||||
select_where(s, C, p, |d, n| paint_reported(d, n) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref()))
|
||||
select_where(s, C, p, |_, n, parent| {
|
||||
paint_reported(n, parent) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref())
|
||||
})
|
||||
}
|
||||
|
||||
/// The longest note, in bytes, that Select by Note searches for.
|
||||
@@ -1219,11 +1227,11 @@ fn fold_case(c: char) -> impl Iterator<Item = char> {
|
||||
c.to_lowercase().map(|l| if l == 'ς' { 'σ' } else { l })
|
||||
}
|
||||
|
||||
/// Does `document.inspect` report a fill and stroke for `n`? A compound path's are its own, though
|
||||
/// it holds its members, and its members report none.
|
||||
fn paint_reported(d: &Document, n: &Node) -> bool {
|
||||
/// Does `document.inspect` report a fill and stroke for `n`, held by `parent`? A compound path's
|
||||
/// are its own, though it holds its members, and its members report none.
|
||||
fn paint_reported(n: &Node, parent: Option<&Node>) -> bool {
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
|
||||
compound(n) || (!n.is_container() && !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
compound(n) || (!n.is_container() && !parent.is_some_and(compound))
|
||||
}
|
||||
|
||||
/// The object Select > Same compares the others with, and whether isolation mode is inside a
|
||||
@@ -1260,30 +1268,30 @@ fn same_fill(s: &mut Session, cmd: &str, eq: impl Fn(&Node, &Node) -> bool) -> R
|
||||
fn same_in(s: &mut Session, cmd: &str, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let (refn, members) = same_reference(st, cmd)?;
|
||||
let group = live_paint_group(&st.doc, refn.id);
|
||||
let group = live_paint_group(st.doc.parent_of(refn.id).and_then(|p| st.doc.node(p)));
|
||||
let refn = refn.clone();
|
||||
select_where(s, cmd, &json!({}), |d, n| {
|
||||
(!live_paint || live_paint_group(d, n.id) == group) && (if members { !n.is_container() } else { paint_reported(d, n) }) && eq(n, &refn)
|
||||
})
|
||||
select_where(s, cmd, &json!({}), |_, n, parent| same_candidate(n, parent, live_paint, group, members) && eq(n, &refn))
|
||||
}
|
||||
|
||||
/// The Live Paint group `id` is a face or edge of.
|
||||
fn live_paint_group(d: &Document, id: NodeId) -> Option<NodeId> {
|
||||
d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint))
|
||||
/// Whether Select > Same compares `n`, held by `parent`, with its reference: with `live_paint`, only
|
||||
/// when `n` is a face or edge of the Live Paint group `group` (or of none, for `None`); in
|
||||
/// isolation mode inside a compound path (`members`), any object that is not a container;
|
||||
/// otherwise one that [`paint_reported`] accepts.
|
||||
fn same_candidate(n: &Node, parent: Option<&Node>, live_paint: bool, group: Option<NodeId>, members: bool) -> bool {
|
||||
(!live_paint || live_paint_group(parent) == group) && (if members { !n.is_container() } else { paint_reported(n, parent) })
|
||||
}
|
||||
|
||||
/// The Live Paint group an object held by `parent` is a face or edge of.
|
||||
fn live_paint_group(parent: Option<&Node>) -> Option<NodeId> {
|
||||
parent.filter(|p| is_live_paint(p)).map(|p| p.id)
|
||||
}
|
||||
|
||||
/// Select the objects [`walk_selectable`] visits that `f` accepts (not looking inside accepted
|
||||
/// ones); Select > Reselect repeats `cmd` with `p`.
|
||||
pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Document, &Node) -> bool) -> Result<Value> {
|
||||
/// ones); `f` is given each object with the node that holds it. Select > Reselect repeats `cmd`
|
||||
/// with `p`.
|
||||
pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Document, &Node, Option<&Node>) -> bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut ids = vec![];
|
||||
walk_selectable(&st.doc, st.isolation, |n| {
|
||||
if f(&st.doc, n) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
let ids = matching(&st.doc, st.isolation, |n, parent| f(&st.doc, n, parent));
|
||||
let from = st.selection.objects.clone();
|
||||
s.select(|_, sel| sel.set(ids.iter().copied()))?;
|
||||
let st = s.doc_mut()?;
|
||||
@@ -1292,12 +1300,26 @@ pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Do
|
||||
Ok(json!({ "count": st.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// The objects [`walk_selectable`] visits that `f` accepts, in paint order, not looking inside
|
||||
/// accepted ones. `f` is given each object with the node that holds it.
|
||||
fn matching(d: &Document, iso: Option<NodeId>, f: impl Fn(&Node, Option<&Node>) -> bool) -> Vec<NodeId> {
|
||||
let mut ids = vec![];
|
||||
walk_selectable_in(d, iso, |n, parent| {
|
||||
if f(n, parent) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
ids
|
||||
}
|
||||
|
||||
fn same_graphic_style(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let cmd = "select.same.graphicStyle";
|
||||
let st = s.doc()?;
|
||||
let (refn, _) = same_reference(st, cmd)?;
|
||||
let id = super::style::linked_style(&st.doc, refn).map(|g| g.id).ok_or_else(|| bad(cmd, "the selection has no graphic style"))?;
|
||||
select_where(s, cmd, &json!({}), |d, n| n.extras().graphic_style == Some(id) && super::style::linked_style(d, n).is_some())
|
||||
select_where(s, cmd, &json!({}), |d, n, _| n.extras().graphic_style == Some(id) && super::style::linked_style(d, n).is_some())
|
||||
}
|
||||
|
||||
/// An appearance attribute Select > Same > Appearance Attribute matches.
|
||||
@@ -1321,7 +1343,7 @@ fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Attribute::Item(ap.items.iter().rev().find(|i| i.is_fill()).cloned().ok_or_else(|| bad(cmd, "the object has no fill, stroke or effect"))?)
|
||||
}
|
||||
};
|
||||
select_where(s, cmd, p, |_, n| match &attr {
|
||||
select_where(s, cmd, p, |_, n, _| match &attr {
|
||||
Attribute::Item(it) => n.appearance.items.contains(it),
|
||||
Attribute::Effect(e) => n.appearance.effects.iter().any(|x| x.id == e.id && x.params == e.params),
|
||||
})
|
||||
@@ -1381,5 +1403,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod same_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Select > Same and Select by Color through [`walk_selectable_in`], which hands each object the
|
||||
//! node that holds it, against copies of the walk and the tests that looked each object's parent up
|
||||
//! by its id.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::{fill_of, is_live_paint, matching, same_candidate, same_paint, same_reference, selectable, stroke_of, walk_selectable_in};
|
||||
use crate::Session;
|
||||
|
||||
/// `walk_selectable` as it was before it handed each object its parent.
|
||||
fn walk_by_id(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if n.visible && !n.locked && f(n) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
inside(c, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn find(n: &Node, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if tops.contains(&n.id) {
|
||||
return inside(n, f);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
find(c, tops, f);
|
||||
}
|
||||
}
|
||||
let tops: BTreeSet<NodeId> = selectable(d, iso).into_iter().collect();
|
||||
for l in &d.layers {
|
||||
find(l, &tops, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// `paint_reported` as it was, looking up `n`'s parent by its id.
|
||||
fn paint_reported_by_id(d: &Document, n: &Node) -> bool {
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
|
||||
compound(n) || (!n.is_container() && !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
}
|
||||
|
||||
/// `live_paint_group` as it was, looking up the parent of `id`.
|
||||
fn live_paint_group_by_id(d: &Document, id: NodeId) -> Option<NodeId> {
|
||||
d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint))
|
||||
}
|
||||
|
||||
/// The objects `select_where`'s loop took before the walk handed each object its parent.
|
||||
fn matching_by_id(d: &Document, iso: Option<NodeId>, f: impl Fn(&Document, &Node) -> bool) -> Vec<NodeId> {
|
||||
let mut ids = vec![];
|
||||
walk_by_id(d, iso, |n| {
|
||||
if f(d, n) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
ids
|
||||
}
|
||||
|
||||
/// The objects `same_in` took before the walk handed each object its parent.
|
||||
fn same_by_id(d: &Document, iso: Option<NodeId>, refn: &Node, members: bool, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Vec<NodeId> {
|
||||
let group = live_paint_group_by_id(d, refn.id);
|
||||
matching_by_id(d, iso, |d, n| {
|
||||
(!live_paint || live_paint_group_by_id(d, n.id) == group)
|
||||
&& (if members { !n.is_container() } else { paint_reported_by_id(d, n) })
|
||||
&& eq(n, refn)
|
||||
})
|
||||
}
|
||||
|
||||
/// The objects `same_in` takes now.
|
||||
fn same_now(d: &Document, iso: Option<NodeId>, refn: &Node, members: bool, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Vec<NodeId> {
|
||||
let group = super::live_paint_group(d.parent_of(refn.id).and_then(|p| d.node(p)));
|
||||
matching(d, iso, |n, parent| same_candidate(n, parent, live_paint, group, members) && eq(n, refn))
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("`{cmd}` {p} failed: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
|
||||
}
|
||||
|
||||
fn sel(s: &mut Session, ids: &[NodeId]) {
|
||||
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
|
||||
}
|
||||
|
||||
/// A 10 × 10 rectangle at (`x`, `y`) filled with `hex`.
|
||||
fn rect(s: &mut Session, x: f64, y: f64, hex: &str) -> NodeId {
|
||||
let r = id(&run(s, "shape.rectangle", json!({"x": x, "y": y, "width": 10.0, "height": 10.0})));
|
||||
run(s, "paint.setFill", json!({"ids": [r.0], "color": hex}));
|
||||
r
|
||||
}
|
||||
|
||||
/// A compound path of three rectangles at `y`, filled with `hex` → the compound path and its
|
||||
/// member paths.
|
||||
fn compound(s: &mut Session, y: f64, hex: &str) -> (NodeId, Vec<NodeId>) {
|
||||
let members: Vec<NodeId> = [0.0, 20.0, 40.0].map(|x| rect(s, 300.0 + x, y, hex)).into();
|
||||
sel(s, &members);
|
||||
let c = id(&run(s, "object.compoundPath.make", json!({})));
|
||||
run(s, "paint.setFill", json!({"ids": [c.0], "color": hex}));
|
||||
(c, members)
|
||||
}
|
||||
|
||||
/// A Live Paint group of two overlapping squares at `y`, its left face red, its middle face blue and
|
||||
/// its right face red → the group and its faces.
|
||||
fn live_paint(s: &mut Session, y: f64) -> (NodeId, Vec<NodeId>) {
|
||||
let a = id(&run(s, "shape.rectangle", json!({"x": 0.0, "y": y, "width": 100.0, "height": 100.0})));
|
||||
let b = id(&run(s, "shape.rectangle", json!({"x": 50.0, "y": y, "width": 100.0, "height": 100.0})));
|
||||
sel(s, &[a, b]);
|
||||
let g = id(&run(s, "livePaint.make", json!({})));
|
||||
let faces = [(25.0, "#ff0000"), (75.0, "#0000ff"), (125.0, "#ff0000")]
|
||||
.map(|(x, hex)| NodeId(run(s, "livePaint.fill", json!({"group": g.0, "point": [x, y + 50.0], "color": hex}))["face"].as_u64().unwrap()))
|
||||
.into();
|
||||
(g, faces)
|
||||
}
|
||||
|
||||
/// The objects of [`rich`] that tests pick from.
|
||||
struct Rich {
|
||||
plain: Vec<NodeId>,
|
||||
compound: NodeId,
|
||||
members: Vec<NodeId>,
|
||||
group: NodeId,
|
||||
live_paint: NodeId,
|
||||
faces: Vec<NodeId>,
|
||||
sublayer: NodeId,
|
||||
}
|
||||
|
||||
/// A document with red and blue rectangles, a compound path, a group with a hidden and a locked
|
||||
/// rectangle, a locked group, a Live Paint group, a sublayer holding a rectangle and a second
|
||||
/// compound path, and a hidden and a locked layer with a red rectangle each.
|
||||
fn rich() -> (Session, Rich) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let mut plain = vec![rect(&mut s, 0.0, 0.0, "#ff0000"), rect(&mut s, 20.0, 0.0, "#ff0000"), rect(&mut s, 40.0, 0.0, "#0000ff")];
|
||||
let (compound_id, members) = compound(&mut s, 0.0, "#ff0000");
|
||||
let [in_group, hidden, locked] = [0.0, 20.0, 40.0].map(|x| rect(&mut s, x, 200.0, "#ff0000"));
|
||||
let blue = rect(&mut s, 60.0, 200.0, "#0000ff");
|
||||
sel(&mut s, &[in_group, hidden, locked, blue]);
|
||||
let group = id(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "layer.setProps", json!({"id": hidden.0, "visible": false}));
|
||||
run(&mut s, "layer.setProps", json!({"id": locked.0, "locked": true}));
|
||||
let in_locked = rect(&mut s, 100.0, 200.0, "#ff0000");
|
||||
sel(&mut s, &[in_locked]);
|
||||
let locked_group = id(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "layer.setProps", json!({"id": locked_group.0, "locked": true}));
|
||||
let (live_paint_id, faces) = live_paint(&mut s, 300.0);
|
||||
plain.extend([in_group, blue]);
|
||||
let sublayer = id(&run(&mut s, "layer.newSublayer", json!({"parent": layer.0})));
|
||||
plain.push(rect(&mut s, 0.0, 500.0, "#ff0000"));
|
||||
compound(&mut s, 500.0, "#0000ff");
|
||||
for prop in ["visible", "locked"] {
|
||||
let l = id(&run(&mut s, "layer.new", json!({"top": true})));
|
||||
rect(&mut s, 200.0, 500.0, "#ff0000");
|
||||
run(&mut s, "layer.setProps", json!({"id": l.0, prop: prop == "locked"}));
|
||||
}
|
||||
let rich = Rich { plain, compound: compound_id, members, group, live_paint: live_paint_id, faces, sublayer };
|
||||
(s, rich)
|
||||
}
|
||||
|
||||
/// The isolation scopes to try: none, the group, the compound path, and the Live Paint group.
|
||||
fn scopes(r: &Rich) -> [Option<NodeId>; 4] {
|
||||
[None, Some(r.group), Some(r.compound), Some(r.live_paint)]
|
||||
}
|
||||
|
||||
/// Isolate `iso`, leaving isolation mode first.
|
||||
fn isolate(s: &mut Session, iso: Option<NodeId>) {
|
||||
if s.doc().unwrap().isolation.is_some() {
|
||||
run(s, "object.exitIsolation", json!({}));
|
||||
}
|
||||
if let Some(i) = iso {
|
||||
run(s, "object.isolate", json!({"id": i.0}));
|
||||
assert_eq!(s.doc().unwrap().isolation, Some(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// The walk visits the objects it visited before, in the same order and with the same objects left
|
||||
/// out, and hands each the node that `Document::parent_of` names for it.
|
||||
#[test]
|
||||
fn the_walk_hands_each_object_the_node_that_holds_it() {
|
||||
let (mut s, r) = rich();
|
||||
// Look inside everything, and inside every other object only.
|
||||
let deeper: [fn(&Node) -> bool; 2] = [|_| true, |n| n.id.0 % 2 == 0];
|
||||
for iso in scopes(&r) {
|
||||
isolate(&mut s, iso);
|
||||
let st = s.doc().unwrap();
|
||||
let d = &st.doc;
|
||||
for f in deeper {
|
||||
let mut before = vec![];
|
||||
walk_by_id(d, st.isolation, |n| {
|
||||
before.push((n.id, d.parent_of(n.id)));
|
||||
f(n)
|
||||
});
|
||||
let mut now = vec![];
|
||||
walk_selectable_in(d, st.isolation, |n, parent| {
|
||||
now.push((n.id, parent.map(|p| p.id)));
|
||||
f(n)
|
||||
});
|
||||
assert!(!now.is_empty(), "isolating {iso:?}");
|
||||
assert_eq!(now, before, "isolating {iso:?}");
|
||||
}
|
||||
}
|
||||
// Every face, member path and the sublayer's art were visited somewhere above.
|
||||
let st = s.doc().unwrap();
|
||||
assert!(r.faces.iter().chain(&r.members).all(|f| st.doc.node(*f).is_some()));
|
||||
assert!(st.doc.node(r.sublayer).is_some_and(|n| n.is_layer()));
|
||||
}
|
||||
|
||||
/// Select > Same and Select by Color select the objects they selected before, in the same order,
|
||||
/// with the same reply and the same Select > Reselect state, from every kind of reference object
|
||||
/// and in every isolation scope.
|
||||
#[test]
|
||||
fn select_same_takes_the_objects_it_took_when_it_looked_up_parents() {
|
||||
type Eq = fn(&Node, &Node) -> bool;
|
||||
let fill: Eq = |a, b| same_paint(&fill_of(a), &fill_of(b), false);
|
||||
let stroke: Eq = |a, b| same_paint(&stroke_of(a).0, &stroke_of(b).0, false);
|
||||
let commands: [(&str, bool, Eq); 6] = [
|
||||
("select.same.fillColor", true, fill),
|
||||
("select.same.fillAndStroke", true, |a, b| {
|
||||
same_paint(&fill_of(a), &fill_of(b), false) && same_paint(&stroke_of(a).0, &stroke_of(b).0, false)
|
||||
}),
|
||||
("select.same.strokeColor", false, stroke),
|
||||
("select.same.opacity", false, |a, b| (a.opacity - b.opacity).abs() < 1e-6),
|
||||
("select.same.blendingMode", false, |a, b| a.blend == b.blend),
|
||||
("select.same.shapeType", false, |a, b| a.kind_label() == b.kind_label()),
|
||||
];
|
||||
let (mut s, r) = rich();
|
||||
assert!(!s.prefs.select_same_tint_percent);
|
||||
let froms: Vec<NodeId> = r.plain.iter().chain(&r.members).chain(&r.faces).copied().chain([r.compound]).collect();
|
||||
let mut checked = 0;
|
||||
for iso in scopes(&r) {
|
||||
isolate(&mut s, iso);
|
||||
for from in &froms {
|
||||
for (cmd, live_paint, eq) in commands {
|
||||
// An object outside the isolated one may not be selectable; the selection then
|
||||
// stays, and both sides compare with what it holds.
|
||||
let _ = s.execute("select.set", &json!({"ids": [from.0]}));
|
||||
let st = s.doc().unwrap();
|
||||
let Ok((refn, members)) = same_reference(st, cmd) else {
|
||||
assert!(s.execute(cmd, &json!({})).is_err(), "{cmd} from {from:?} isolating {iso:?}");
|
||||
continue;
|
||||
};
|
||||
let refn = refn.clone();
|
||||
let expected = same_by_id(&st.doc, st.isolation, &refn, members, live_paint, eq);
|
||||
assert_eq!(same_now(&st.doc, st.isolation, &refn, members, live_paint, eq), expected, "{cmd} from {from:?} isolating {iso:?}");
|
||||
let before = st.selection.objects.clone();
|
||||
let reply = run(&mut s, cmd, json!({}));
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, expected, "{cmd} from {from:?} isolating {iso:?}");
|
||||
assert_eq!(reply, json!({"count": expected.len()}));
|
||||
assert_eq!(st.last_selection_cmd, Some((cmd.to_string(), json!({}), before)));
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
for hex in ["#ff0000", "#0000ff"] {
|
||||
let st = s.doc().unwrap();
|
||||
let reads_as = |n: &Node| fill_of(n).color().is_some_and(|c| c.to_hex() == hex);
|
||||
let expected = matching_by_id(&st.doc, st.isolation, |d, n| paint_reported_by_id(d, n) && reads_as(n));
|
||||
let p = json!({"fill": hex});
|
||||
let reply = run(&mut s, "select.color", p.clone());
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, expected, "select.color {hex} isolating {iso:?}");
|
||||
assert_eq!(reply, json!({"count": expected.len()}));
|
||||
assert_eq!(st.last_selection_cmd.as_ref().map(|(c, p, _)| (c.as_str(), p)), Some(("select.color", &p)));
|
||||
}
|
||||
}
|
||||
// Most of the references can be selected in some scope.
|
||||
assert!(checked > froms.len() * commands.len(), "{checked} checks");
|
||||
}
|
||||
|
||||
/// In a damaged document that holds an id twice, the parent that decides whether an object is a
|
||||
/// member of a compound path or a face of a Live Paint group is the one that holds the object the
|
||||
/// walk is at, not the one that holds the id's first place in the tree.
|
||||
#[test]
|
||||
fn select_same_reads_the_parent_of_the_object_it_is_at() {
|
||||
for in_live_paint in [false, true] {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let (_, inner) = if in_live_paint { live_paint(&mut s, 300.0) } else { compound(&mut s, 0.0, "#0000ff") };
|
||||
let from = rect(&mut s, 0.0, 0.0, "#ff0000");
|
||||
// A red rectangle above the others that has the id of a face or member path.
|
||||
let mut copy = s.doc().unwrap().doc.node(from).unwrap().clone();
|
||||
copy.id = inner[0];
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, copy).unwrap();
|
||||
let mut commands = vec![("select.same.fillColor", json!({})), ("select.same.fillAndStroke", json!({}))];
|
||||
// Select by Color takes the red faces of a Live Paint group too, so it is tried on the
|
||||
// compound path only.
|
||||
if !in_live_paint {
|
||||
commands.push(("select.color", json!({"fill": "#ff0000"})));
|
||||
}
|
||||
for (cmd, p) in commands {
|
||||
sel(&mut s, &[from]);
|
||||
let reply = run(&mut s, cmd, p);
|
||||
assert_eq!(reply["count"], 2, "{cmd}, Live Paint: {in_live_paint}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document of `n` objects on one layer: red and blue rectangles, one in 25 a compound path of
|
||||
/// three, and two Live Paint groups that hold one in 25 each as faces → the session, with the first
|
||||
/// rectangle selected.
|
||||
fn big(n: usize) -> Session {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let (c, _) = compound(&mut s, 0.0, "#ff0000");
|
||||
let (g, _) = live_paint(&mut s, 300.0);
|
||||
let [red, blue] = ["#ff0000", "#0000ff"].map(|hex| rect(&mut s, 0.0, 0.0, hex));
|
||||
let mut d = Document::clone(&s.doc().unwrap().doc);
|
||||
let layer = d.layers[0].id;
|
||||
let template = |id: NodeId| d.node(id).unwrap().clone();
|
||||
let (c, g, red, blue) = (template(c), template(g), template(red), template(blue));
|
||||
fn renumber(n: &Node, d: &mut Document) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = d.alloc_id();
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
*c = Arc::new(renumber(c, d));
|
||||
}
|
||||
n
|
||||
}
|
||||
d.children_mut(Some(layer)).unwrap().clear();
|
||||
let faces: Vec<Arc<Node>> = g.children().into_iter().flatten().cloned().collect();
|
||||
for _ in 0..2 {
|
||||
let mut g = renumber(&g, &mut d);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
ch.clear();
|
||||
for i in 0..n / 25 {
|
||||
ch.push(Arc::new(renumber(&faces[i % faces.len()], &mut d)));
|
||||
}
|
||||
}
|
||||
d.insert(Some(layer), usize::MAX, g).unwrap();
|
||||
}
|
||||
for i in 0..n - 2 * (n / 25) {
|
||||
let node = match i % 25 {
|
||||
0 => renumber(&c, &mut d),
|
||||
k if k % 2 == 0 => renumber(&red, &mut d),
|
||||
_ => renumber(&blue, &mut d),
|
||||
};
|
||||
d.insert(Some(layer), usize::MAX, node).unwrap();
|
||||
}
|
||||
let first = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Path { .. })).unwrap().id;
|
||||
s.add_document(d, None);
|
||||
sel(&mut s, &[first]);
|
||||
s
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn time(f: impl FnOnce()) -> Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ms(d: Duration) -> f64 {
|
||||
d.as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// Timings of Select > Same's search, by id lookups and with the walk's parents, on 5,000, 50,000
|
||||
/// and 200,000 objects, run in turn on the same document, 7 runs each. Ignored by default; it
|
||||
/// prints the median, fastest and slowest run and sets no bound on them:
|
||||
/// `cargo test --release -p vectorcraft-engine --lib select_same_perf -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "a benchmark: run with --ignored --nocapture"]
|
||||
fn select_same_perf() {
|
||||
const RUNS: usize = 7;
|
||||
type Eq = fn(&Node, &Node) -> bool;
|
||||
let fill: Eq = |a, b| same_paint(&fill_of(a), &fill_of(b), false);
|
||||
let stroke: Eq = |a, b| same_paint(&stroke_of(a).0, &stroke_of(b).0, false);
|
||||
eprintln!("select_same_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
eprintln!(
|
||||
"select_same_perf: {:>7} {:<12} {:>8} {:>26} {:>26}",
|
||||
"objects", "command", "selected", "by id ms (min-max)", "walk parents ms (min-max)"
|
||||
);
|
||||
for n in [5_000, 50_000, 200_000] {
|
||||
let s = big(n);
|
||||
let st = s.doc().unwrap();
|
||||
let (d, iso) = (&st.doc, st.isolation);
|
||||
let objects = {
|
||||
let mut k = 0;
|
||||
walk_selectable_in(d, iso, |_, _| {
|
||||
k += 1;
|
||||
true
|
||||
});
|
||||
k
|
||||
};
|
||||
for (cmd, live_paint, eq) in [("fillColor", true, fill), ("strokeColor", false, stroke)] {
|
||||
let (refn, members) = same_reference(st, cmd).unwrap();
|
||||
let (mut old, mut new) = (Vec::new(), Vec::new());
|
||||
let (mut a, mut b) = (vec![], vec![]);
|
||||
for run in 0..RUNS {
|
||||
// The two take turns going first.
|
||||
if run % 2 == 0 {
|
||||
old.push(time(|| a = std::hint::black_box(same_by_id(d, iso, refn, members, live_paint, eq))));
|
||||
new.push(time(|| b = std::hint::black_box(same_now(d, iso, refn, members, live_paint, eq))));
|
||||
} else {
|
||||
new.push(time(|| b = std::hint::black_box(same_now(d, iso, refn, members, live_paint, eq))));
|
||||
old.push(time(|| a = std::hint::black_box(same_by_id(d, iso, refn, members, live_paint, eq))));
|
||||
}
|
||||
assert_eq!(a, b, "{n} objects, {cmd}");
|
||||
}
|
||||
old.sort();
|
||||
new.sort();
|
||||
eprintln!(
|
||||
"select_same_perf: {objects:>7} {cmd:<12} {:>8} {:>10.3} ({:>6.3}-{:>7.3}) {:>10.3} ({:>6.3}-{:>7.3})",
|
||||
b.len(),
|
||||
ms(old[RUNS / 2]),
|
||||
ms(old[0]),
|
||||
ms(old[RUNS - 1]),
|
||||
ms(new[RUNS / 2]),
|
||||
ms(new[0]),
|
||||
ms(new[RUNS - 1]),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
//! Magic Wand panel's (session state, kept across tool switches); the tool runs
|
||||
//! `select.magicWand` on click.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -188,13 +190,14 @@ impl WandSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paintable leaves (paths, compounds, text, images) that are visible and editable.
|
||||
/// Paintable leaves (paths, compounds, text, images) that are visible and editable, in the order
|
||||
/// of the document walk.
|
||||
fn paintable(doc: &Document) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut compounds: Vec<NodeId> = vec![];
|
||||
let mut compounds: HashSet<NodeId> = HashSet::new();
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
compounds.push(n.id);
|
||||
compounds.insert(n.id);
|
||||
out.push(n.id);
|
||||
} else if !n.is_container() && !n.is_ruler_guide() {
|
||||
out.push(n.id);
|
||||
@@ -210,6 +213,18 @@ fn paintable(doc: &Document) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Shift-click: the selected objects in their order, then each hit that isn't selected yet.
|
||||
fn added(selected: &[NodeId], hits: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let seen: HashSet<NodeId> = selected.iter().copied().collect();
|
||||
selected.iter().copied().chain(hits.into_iter().filter(|h| !seen.contains(h))).collect()
|
||||
}
|
||||
|
||||
/// Alt-click: the selected objects that aren't hits, in their order.
|
||||
fn subtracted(selected: &[NodeId], hits: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let hits: HashSet<NodeId> = hits.into_iter().collect();
|
||||
selected.iter().copied().filter(|i| !hits.contains(i)).collect()
|
||||
}
|
||||
|
||||
fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "select.magicWand")?.ok_or_else(|| bad("select.magicWand", "missing id"))?;
|
||||
let st = s.doc()?;
|
||||
@@ -224,8 +239,8 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode)))
|
||||
.collect();
|
||||
let ids: Vec<NodeId> = match str_param(p, "mode").unwrap_or("set") {
|
||||
"add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(),
|
||||
"subtract" => st.selection.objects.iter().copied().filter(|i| !hits.contains(i)).collect(),
|
||||
"add" => added(&st.selection.objects, hits),
|
||||
"subtract" => subtracted(&st.selection.objects, hits),
|
||||
"set" => hits,
|
||||
other => return Err(bad("select.magicWand", format!("unknown mode `{other}` (set, add, subtract)"))),
|
||||
};
|
||||
@@ -423,6 +438,252 @@ mod tests {
|
||||
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0)));
|
||||
}
|
||||
|
||||
/// [`paintable`] with the compound paths kept in a list and searched for each object's parent.
|
||||
fn paintable_by_search(doc: &Document) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut compounds: Vec<NodeId> = vec![];
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
compounds.push(n.id);
|
||||
out.push(n.id);
|
||||
} else if !n.is_container() && !n.is_ruler_guide() {
|
||||
out.push(n.id);
|
||||
}
|
||||
});
|
||||
let editable = doc.editable();
|
||||
out.retain(|id| {
|
||||
!doc.parent_of(*id).is_some_and(|p| compounds.contains(&p))
|
||||
&& editable(*id)
|
||||
&& doc.is_visible(*id)
|
||||
&& doc.node(*id).is_some_and(|n| n.visible)
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// [`added`] with the selection searched for each hit.
|
||||
fn added_by_search(selected: &[NodeId], hits: &[NodeId]) -> Vec<NodeId> {
|
||||
selected.iter().copied().chain(hits.iter().copied().filter(|h| !selected.contains(h))).collect()
|
||||
}
|
||||
|
||||
/// [`subtracted`] with the hits searched for each selected object.
|
||||
fn subtracted_by_search(selected: &[NodeId], hits: &[NodeId]) -> Vec<NodeId> {
|
||||
selected.iter().copied().filter(|i| !hits.contains(i)).collect()
|
||||
}
|
||||
|
||||
/// A red fill for an even `k` and a blue one for an odd `k`, with a 1 pt black stroke.
|
||||
fn bench_paint(k: usize) -> vectorcraft_doc::Appearance {
|
||||
use vectorcraft_color::Color;
|
||||
let fill = if k.is_multiple_of(2) { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) };
|
||||
vectorcraft_doc::Appearance::basic(Paint::solid(fill), Paint::solid(Color::BLACK), 1.0)
|
||||
}
|
||||
|
||||
/// Path `k`: a 10 × 10 rectangle painted as [`bench_paint`]. Every 97th path is locked and
|
||||
/// every 89th hidden.
|
||||
fn bench_path(d: &mut Document, k: usize) -> Node {
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0);
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)), bench_paint(k));
|
||||
n.locked = k % 97 == 5;
|
||||
n.visible = k % 89 != 7;
|
||||
n
|
||||
}
|
||||
|
||||
/// A session whose document holds `blocks` × 200 paths on one layer. Each block has a group of
|
||||
/// 10 paths, 25 compound paths of 2 paths each and 140 loose paths, with the group and the
|
||||
/// compound paths among the loose paths. The compound paths alternate red and blue fills, and
|
||||
/// a few are locked or hidden.
|
||||
fn wand_session(blocks: usize) -> Session {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_geom::FillRule;
|
||||
let mut d = Document::new(4000.0, 4000.0);
|
||||
let mut k = 0;
|
||||
let mut next = |d: &mut Document| {
|
||||
k += 1;
|
||||
bench_path(d, k - 1)
|
||||
};
|
||||
let mut art = vec![];
|
||||
for slot in 0..blocks * 166 {
|
||||
let node = match slot % 166 {
|
||||
0 => {
|
||||
let members = (0..10).map(|_| Arc::new(next(&mut d))).collect();
|
||||
Node::group(d.alloc_id(), members)
|
||||
}
|
||||
c @ 1..=25 => {
|
||||
let members = (0..2).map(|_| Arc::new(next(&mut d))).collect();
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
n.appearance = bench_paint(c).into();
|
||||
n.locked = slot % 1001 == 3;
|
||||
n.visible = slot % 1003 != 5;
|
||||
n
|
||||
}
|
||||
_ => next(&mut d),
|
||||
};
|
||||
art.push(Arc::new(node));
|
||||
}
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
*ch = art;
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
s
|
||||
}
|
||||
|
||||
/// The objects the wand picks when `reference` is clicked, found as before membership sets.
|
||||
fn hits_by_search(s: &Session, reference: NodeId) -> Vec<NodeId> {
|
||||
let st = s.doc().unwrap();
|
||||
let r = st.doc.node(reference).unwrap();
|
||||
let w = s.menu.wand.clone();
|
||||
paintable_by_search(&st.doc).into_iter().filter(|i| w.matches(r, st.doc.node(*i).unwrap(), st.doc.color_mode)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn membership_sets_give_the_same_objects_in_the_same_order_as_searches() {
|
||||
// 20,000 paths: 5,000 in 2,500 compound paths and 1,000 in 100 groups.
|
||||
let mut s = wand_session(100);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let all = paintable(doc);
|
||||
assert!(all == paintable_by_search(doc), "paintable objects differ");
|
||||
// Compound paths stay pickable unless locked or hidden, and their members never are.
|
||||
let pickable: HashSet<NodeId> = all.iter().copied().collect();
|
||||
let (mut compounds, mut skipped) = (0, 0);
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
compounds += 1;
|
||||
skipped += usize::from(n.locked || !n.visible);
|
||||
assert_eq!(pickable.contains(&n.id), n.visible && !n.locked, "compound path {}", n.id.0);
|
||||
assert!(children.iter().all(|m| !pickable.contains(&m.id)), "a member of compound path {} is pickable", n.id.0);
|
||||
}
|
||||
});
|
||||
assert_eq!(compounds, 2_500);
|
||||
assert!(skipped > 0 && skipped < 100, "{skipped} locked or hidden compound paths");
|
||||
let reference = all[0];
|
||||
let hits = hits_by_search(&s, reference);
|
||||
assert!(hits.len() > 5_000 && hits.len() < all.len() / 2 + 1_000, "{} hits", hits.len());
|
||||
// A selection in another order than the document's: every third object from the end, both
|
||||
// hits and objects that aren't hits.
|
||||
let selected: Vec<NodeId> = all.iter().rev().step_by(3).copied().collect();
|
||||
assert!(selected.iter().any(|i| hits.contains(i)) && selected.iter().any(|i| !hits.contains(i)));
|
||||
assert!(added(&selected, hits.clone()) == added_by_search(&selected, &hits), "Shift-click differs");
|
||||
assert!(subtracted(&selected, hits.clone()) == subtracted_by_search(&selected, &hits), "Alt-click differs");
|
||||
// And through the command, in each mode.
|
||||
let ids: Vec<u64> = selected.iter().map(|i| i.0).collect();
|
||||
for (mode, want) in [("set", hits.clone()), ("add", added_by_search(&selected, &hits)), ("subtract", subtracted_by_search(&selected, &hits))]
|
||||
{
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
assert!(s.doc().unwrap().selection.objects == selected, "select.set kept the order");
|
||||
let r = s.execute("select.magicWand", &json!({"id": reference.0, "mode": mode})).unwrap();
|
||||
assert_eq!(r["count"], json!(want.len()), "{mode}");
|
||||
assert!(s.doc().unwrap().selection.objects == want, "{mode} selects other objects or another order");
|
||||
}
|
||||
}
|
||||
|
||||
/// Time the Magic Wand's paintable walk, Shift-click and Alt-click lists and a whole Shift-click
|
||||
/// on documents of 2,000, 20,000 and 50,000 paths, with membership sets and with the searches
|
||||
/// they replace, alternating 7 runs of each and giving the medians in ms. On Linux the times are
|
||||
/// the thread's CPU time.
|
||||
/// Run with `cargo test --release -p vectorcraft-engine --lib magic_wand_membership_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; performance depends on machine load"]
|
||||
fn magic_wand_membership_timing() {
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
/// The time of one call of `f`, averaged over `reps` calls.
|
||||
fn time(reps: u32, f: &mut dyn FnMut()) -> f64 {
|
||||
let start = (cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..reps {
|
||||
f();
|
||||
}
|
||||
let ms = match (start.0, cpu_ns()) {
|
||||
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
|
||||
_ => start.1.elapsed().as_secs_f64() * 1000.0,
|
||||
};
|
||||
ms / f64::from(reps)
|
||||
}
|
||||
fn median(v: &mut [f64]) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
/// Alternate `old` and `new` 7 times each and print their medians and every run. Each run
|
||||
/// takes the mean of enough calls for about 100 ms.
|
||||
fn compare(paths: usize, what: &str, old: &mut dyn FnMut(), new: &mut dyn FnMut()) {
|
||||
let reps = (100.0 / time(1, old).max(0.1)).clamp(1.0, 200.0) as u32;
|
||||
let (mut o, mut n) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
o.push(time(reps, old));
|
||||
n.push(time(reps, new));
|
||||
}
|
||||
let runs = format!("calls per run {reps}: {o:.3?} / {n:.3?}");
|
||||
println!("| {paths} | {what} | {:.3} | {:.3} | {runs}", median(&mut o), median(&mut n));
|
||||
}
|
||||
println!("clock: {}", if cpu_ns().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
println!("| paths | step | searches (ms) | sets (ms) | runs");
|
||||
for blocks in [10, 100, 250] {
|
||||
let mut s = wand_session(blocks);
|
||||
let paths = blocks * 200;
|
||||
let st = s.doc().unwrap();
|
||||
let all = paintable(&st.doc);
|
||||
assert!(all == paintable_by_search(&st.doc));
|
||||
let reference = all[0];
|
||||
let hits = hits_by_search(&s, reference);
|
||||
let selected: Vec<NodeId> = all.iter().rev().step_by(2).copied().collect();
|
||||
assert!(added(&selected, hits.clone()) == added_by_search(&selected, &hits));
|
||||
assert!(subtracted(&selected, hits.clone()) == subtracted_by_search(&selected, &hits));
|
||||
let doc = &st.doc;
|
||||
compare(
|
||||
paths,
|
||||
"paintable",
|
||||
&mut || {
|
||||
std::hint::black_box(paintable_by_search(doc));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(paintable(doc));
|
||||
},
|
||||
);
|
||||
compare(
|
||||
paths,
|
||||
"Shift-click list",
|
||||
&mut || {
|
||||
std::hint::black_box(added_by_search(&selected, &hits));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(added(&selected, hits.clone()));
|
||||
},
|
||||
);
|
||||
compare(
|
||||
paths,
|
||||
"Alt-click list",
|
||||
&mut || {
|
||||
std::hint::black_box(subtracted_by_search(&selected, &hits));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(subtracted(&selected, hits.clone()));
|
||||
},
|
||||
);
|
||||
// A whole Shift-click after the selection is set: [`magic_wand`], and its steps with
|
||||
// the searches.
|
||||
let ids = json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<u64>>() });
|
||||
let click = json!({"id": reference.0, "mode": "add"});
|
||||
let s = std::cell::RefCell::new(&mut s);
|
||||
compare(
|
||||
paths,
|
||||
"select.set, then Shift-click",
|
||||
&mut || {
|
||||
let s = &mut **s.borrow_mut();
|
||||
s.execute("select.set", &ids).unwrap();
|
||||
let before = s.doc().unwrap().selection.objects.clone();
|
||||
let picked = added_by_search(&before, &hits_by_search(s, reference));
|
||||
s.select(|_, sel| sel.set(picked)).unwrap();
|
||||
},
|
||||
&mut || {
|
||||
let s = &mut **s.borrow_mut();
|
||||
s.execute("select.set", &ids).unwrap();
|
||||
magic_wand(s, &click).unwrap();
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolation_mode_limits_the_wand_to_the_isolated_group() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -24,6 +24,7 @@ mod build;
|
||||
mod cancel;
|
||||
mod caret_kerning;
|
||||
mod charstroke;
|
||||
mod circle_through;
|
||||
pub(super) mod clip;
|
||||
mod clipboard;
|
||||
mod clipflavours;
|
||||
|
||||
@@ -772,3 +772,142 @@ fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() {
|
||||
assert!(!v.no_spine, "{odd}");
|
||||
}
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Two blends with different options, both selected: the first (Steps 3, along the path, Ease
|
||||
/// Out at 20%, Shift 10%) and the second (Distance 12 pt, along the page, Ease In Out at 60%,
|
||||
/// Shift -40%).
|
||||
fn two_different_blends(s: &mut Session) -> (NodeId, NodeId) {
|
||||
let b1 = make(s, 0.0, json!({"spacing": "steps", "orientation": "path"}));
|
||||
let b2 = make(s, 100.0, json!({"spacing": "distance", "value": 12, "orientation": "path"}));
|
||||
s.execute("object.blend.setEasing", &json!({"id": b1.0, "easingType": "easeOut", "ramp": 20, "colorShift": 10})).unwrap();
|
||||
s.execute("object.blend.setEasing", &json!({"id": b2.0, "easingType": "easeInOut", "ramp": 60, "colorShift": -40})).unwrap();
|
||||
sel(s, &[b2]);
|
||||
s.execute("object.blend.options", &json!({"orientation": "page"})).unwrap();
|
||||
sel(s, &[b1, b2]);
|
||||
(b1, b2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_on_several_blends_set_only_the_values_given() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let (before1, before2) = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
assert_ne!(before1.spacing, before2.spacing);
|
||||
// Each value given goes to every selected blend; each keeps its own for the others.
|
||||
for (p, apply) in [
|
||||
(json!({"colorShift": 30}), (|sp: &mut BlendSpec| sp.color_shift = 30.0) as fn(&mut BlendSpec)),
|
||||
(json!({"ramp": 45}), |sp| sp.ease.ramp = 0.45),
|
||||
(json!({"easingType": "easeOutIn"}), |sp| sp.ease.kind = vectorcraft_doc::BlendEaseType::OutIn),
|
||||
(json!({"orientation": "path"}), |sp| sp.orientation = BlendOrientation::AlignToPath),
|
||||
(json!({"spacing": "steps", "value": 7}), |sp| sp.spacing = BlendSpacing::Steps(7)),
|
||||
] {
|
||||
let (mut want1, mut want2) = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
apply(&mut want1);
|
||||
apply(&mut want2);
|
||||
s.execute("object.blend.options", &p).unwrap();
|
||||
assert_eq!((spec(&s, b1).1, spec(&s, b2).1), (want1, want2), "{p}");
|
||||
}
|
||||
// A spacing mode without a count keeps the count of a blend already in that mode; a blend in
|
||||
// another mode takes the mode's starting count.
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "spacing": "distance", "value": 12})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"spacing": "steps"})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.spacing, spec(&s, b2).1.spacing), (BlendSpacing::Steps(7), BlendSpacing::Steps(5)));
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "spacing": "steps", "value": 12})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"spacing": "steps"})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.spacing, spec(&s, b2).1.spacing), (BlendSpacing::Steps(7), BlendSpacing::Steps(12)));
|
||||
// The whole edit of both blends is one undo step.
|
||||
let depth = undo_len(&s);
|
||||
s.execute("object.blend.options", &json!({"colorShift": -5, "ramp": 5})).unwrap();
|
||||
assert_eq!(undo_len(&s), depth + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.color_shift, spec(&s, b2).1.color_shift), (30.0, 30.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_with_an_id_edit_that_blend_alone() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let before2 = spec(&s, b2).1;
|
||||
let mut want1 = spec(&s, b1).1;
|
||||
s.execute("object.blend.options", &json!({"id": b1.0, "spacing": "distance", "value": 15, "ramp": 50, "colorShift": -20})).unwrap();
|
||||
want1.spacing = BlendSpacing::Distance(15.0);
|
||||
want1.ease.ramp = 0.5;
|
||||
want1.color_shift = -20.0;
|
||||
assert_eq!(spec(&s, b1).1, want1, "only the values given change");
|
||||
assert_eq!(spec(&s, b2).1, before2, "a selected blend that is not `id` stays as it was");
|
||||
// `id` works with nothing selected, and does not set the options new blends start with.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let defaults = s.execute("object.blend.info", &json!({})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "orientation": "path"})).unwrap();
|
||||
assert_eq!(spec(&s, b2).1.orientation, BlendOrientation::AlignToPath);
|
||||
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap(), defaults);
|
||||
// A hidden or locked blend and an object that is not a blend are errors that change nothing.
|
||||
for (visible, locked) in [(false, false), (true, true)] {
|
||||
s.edit("state", |d, _| {
|
||||
let n = d.node_mut(b1).unwrap();
|
||||
(n.visible, n.locked) = (visible, locked);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (before, depth) = (spec(&s, b1).1, undo_len(&s));
|
||||
let error = s.execute("object.blend.options", &json!({"id": b1.0, "colorShift": 25})).unwrap_err().to_string();
|
||||
assert!(error.contains("the object is hidden or locked"), "{error}");
|
||||
assert_eq!((spec(&s, b1).1, undo_len(&s)), (before, depth));
|
||||
}
|
||||
let other = rect(&mut s, 300.0, 0.0, 10.0);
|
||||
for id in [json!(other.0), json!(999_999)] {
|
||||
let error = s.execute("object.blend.options", &json!({"id": id, "colorShift": 25})).unwrap_err().to_string();
|
||||
assert!(error.contains("not a blend"), "{error}");
|
||||
}
|
||||
// The blend's own spine decides whether easing is allowed, whatever is selected.
|
||||
s.execute("object.blend.createSpine", &json!({"mode": "never"})).unwrap();
|
||||
let bare = make(&mut s, 300.0, json!({}));
|
||||
sel(&mut s, &[b2]);
|
||||
let error = s.execute("object.blend.options", &json!({"id": bare.0, "ramp": 30})).unwrap_err().to_string();
|
||||
assert!(error.contains("the blend has no spine"), "{error}");
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "ramp": 30})).unwrap();
|
||||
assert_eq!(spec(&s, b2).1.ease.ramp, 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_that_change_nothing_or_are_refused_record_no_undo_step() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let before = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
let depth = undo_len(&s);
|
||||
// Values the blends already have, and no values at all.
|
||||
for p in [json!({}), json!({"smooth": false}), json!({"orientation": "page", "id": b2.0}), json!({"colorShift": 10, "id": b1.0})] {
|
||||
s.execute("object.blend.options", &p).unwrap();
|
||||
assert_eq!(undo_len(&s), depth, "{p}");
|
||||
}
|
||||
// An invalid value anywhere stops the whole call before anything changes.
|
||||
for p in [
|
||||
json!({"colorShift": 50, "ramp": 101}),
|
||||
json!({"colorShift": 50, "ramp": -1}),
|
||||
json!({"colorShift": 50, "ramp": "half"}),
|
||||
json!({"ramp": 50, "colorShift": -101}),
|
||||
json!({"ramp": 50, "easingType": "linear"}),
|
||||
json!({"ramp": 50, "spacing": "steps", "value": 0}),
|
||||
json!({"ramp": 50, "spacing": "distance", "value": -3}),
|
||||
json!({"ramp": 50, "id": "b1"}),
|
||||
json!({"ramp": 50, "orientation": "sideways"}),
|
||||
json!({"ramp": 50, "orientation": 1}),
|
||||
json!({"ramp": 50, "value": 3}),
|
||||
json!({"ramp": 50, "spacing": 123}),
|
||||
] {
|
||||
assert!(s.execute("object.blend.options", &p).is_err(), "{p}");
|
||||
assert_eq!((spec(&s, b1).1, spec(&s, b2).1, undo_len(&s)), (before.0.clone(), before.1.clone(), depth), "{p}");
|
||||
}
|
||||
// Make and the options new blends start with refuse an unknown orientation too.
|
||||
let error = s.execute("object.blend.make", &json!({"orientation": "sideways"})).unwrap_err().to_string();
|
||||
assert!(error.contains("orientation must be page or path"), "{error}");
|
||||
assert_eq!(undo_len(&s), depth);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let defaults = s.execute("object.blend.info", &json!({})).unwrap();
|
||||
assert!(s.execute("object.blend.options", &json!({"orientation": "sideways"})).is_err());
|
||||
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap(), defaults);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor
|
||||
//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn object_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Whether the geometric bounds of `id` are `want` to within 10⁻⁹ pt.
|
||||
fn bounds_are(s: &Session, id: NodeId, want: vectorcraft_geom::Rect) -> bool {
|
||||
let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
|
||||
[(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// The largest distance of `points` from the path of `id`.
|
||||
fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 {
|
||||
let n = node(s, id);
|
||||
let path = n.path_data().unwrap();
|
||||
points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// (0, 0), (80, 0) and (0, 60) lie on the circle centered at (40, 30) with radius 50 (their
|
||||
/// right angle stands on the diameter). The circle is a live ellipse with the current paint, is
|
||||
/// selected, passes through the points to within the four-curve circle's error (about 0.03% of the
|
||||
/// radius), and one undo removes it.
|
||||
#[test]
|
||||
fn the_circle_through_three_given_points_is_exact_and_one_undo_step() {
|
||||
let mut s = session();
|
||||
let reference = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap());
|
||||
let undo = undo_len(&s);
|
||||
let points = [Point::new(0.0, 0.0), Point::new(80.0, 0.0), Point::new(0.0, 60.0)];
|
||||
let out = s.execute(C, &json!({"points": [[0, 0], [80, 0], [0, 60]]})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
let id = id_of(&out);
|
||||
let n = node(&s, id);
|
||||
match &n.kind {
|
||||
NodeKind::Path { live: Some(live), .. } => match live.as_ref() {
|
||||
LiveShape::Ellipse { w, h, pie, .. } => assert_eq!((*w, *h, *pie), (100.0, 100.0, (0.0, 360.0))),
|
||||
other => panic!("not a live ellipse: {other:?}"),
|
||||
},
|
||||
other => panic!("not a live shape: {other:?}"),
|
||||
}
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(-10.0, -20.0, 90.0, 80.0)));
|
||||
assert!(farthest_from_path(&s, id, &points) < 50.0 * 3e-4, "{}", farthest_from_path(&s, id, &points));
|
||||
assert_eq!(n.appearance, node(&s, reference).appearance, "the current paint, as the Ellipse tool draws");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [id]);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
}
|
||||
|
||||
/// Two points that are the same, or three on one line, are refused with a message; nothing is
|
||||
/// drawn and no undo step is recorded. Points nearly on one line still give their circle.
|
||||
#[test]
|
||||
fn coincident_or_collinear_points_are_refused() {
|
||||
let mut s = session();
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
for points in [json!([[10, 10], [10, 10], [50, 80]]), json!([[0, 0], [50, 50], [100, 100]]), json!([[5, 5], [5, 5], [5, 5]])] {
|
||||
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
|
||||
assert!(e.contains("no circle passes through these points"), "{points}: {e}");
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "{points}");
|
||||
}
|
||||
// 0.01 pt off a chord 200 pt long: the sagitta formula r = (h² + (L/2)²) / 2h.
|
||||
let out = s.execute(C, &json!({"points": [[100, 200], [300, 200], [200, 199.99]]})).unwrap();
|
||||
let want = (0.01f64 * 0.01 + 100.0 * 100.0) / 0.02;
|
||||
let (cx, cy, r) = (out["cx"].as_f64().unwrap(), out["cy"].as_f64().unwrap(), out["radius"].as_f64().unwrap());
|
||||
assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}");
|
||||
}
|
||||
|
||||
/// Points that are not three pairs of finite numbers are an error, not a fallback.
|
||||
#[test]
|
||||
fn malformed_points_are_refused() {
|
||||
let mut s = session();
|
||||
let undo = undo_len(&s);
|
||||
for points in [
|
||||
json!([[0, 0], [10, 0]]),
|
||||
json!([[0, 0], [10, 0], [0, 10], [5, 5]]),
|
||||
json!([[0, 0], [10, 0], [0]]),
|
||||
json!([[0, 0], [10, 0], ["0", 10]]),
|
||||
json!("0,0 10,0 0,10"),
|
||||
json!([[0, 0], [10, 0], [0, 10, 3]]),
|
||||
] {
|
||||
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
|
||||
assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}");
|
||||
}
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// With `points` left out, the three anchor points selected with Direct Selection give the
|
||||
/// circle, from one path or several; any other number of them is an error.
|
||||
#[test]
|
||||
fn three_direct_selected_anchor_points_give_the_circle() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<Value> = [(0, 0), (80, 0), (0, 60), (50, 120)].iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
|
||||
let path = id_of(&s.execute("path.create", &json!({ "anchors": anchors })).unwrap());
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap();
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
// Anchors of two paths.
|
||||
let other = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 60}, {"x": 0, "y": 200}]})).unwrap());
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
|
||||
let out = s.execute(C, &json!({"points": null})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}");
|
||||
// Two or four anchors, or a path of four anchors selected whole.
|
||||
for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
let e = s.execute(C, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
assert!(s.execute(C, &json!({})).is_err());
|
||||
// A path of three anchors selected whole counts all three, as the other anchor commands count
|
||||
// them; with an object that is not a path also selected, there is no circle.
|
||||
let triangle = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [triangle.0]})).unwrap();
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let text = id_of(&s.execute("text.create", &json!({"x": 300, "y": 300, "text": "A"})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [triangle.0, text.0]})).unwrap();
|
||||
assert!(s.execute(C, &json!({})).is_err());
|
||||
let undo = undo_len(&s);
|
||||
// Two selected segments hold three ends, which are not selected anchor points.
|
||||
s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3));
|
||||
let e = s.execute(C, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}");
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// With Align New Objects to Pixel Grid on, the circle is still drawn through the points: it is
|
||||
/// not pixel-aligned, so the grid does not move it.
|
||||
#[test]
|
||||
fn the_circle_is_not_moved_onto_the_pixel_grid() {
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
|
||||
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
let id = id_of(&s.execute(C, &json!({ "points": pairs })).unwrap());
|
||||
assert!(farthest_from_path(&s, id, &points) < 51.0 * 3e-4, "{}", farthest_from_path(&s, id, &points));
|
||||
assert!(!node(&s, id).extras().pixel_aligned);
|
||||
}
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..ViewInfo::default() }
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, mods: Mods, x: f64, y: f64) {
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), view()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one
|
||||
/// undo step; Escape drops the points placed so far.
|
||||
#[test]
|
||||
fn three_shift_clicks_with_the_ellipse_tool_draw_the_circle_through_them() {
|
||||
let mut s = session();
|
||||
s.select_tool("ellipse", view()).unwrap();
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
click(&mut s, shift, 100.0, 100.0);
|
||||
click(&mut s, shift, 180.0, 100.0);
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two points draw nothing yet");
|
||||
click(&mut s, shift, 100.0, 160.0);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(90.0, 80.0, 190.0, 180.0)));
|
||||
// Escape after two points: the next three clicks start afresh.
|
||||
click(&mut s, shift, 0.0, 0.0);
|
||||
click(&mut s, shift, 10.0, 300.0);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
click(&mut s, shift, 200.0, 200.0);
|
||||
click(&mut s, shift, 280.0, 200.0);
|
||||
let undo = undo_len(&s);
|
||||
click(&mut s, shift, 200.0, 260.0);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(190.0, 180.0, 290.0, 280.0)));
|
||||
}
|
||||
@@ -3160,6 +3160,27 @@ fn direction_handles_leave_out_hidden_and_locked_paths() {
|
||||
assert_eq!(selected(&s), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direction_handles_select_many_paths_in_groups_and_layers_in_paint_order() {
|
||||
let mut s = session();
|
||||
let mut paths: Vec<NodeId> = (0..60).map(|i| rect(&mut s, (i % 20) as f64 * 12.0, (i / 20) as f64 * 12.0, 10.0, 10.0)).collect();
|
||||
sel(&mut s, &paths[10..40]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
paths.extend((0..60).map(|i| rect(&mut s, (i % 20) as f64 * 12.0, 100.0 + (i / 20) as f64 * 12.0, 10.0, 10.0)));
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("select.object.directionHandles", &json!({})).unwrap()["anchors"], 4 * paths.len());
|
||||
let st = s.doc().unwrap();
|
||||
let mut want = vectorcraft_doc::Selection::default();
|
||||
for id in st.doc.paint_order(paths.iter().copied()) {
|
||||
want.add(id);
|
||||
want.anchors.insert(id, (0..4).map(|i| (0, i)).collect());
|
||||
}
|
||||
want.new_art = st.selection.new_art.clone();
|
||||
assert_eq!(st.selection.objects.len(), paths.len());
|
||||
assert_eq!(st.selection, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_point_and_area_text() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -767,6 +767,38 @@ fn package_copies_a_linked_eps_file_as_it_is() {
|
||||
assert!(s.doc().unwrap().doc.has_placed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_copies_the_files_a_linked_eps_files_native_document_places_beside_it() {
|
||||
let dir = Folder::new("package-placed-eps-links");
|
||||
let pic = dir.file("pics/photo.png");
|
||||
write(&pic, &png(600, 300, RED));
|
||||
let mut art = session();
|
||||
place(&mut art, &pic);
|
||||
std::fs::create_dir_all(dir.0.join("art")).unwrap();
|
||||
let src = dir.file("art/seal.eps");
|
||||
run(&mut art, "document.export", json!({"path": src, "format": "eps"}));
|
||||
let mut s = session();
|
||||
let placed = run(&mut s, "file.place", json!({"path": src}));
|
||||
assert_eq!(placed["linked"], true, "{placed}");
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
|
||||
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone(), r["warnings"].clone()), (Some(2), json!([]), json!([])), "{r}");
|
||||
let root = dir.0.join("out/poster Folder");
|
||||
assert_eq!(std::fs::read(root.join("Links/photo.png")).unwrap(), png(600, 300, RED));
|
||||
// The copy of the EPS file finds the picture beside it, not its preview.
|
||||
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
|
||||
std::fs::remove_dir_all(dir.0.join("pics")).unwrap();
|
||||
let copy = root.join("Links/seal.eps").to_string_lossy().into_owned();
|
||||
let shows_the_file = || {
|
||||
let bytes = std::fs::read(©).unwrap();
|
||||
let a = cmd::place::document::document_art("seal.eps", &bytes, Some(©), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap();
|
||||
a.doc.images.values().any(|b| !b.is_proxy())
|
||||
};
|
||||
assert!(shows_the_file());
|
||||
std::fs::remove_file(root.join("Links/photo.png")).unwrap();
|
||||
assert!(!shows_the_file(), "the preview only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_copies_a_linked_postscript_ai_file_the_document_holds_after_it_is_gone() {
|
||||
let dir = Folder::new("package-placed-ps-ai");
|
||||
|
||||
@@ -378,6 +378,60 @@ fn flare_spiral_and_polar_grid_draw_in_perspective() {
|
||||
assert_eq!(attached(&s, NodeId(r["id"].as_u64().unwrap())).map(|a| a.0), Some(Plane::Left));
|
||||
}
|
||||
|
||||
/// Alt-click (Option-click on macOS) with the Flare tool draws one flare with the tool's options as
|
||||
/// one undo step, without a dialog. On the active plane it is the flare the click-opened Flare Tool
|
||||
/// Options draw there; without the grid it is drawn flat. A plain click opens the dialog.
|
||||
#[test]
|
||||
fn an_alt_click_with_the_flare_tool_draws_the_flare_the_click_dialog_draws() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let (mut s, _) = persp_session();
|
||||
s.execute("perspective.grid.show", &json!({"visible": true})).unwrap();
|
||||
s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("flare", v).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"tool": "flare", "values": {"diameter": 40, "rays": 6, "ringsOn": false}})).unwrap();
|
||||
let options = s.tool_options_of("flare");
|
||||
let at = Point::new(300.0, 380.0);
|
||||
let alt = Mods { alt: true, ..Default::default() };
|
||||
let alt_click = |s: &mut Session| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(alt), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(alt), v).unwrap()
|
||||
};
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(alt_click(&mut s), vec![], "no dialog");
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(s.journal.last().unwrap().0, "perspective.draw");
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Left));
|
||||
let drawn = node(&s, id).geometric_bounds().unwrap();
|
||||
assert_eq!(s.tool_options_of("flare"), options, "the click leaves the options as they are");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id).geometric_bounds(), Some(drawn));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let params = vectorcraft_tools::extra::flare_params(&options, at);
|
||||
let (cmd, p) = crate::perspective_click(&s, "shape.flare", ¶ms, at).unwrap();
|
||||
let dialog = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(node(&s, dialog).geometric_bounds(), Some(drawn), "the flare the dialog's OK draws");
|
||||
// A click above the ground plane's horizon draws nothing and reports the error.
|
||||
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
|
||||
let above = grid(&s).horizon - 50.0;
|
||||
let n = undo_len(&s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, above).with_mods(alt), v).unwrap();
|
||||
assert!(s.pointer(&PointerEvent::new(PointerKind::Up, at.x, above).with_mods(alt), v).is_err());
|
||||
assert_eq!(undo_len(&s), n);
|
||||
// Without the grid the flare is drawn flat; a plain click opens the dialog.
|
||||
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
|
||||
assert_eq!(alt_click(&mut s), vec![]);
|
||||
assert_eq!(s.journal.last().unwrap().0, "shape.flare");
|
||||
let flat = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert_eq!(attached(&s, flat), None);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), v).unwrap();
|
||||
let ui = s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), v).unwrap();
|
||||
assert_eq!(ui, vec![UiRequest::Dialog("flare".into(), json!({"x": at.x, "y": at.y}))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() {
|
||||
let (mut s, _) = persp_session();
|
||||
|
||||
@@ -1212,6 +1212,30 @@ fn a_click_of_the_place_cursor_asks_the_frontend_to_place_the_file_when_asked_to
|
||||
assert_eq!(s.journal.last(), at_once.journal.last());
|
||||
}
|
||||
|
||||
/// A Shift-click of the place cursor asks the frontend for the file's import options
|
||||
/// (`showImportOptions: true`); headless, with no frontend to ask, it places the file as a click
|
||||
/// does.
|
||||
#[test]
|
||||
fn a_shift_click_of_the_place_cursor_places_headless_as_a_click_does() {
|
||||
let view = ViewInfo::default();
|
||||
let files: Vec<Value> = ["a.png", "b.png"].iter().map(|n| file(n, &png(40, 20, [9, 9, 9, 255], None))).collect();
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let (mut headless, mut app) = (session(), session());
|
||||
app.place_cursor_requests = true;
|
||||
let mut reqs = vec![];
|
||||
for s in [&mut headless, &mut app] {
|
||||
s.execute("file.place.queue", &json!({"files": files})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0).with_mods(shift), view).unwrap();
|
||||
reqs = s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0).with_mods(shift), view).unwrap();
|
||||
}
|
||||
let [UiRequest::Place(p)] = &reqs[..] else { panic!("{reqs:?}") };
|
||||
assert_eq!(p["showImportOptions"], true);
|
||||
let [img] = &top_children(&headless)[..] else { panic!("one image placed") };
|
||||
let b = img.geometric_bounds().unwrap();
|
||||
assert_eq!([b.x0, b.y0, b.width(), b.height()], [10.0, 10.0, 40.0, 20.0]);
|
||||
assert_eq!(headless.tool_options()["names"], json!(["b.png"]));
|
||||
}
|
||||
|
||||
/// Files read for the place cursor apart from the session ([`Session::prepare_place_queue`], then
|
||||
/// [`cmd::place::QueueJob::read`] on another thread and [`Session::place_queue_read`]) load it as
|
||||
/// `file.place.queue` loads it: the same reply, with the files that can't be read skipped, and the
|
||||
|
||||
@@ -47,6 +47,81 @@ fn setup_is_saved_with_the_document_as_one_undo_step() {
|
||||
assert!(vectorcraft_format::load(v.to_string().as_bytes()).unwrap().print_setup.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprint_black_is_saved_with_the_setup_and_in_presets() {
|
||||
let (mut s, _) = session();
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["output"]["overprintBlack"], false, "off by default");
|
||||
let v = s.execute("print.setup", &json!({"settings": {"output": {"mode": "separations", "overprintBlack": true}}})).unwrap();
|
||||
assert_eq!(v["settings"]["output"]["overprintBlack"], true);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert!(back.print_setup.as_ref().is_some_and(|p| p["output"]["overprintBlack"] == true), "kept in the native file");
|
||||
// Settings saved before the option load with it off; a value that is not true or false is refused.
|
||||
let old: vectorcraft_pdf::PrintSettings = serde_json::from_value(json!({"output": {"mode": "separations"}})).unwrap();
|
||||
assert!(!old.output.overprint_black);
|
||||
assert!(matches!(s.execute("print.setup", &json!({"settings": {"output": {"overprintBlack": "yes"}}})), Err(EngineError::BadParams { .. })));
|
||||
// Print presets keep it and list it as a change from [Default].
|
||||
let mut s = Session::new();
|
||||
s.execute("print.presets.save", &json!({"name": "Seps", "settings": {"output": {"overprintBlack": true}}})).unwrap();
|
||||
assert!(s.prefs.print_presets[0].settings.output.overprint_black);
|
||||
let v = s.execute("print.presets.list", &json!({})).unwrap();
|
||||
let changed: Vec<&str> = v["presets"][1]["changed"].as_array().unwrap().iter().map(|c| c["option"].as_str().unwrap()).collect();
|
||||
assert_eq!(changed, ["output.overprintBlack"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scale_link_keeps_width_and_height_equal() {
|
||||
let (mut s, _) = session();
|
||||
let scale = |s: &mut Session, p: Value| s.execute("print.setup", &json!({ "settings": p })).unwrap()["settings"]["scale"].clone();
|
||||
assert_eq!(scale(&mut s, json!({})), json!({"width": 100.0, "height": 100.0, "linked": true}), "on for a new job");
|
||||
// Linked, one percentage sets the other, whichever it is.
|
||||
assert_eq!(scale(&mut s, json!({"scaling": "custom", "scale": {"width": 40}})), json!({"width": 40.0, "height": 40.0, "linked": true}));
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"height": 250}})), json!({"width": 250.0, "height": 250.0, "linked": true}));
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"width": 60, "height": 60.0}})), json!({"width": 60.0, "height": 60.0, "linked": true}));
|
||||
// Two different percentages with linked: true are refused and keep what was saved.
|
||||
let apart = s.execute("print.setup", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": true}}}));
|
||||
assert!(matches!(apart, Err(EngineError::BadParams { .. })), "{apart:?}");
|
||||
assert!(s.execute("print.preview", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": true}}})).is_err());
|
||||
// `linked: null` keeps the saved link, as null keeps any saved setting.
|
||||
let kept = s.execute("print.setup", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": null}}}));
|
||||
assert!(matches!(kept, Err(EngineError::BadParams { .. })), "{kept:?}");
|
||||
assert_eq!(scale(&mut s, json!({}))["width"], 60.0);
|
||||
// Without linked, two different percentages turn the link off and print as given.
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"width": 50, "height": 200}})), json!({"width": 50.0, "height": 200.0, "linked": false}));
|
||||
assert_eq!(s.execute("print.preview", &json!({})).unwrap()["sheets"][0]["scale"], json!([50.0, 200.0]));
|
||||
// Unlinked, each changes alone; turning the link on sets the height to the width.
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"height": 120}})), json!({"width": 50.0, "height": 120.0, "linked": false}));
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"linked": true}})), json!({"width": 50.0, "height": 50.0, "linked": true}));
|
||||
assert_eq!(s.execute("print.preview", &json!({})).unwrap()["sheets"][0]["scale"], json!([50.0, 50.0]));
|
||||
// Kept in the native file and in print presets.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(back.print_setup.as_ref().map(|p| p["scale"].clone()), Some(json!({"width": 50.0, "height": 50.0, "linked": true})));
|
||||
s.execute("print.presets.save", &json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap();
|
||||
let preset = s.prefs.print_presets.iter().find(|p| p.name == "Apart").map(|p| p.settings.scale.clone());
|
||||
assert_eq!(preset.map(|p| (p.width, p.height, p.linked)), Some((30.0, 90.0, false)));
|
||||
assert_eq!(scale(&mut s, json!({}))["linked"], true, "saving a preset leaves the document's settings");
|
||||
let v = s.execute("print.setup", &json!({"preset": "Apart"})).unwrap();
|
||||
assert_eq!(v["settings"]["scale"], json!({"width": 30.0, "height": 90.0, "linked": false}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_saved_without_the_link_keeps_its_width_and_height() {
|
||||
let (mut s, _) = session();
|
||||
// Settings saved before the link had no `linked`: they print as they did, unlinked.
|
||||
let mut old = serde_json::to_value(vectorcraft_pdf::PrintSettings::default()).unwrap();
|
||||
old["scaling"] = json!("custom");
|
||||
old["scale"] = json!({"width": 50, "height": 200});
|
||||
let mut doc = (*s.doc().unwrap().doc).clone();
|
||||
doc.print_setup = Some(old);
|
||||
s.doc_mut().unwrap().doc = std::sync::Arc::new(doc);
|
||||
let pv = s.execute("print.preview", &json!({})).unwrap();
|
||||
assert_eq!(pv["sheets"][0]["scale"], json!([50.0, 200.0]));
|
||||
assert_eq!(pv["settings"]["scale"]["linked"], false);
|
||||
// One percentage changes alone until the link is turned on.
|
||||
assert_eq!(s.execute("print.preview", &json!({"settings": {"scale": {"width": 80}}})).unwrap()["sheets"][0]["scale"], json!([80.0, 200.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_writes_the_saved_setup_with_overrides() {
|
||||
let (mut s, _) = session();
|
||||
|
||||
@@ -395,6 +395,56 @@ fn expand_rasterize_then_transform_matches_canvas() {
|
||||
assert!(matches!(&n.kind, vectorcraft_doc::NodeKind::Group { children, .. } if children.is_empty()), "{:?}", n.kind);
|
||||
}
|
||||
|
||||
/// With copies, the Transform effect after Rasterize places the one image on the original and on
|
||||
/// each copy: Expand Appearance and PDF export make a group of the image placed by each copy's
|
||||
/// map, the last copy lowest and the original on top, as the canvas draws it, all on the pixels
|
||||
/// Object › Rasterize makes of the art.
|
||||
#[test]
|
||||
fn expand_rasterize_then_copying_transform_places_the_image_on_each_copy() {
|
||||
let mut o = session();
|
||||
red_rectangle(&mut o);
|
||||
let made = id(&o.execute("object.rasterize", &json!({"ppi": 72, "background": "white", "addAround": 2})).unwrap());
|
||||
let od = &o.doc().unwrap().doc;
|
||||
let (w, h, xf, png, _) = rasterized(od, od.node(made).unwrap());
|
||||
let about =
|
||||
|m: vectorcraft_geom::Affine| vectorcraft_geom::Affine::translate((70.5, 65.25)) * m * vectorcraft_geom::Affine::translate((-70.5, -65.25));
|
||||
let turn = |deg: f64| about(vectorcraft_geom::Affine::rotate(-deg.to_radians()));
|
||||
let cases = [
|
||||
(json!({"moveH": 50, "copies": 2}), [vectorcraft_geom::Affine::translate((100.0, 0.0)), vectorcraft_geom::Affine::translate((50.0, 0.0))]),
|
||||
(json!({"rotate": 30, "copies": 2}), [turn(60.0), turn(30.0)]),
|
||||
];
|
||||
for (params, [lowest, middle]) in cases {
|
||||
let mut s = session();
|
||||
let r = red_rectangle(&mut s);
|
||||
let raster = json!({"useDocumentResolution": false, "resolution": 72, "background": "white", "addAround": 2});
|
||||
s.execute("effect.apply", &json!({"effect": "rasterize", "params": raster, "ids": [r.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": params.clone(), "ids": [r.0]})).unwrap();
|
||||
let check = |d: &Document, n: &vectorcraft_doc::Node, what: &str| {
|
||||
let NodeKind::Group { children, clip: false } = &n.kind else { panic!("{what} {params}: a group, {:?}", n.kind_label()) };
|
||||
assert_eq!(children.len(), 3, "{what} {params}");
|
||||
let mut keys = std::collections::HashSet::new();
|
||||
for (c, map) in children.iter().zip([lowest, middle, vectorcraft_geom::Affine::IDENTITY]) {
|
||||
let (w2, h2, xf2, png2, _) = rasterized(d, c);
|
||||
assert_eq!((w2, h2), (w, h), "{what} {params}");
|
||||
assert!(png2 == png, "{what} {params}: the same pixels");
|
||||
let want = map * xf;
|
||||
assert!(xf2.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{what} {params}: {xf2:?} {want:?}");
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
keys.insert(im.key.clone());
|
||||
}
|
||||
}
|
||||
assert_eq!(keys.len(), 1, "{what} {params}: one image for the three placements");
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
n.walk(&mut |c| assert!(ids.insert(c.id), "{what} {params}: id {:?} twice", c.id));
|
||||
};
|
||||
let flat = crate::flatten_raster_effects(&s.doc().unwrap().doc).unwrap();
|
||||
check(&flat, &flat.layers[0].children().unwrap()[0], "PDF export");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [r.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
check(d, d.node(r).unwrap(), "Expand Appearance");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipping_mask_follows_the_art_its_geometry_effects_draw() {
|
||||
let clip = |s: &Session, n: NodeId| match &s.doc().unwrap().doc.node(n).unwrap().kind {
|
||||
|
||||
@@ -328,6 +328,33 @@ fn contour_with_rounding(pts: &[Point], rounded: f64) -> PathData {
|
||||
PathData::single(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// The circle through the points `a`, `b` and `c`: its center and radius. `None` when two of the
|
||||
/// points are the same or the three lie on one line, which this takes to be when twice the
|
||||
/// triangle's area is at most 10⁻¹⁰ of its longest side squared.
|
||||
pub fn circle_through(a: Point, b: Point, c: Point) -> Option<(Point, f64)> {
|
||||
// The corner opposite the longest side is the origin, so the two shorter sides are used.
|
||||
let (ab, bc, ca) = ((b - a).hypot2(), (c - b).hypot2(), (a - c).hypot2());
|
||||
let (o, p, q, longest) = if bc >= ab && bc >= ca {
|
||||
(a, b, c, bc)
|
||||
} else if ca >= ab {
|
||||
(b, c, a, ca)
|
||||
} else {
|
||||
(c, a, b, ab)
|
||||
};
|
||||
let (u, v) = (p - o, q - o);
|
||||
let cross = u.cross(v);
|
||||
// Not a number, or nearly zero: no circle (a not-a-number side fails the finite check below).
|
||||
if cross.is_nan() || cross.abs() <= 1e-10 * longest {
|
||||
return None;
|
||||
}
|
||||
let (uu, vv) = (u.hypot2(), v.hypot2());
|
||||
let d = 2.0 * cross;
|
||||
let offset = Vec2::new((v.y * uu - u.y * vv) / d, (u.x * vv - v.x * uu) / d);
|
||||
let center = o + offset;
|
||||
let radius = offset.hypot();
|
||||
(center.is_finite() && radius.is_finite()).then_some((center, radius))
|
||||
}
|
||||
|
||||
/// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre.
|
||||
pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData {
|
||||
let n = sides.max(3);
|
||||
@@ -702,6 +729,47 @@ mod tests {
|
||||
assert!(ellipse_pie(r, f64::NAN, 10.0).anchor_count() == 4, "not a number: the whole ellipse");
|
||||
}
|
||||
|
||||
/// The circle through three points against the closed form: (0, 0), (8, 0) and (0, 6) lie on
|
||||
/// the circle with the hypotenuse (8, 0)–(0, 6) as its diameter, center (4, 3) and radius 5.
|
||||
#[test]
|
||||
fn the_circle_through_three_points_has_the_closed_form_center_and_radius() {
|
||||
let (o, a, b) = (Point::ORIGIN, Point::new(8.0, 0.0), Point::new(0.0, 6.0));
|
||||
for (p, q, r) in [(o, a, b), (a, b, o), (b, o, a), (b, a, o)] {
|
||||
let (c, radius) = circle_through(p, q, r).unwrap();
|
||||
assert!(c.distance(Point::new(4.0, 3.0)) < 1e-12 && (radius - 5.0).abs() < 1e-12, "{c:?} {radius}");
|
||||
}
|
||||
// Moved far from the origin, the answer moves with the points.
|
||||
let far = Vec2::new(3.0e6, -2.0e6);
|
||||
let (c, radius) = circle_through(o + far, a + far, b + far).unwrap();
|
||||
assert!(c.distance(Point::new(4.0, 3.0) + far) < 1e-6 && (radius - 5.0).abs() < 1e-6, "{c:?} {radius}");
|
||||
}
|
||||
|
||||
/// Two points that are the same, or three on one line, give no circle.
|
||||
#[test]
|
||||
fn coincident_or_collinear_points_give_no_circle() {
|
||||
let (a, b) = (Point::new(1.0, 2.0), Point::new(5.0, 7.0));
|
||||
assert_eq!(circle_through(a, a, b), None);
|
||||
assert_eq!(circle_through(a, b, b), None);
|
||||
assert_eq!(circle_through(a, a, a), None);
|
||||
assert_eq!(circle_through(a, b, a.midpoint(b)), None);
|
||||
assert_eq!(circle_through(a, b, a + (b - a) * 3.0), None);
|
||||
assert_eq!(circle_through(a, b, Point::new(f64::NAN, 0.0)), None);
|
||||
}
|
||||
|
||||
/// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta
|
||||
/// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular
|
||||
/// bisector; a point 10⁻¹² off it does not.
|
||||
#[test]
|
||||
fn nearly_collinear_points_give_a_stable_circle() {
|
||||
let (a, b) = (Point::new(-1000.0, 0.0), Point::new(1000.0, 0.0));
|
||||
let h = 1e-4;
|
||||
let (c, radius) = circle_through(a, b, Point::new(0.0, h)).unwrap();
|
||||
let want = (h * h + 1000.0 * 1000.0) / (2.0 * h);
|
||||
assert!((radius - want).abs() / want < 1e-9, "{radius} vs {want}");
|
||||
assert!(c.x.abs() < 1e-6 && (c.y - (h - want)).abs() / want < 1e-9, "{c:?}");
|
||||
assert_eq!(circle_through(a, b, Point::new(0.0, 1e-12)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_is_4_corners_clockwise() {
|
||||
let p = rectangle(Rect::new(0.0, 0.0, 100.0, 50.0));
|
||||
|
||||
@@ -913,7 +913,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.sampleScreenColor",
|
||||
"Sample Color from Screen",
|
||||
"",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS and in browsers) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
),
|
||||
(
|
||||
"ui.newBrush",
|
||||
|
||||
@@ -10,7 +10,13 @@
|
||||
//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or
|
||||
//! skewed with it.
|
||||
//! - Text becomes point type in the font the file names, underlined or struck through as the font
|
||||
//! is, and clipped to its rectangle when the file clips it.
|
||||
//! is, and clipped to its rectangle when the file clips it. Characters the file gives advances
|
||||
//! for are spaced by them: tracking on each character, with pair kerning off. On a single left
|
||||
//! to right line, the characters after an advance that tracking can't give (further than its
|
||||
//! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between.
|
||||
//! It is also carried on to the end of the last character's advance. Type on more than one line
|
||||
//! is placed a line at a time: each line is aligned by its own advances and split as a single
|
||||
//! line is.
|
||||
//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around
|
||||
//! the whole picture clips nothing and is left out.
|
||||
//!
|
||||
@@ -28,7 +34,7 @@ use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeId,
|
||||
NodeKind, StrokeLayer, TextObject,
|
||||
NodeKind, StrokeLayer, TextObject, TextRun,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes};
|
||||
|
||||
@@ -524,7 +530,25 @@ impl Mapper {
|
||||
}
|
||||
|
||||
fn text(&mut self, t: &craft_metafile::Text, chain: Vec<Arc<Clip>>) {
|
||||
let s: String = t.text.chars().filter(|c| *c != '\0').collect();
|
||||
// The characters without NULs, and each one's advance (text units) when the file gives
|
||||
// one for every character: a NUL's advance goes to the character before it, or moves the
|
||||
// start when the string begins with one.
|
||||
let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite());
|
||||
let (mut s, mut dx, mut lead) = (String::new(), Vec::new(), 0.0f64);
|
||||
for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) {
|
||||
if c != '\0' {
|
||||
s.push(c);
|
||||
dx.push(d);
|
||||
} else if let Some(last) = dx.last_mut() {
|
||||
*last += d;
|
||||
} else {
|
||||
lead += d;
|
||||
}
|
||||
}
|
||||
if !advances {
|
||||
dx.clear();
|
||||
lead = 0.0;
|
||||
}
|
||||
if s.trim().is_empty() || t.color[3] == 0 {
|
||||
return;
|
||||
}
|
||||
@@ -553,6 +577,11 @@ impl Mapper {
|
||||
.into();
|
||||
style.underline = f.underline;
|
||||
style.strikethrough = f.strike;
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Characters placed by their advances take no pair kerning: the advances place them.
|
||||
if !dx.is_empty() {
|
||||
style.kerning = Some(0.0);
|
||||
}
|
||||
// Where the baseline is below the reference point.
|
||||
let drop = match t.v_align {
|
||||
VAlign::Baseline => 0.0,
|
||||
@@ -560,17 +589,110 @@ impl Mapper {
|
||||
VAlign::Top => 0.8 * size,
|
||||
};
|
||||
let origin = self.xf * Point::new(t.transform[4], t.transform[5]);
|
||||
let mut text = TextObject::point(Point::ZERO, &s, style);
|
||||
text.xf = Affine::translate(origin.to_vec2()) * shape * Affine::translate((0.0, drop));
|
||||
text.para.justify = match t.h_align {
|
||||
let base = Affine::translate(origin.to_vec2()) * shape;
|
||||
let justify = match t.h_align {
|
||||
HAlign::Center => Justify::Center,
|
||||
HAlign::Right => Justify::Right,
|
||||
HAlign::Left => Justify::Left,
|
||||
};
|
||||
text.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text).bounds);
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
|
||||
n.opacity = f32::from(t.color[3]) / 255.0;
|
||||
self.push(chain, n);
|
||||
let point = |s: &str| {
|
||||
let mut text = TextObject::point(Point::ZERO, s, style.clone());
|
||||
text.para.justify = justify;
|
||||
text
|
||||
};
|
||||
let whole = point(&s);
|
||||
let opacity = f32::from(t.color[3]) / 255.0;
|
||||
if dx.is_empty() {
|
||||
let mut text = whole;
|
||||
text.xf = base * Affine::translate((0.0, drop));
|
||||
text.cached_bounds = Some(vectorcraft_text::layout(db, &text).bounds);
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
|
||||
n.opacity = opacity;
|
||||
self.push(chain, n);
|
||||
return;
|
||||
}
|
||||
// Text units grow by `k` along the baseline in the text object's own space.
|
||||
let dx: Vec<f64> = dx.iter().map(|d| d * k).collect();
|
||||
let chars: Vec<char> = s.chars().collect();
|
||||
let line = Line { base, drop, align: &t.h_align, decorated: f.underline || f.strike, color: t.color, opacity, point: &point, chain: &chain };
|
||||
// Type on more than one line is placed a line at a time, each line aligned by its own
|
||||
// advances (layout leaves the tracking after a line's last character out of the width it
|
||||
// aligns, and each line ends with its own) and its underline carried on to its own end.
|
||||
let laid = vectorcraft_text::layout(db, &whole);
|
||||
if laid.lines.len() > 1 {
|
||||
// Where each character starts (bytes): the character a byte offset starts is found by
|
||||
// a search.
|
||||
let starts: Vec<usize> = s.char_indices().map(|(at, _)| at).collect();
|
||||
let count = |to: usize| starts.partition_point(|at| *at < to);
|
||||
let first = laid.lines.first().map_or(0.0, |l| l.baseline);
|
||||
for (n, l) in laid.lines.iter().enumerate() {
|
||||
let (from, to) = (count(l.start), count(l.end));
|
||||
let (Some(cs), Some(dx)) = (chars.get(from..to), dx.get(from..to)) else { continue };
|
||||
// A leading NUL's advance comes before the first line only.
|
||||
let lead = if n == 0 { lead * k } else { 0.0 };
|
||||
let down = l.baseline - first;
|
||||
self.line(&line, cs, dx, lead, if down.is_finite() { down } else { 0.0 });
|
||||
}
|
||||
} else {
|
||||
self.line(&line, &chars, &dx, lead * k, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One line of text with advances `dx` (points along the baseline) for its characters `chars`,
|
||||
/// `down` below the first line's baseline: in pieces, each a text object of its own, a new
|
||||
/// piece after each cluster that tracking can't space by its advance.
|
||||
fn line(&mut self, line: &Line, chars: &[char], dx: &[f64], lead: f64, down: f64) {
|
||||
if chars.is_empty() || (chars.iter().all(|c| c.is_whitespace()) && !line.decorated) {
|
||||
return;
|
||||
}
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let s: String = chars.iter().collect();
|
||||
let (pieces, text, laid) = pieces((line.point)(&s), db, dx);
|
||||
let split = pieces.len() > 1;
|
||||
let mut tracked = Some((text, laid));
|
||||
// Along the baseline (the text object's own space), where the next piece starts from the
|
||||
// reference point: the line as long as its advances (a leading NUL's included), where the
|
||||
// alignment puts it.
|
||||
let mut at = aligned(lead, dx.iter().sum(), line.align);
|
||||
let last = pieces.len().saturating_sub(1);
|
||||
for (i, (from, to)) in pieces.into_iter().enumerate() {
|
||||
let piece: String = chars.get(from..to).unwrap_or_default().iter().collect();
|
||||
let dx = dx.get(from..to).unwrap_or_default();
|
||||
// Blanks of their own draw nothing unless they are underlined or struck through.
|
||||
if piece.trim().is_empty() && !line.decorated {
|
||||
at += dx.iter().sum::<f64>();
|
||||
continue;
|
||||
}
|
||||
// The line in one piece was already tracked to its advances.
|
||||
let (mut text, laid) = match tracked.take().filter(|_| !split) {
|
||||
Some(done) => done,
|
||||
None => {
|
||||
let mut text = (line.point)(&piece);
|
||||
let laid = advanced(&mut text, db, dx);
|
||||
(text, laid)
|
||||
}
|
||||
};
|
||||
let x0 = laid.lines.first().map_or(0.0, |l| l.x0);
|
||||
let start = if (at - x0).is_finite() { at - x0 } else { 0.0 };
|
||||
let span: f64 = dx.iter().sum();
|
||||
at += span;
|
||||
text.xf = line.base * Affine::translate((start, line.drop + down));
|
||||
text.cached_bounds = Some(laid.bounds);
|
||||
// An underline or strikethrough runs on across the space an advance leaves before
|
||||
// the next piece, or after the line's last character, as one bar per piece from where
|
||||
// its own bars end.
|
||||
let gap = if (split && i < last) || (i == last && line.decorated) { gaps(&laid, db, &text, x0 + span) } else { BezPath::new() };
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text.clone())));
|
||||
n.opacity = line.opacity;
|
||||
self.push(line.chain.to_vec(), n);
|
||||
if !gap.elements().is_empty() {
|
||||
let mut gap = gap;
|
||||
gap.apply_affine(text.xf);
|
||||
if let Some(n) = self.path_node(gap, Some(line.color), None, false) {
|
||||
self.push(line.chain.to_vec(), n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The document: what was drawn on one layer, clipped art in clipping groups.
|
||||
@@ -595,6 +717,193 @@ impl Mapper {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a line `lead + span` long (along the baseline) starts from the reference point, as
|
||||
/// `align` puts it, and `lead` on from there: where its first character starts.
|
||||
fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 {
|
||||
let total = lead + span;
|
||||
lead + match align {
|
||||
HAlign::Left => 0.0,
|
||||
HAlign::Center => -total / 2.0,
|
||||
HAlign::Right => -total,
|
||||
}
|
||||
}
|
||||
|
||||
/// What every piece of a text record's lines shares: the text space (`base`, with the baseline
|
||||
/// `drop` below the reference point), the alignment, whether the type is underlined or struck
|
||||
/// through, its color and opacity, a point type object of a string in its style, and its clips.
|
||||
struct Line<'a> {
|
||||
base: Affine,
|
||||
drop: f64,
|
||||
align: &'a HAlign,
|
||||
decorated: bool,
|
||||
color: [u8; 4],
|
||||
opacity: f32,
|
||||
point: &'a dyn Fn(&str) -> TextObject,
|
||||
chain: &'a [Arc<Clip>],
|
||||
}
|
||||
|
||||
/// The most times [`advanced`] lays the type out again to correct its tracking.
|
||||
const ADVANCE_PASSES: usize = 3;
|
||||
|
||||
/// Sets `t`'s tracking so that each cluster (a ligature, a letter with its marks) advances by the
|
||||
/// sum of its characters' entries of `dx` (points along the baseline), and gives its layout.
|
||||
/// Tracking can change how the type is shaped (it drops standard ligatures past a limit), so the
|
||||
/// tracking is measured against the type laid out with the last tracking and corrected, a few
|
||||
/// times at most. A tracking that would pass the attribute's range is held at its end. When the
|
||||
/// corrections still miss (a ligature that forms at one tracking and breaks at the next), standard
|
||||
/// ligatures are turned off and the tracking is corrected again.
|
||||
fn advanced(t: &mut TextObject, db: &vectorcraft_text::FontDb, dx: &[f64]) -> vectorcraft_text::TextLayout {
|
||||
let laid = tracked(t, db, dx);
|
||||
let (_, clusters) = clusters(t, &laid, dx);
|
||||
let settled = clusters.iter().all(|c| (c.want - c.has).abs() <= c.em * 1e-4 || !(TRACKING.0..=TRACKING.1).contains(&c.wanted()));
|
||||
if settled {
|
||||
return laid;
|
||||
}
|
||||
for r in &mut t.runs {
|
||||
if !r.style.features.iter().any(|f| f == "-liga") {
|
||||
r.style.features.push("-liga".to_string());
|
||||
}
|
||||
}
|
||||
tracked(t, db, dx)
|
||||
}
|
||||
|
||||
/// `t` laid out with its tracking corrected towards `dx` at most [`ADVANCE_PASSES`] times.
|
||||
fn tracked(t: &mut TextObject, db: &vectorcraft_text::FontDb, dx: &[f64]) -> vectorcraft_text::TextLayout {
|
||||
let mut laid = vectorcraft_text::layout(db, t);
|
||||
for _ in 0..ADVANCE_PASSES {
|
||||
match retracked(t, &laid, dx) {
|
||||
Some(runs) => t.runs = runs,
|
||||
None => break,
|
||||
}
|
||||
laid = vectorcraft_text::layout(db, t);
|
||||
}
|
||||
laid
|
||||
}
|
||||
|
||||
/// The tracking range of a character (thousandths of an em), as the Character panel holds it.
|
||||
const TRACKING: (f64, f64) = (-1000.0, 10000.0);
|
||||
|
||||
/// One cluster of characters (a ligature, a letter with its marks): the advance the file wants
|
||||
/// for it and its advance laid out (points, tracking included), its em as its first character's
|
||||
/// Horizontal Scale draws it (which tracking is measured in) and its tracking.
|
||||
struct Cluster {
|
||||
want: f64,
|
||||
has: f64,
|
||||
em: f64,
|
||||
tracking: f64,
|
||||
}
|
||||
|
||||
impl Cluster {
|
||||
/// The tracking that gives the cluster the advance the file wants, not held to the range.
|
||||
fn wanted(&self) -> f64 {
|
||||
self.tracking + (self.want - self.has) / self.em * 1000.0
|
||||
}
|
||||
}
|
||||
|
||||
/// `t`'s clusters as `laid` sets them, with the sum of their characters' entries of `dx`, and the
|
||||
/// cluster of each character.
|
||||
fn clusters(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) -> (Vec<usize>, Vec<Cluster>) {
|
||||
// The advance of the cluster that starts at each byte offset.
|
||||
let mut own: HashMap<usize, f64> = HashMap::new();
|
||||
for g in &laid.glyphs {
|
||||
*own.entry(g.byte).or_insert(0.0) += g.advance;
|
||||
}
|
||||
let mut cluster = Vec::new();
|
||||
let mut clusters: Vec<Cluster> = Vec::new();
|
||||
let mut byte = 0;
|
||||
for r in &t.runs {
|
||||
let em = (r.style.size * vectorcraft_text::spacing_scale(&r.style, false)).max(1e-3);
|
||||
for c in r.text.chars() {
|
||||
let want = dx.get(cluster.len()).copied().unwrap_or(0.0);
|
||||
match (own.get(&byte), clusters.last_mut()) {
|
||||
(None, Some(last)) => last.want += want,
|
||||
(has, _) => clusters.push(Cluster { want, has: has.copied().unwrap_or(0.0), em, tracking: r.style.tracking }),
|
||||
}
|
||||
cluster.push(clusters.len().saturating_sub(1));
|
||||
byte += c.len_utf8();
|
||||
}
|
||||
}
|
||||
(cluster, clusters)
|
||||
}
|
||||
|
||||
/// `t`'s characters in pieces (first and past the last character index) that tracking can space
|
||||
/// by their advances `dx`: a piece ends after each cluster whose advance, once tracked, still
|
||||
/// differs from the one the file gives (further than the tracking range reaches, or a tab, which
|
||||
/// layout advances to its tab stop). The clusters are the ones the type has once tracked
|
||||
/// towards its advances, so that a ligature the tracking breaks apart can split between its letters.
|
||||
/// Type laid out right to left, or on more than one line, stays in one piece: pieces are placed
|
||||
/// one after another left to right along a single line. Also gives `t` tracked to its advances and
|
||||
/// its layout, for the type that stays in one piece.
|
||||
fn pieces(mut t: TextObject, db: &vectorcraft_text::FontDb, dx: &[f64]) -> (Vec<(usize, usize)>, TextObject, vectorcraft_text::TextLayout) {
|
||||
let laid = advanced(&mut t, db, dx);
|
||||
let (cluster, clusters) = clusters(&t, &laid, dx);
|
||||
let mut out = vec![];
|
||||
let mut from = 0;
|
||||
if laid.lines.len() <= 1 && !laid.glyphs.iter().any(|g| g.rtl) {
|
||||
for (i, c) in cluster.iter().enumerate() {
|
||||
let ends = cluster.get(i + 1) != Some(c);
|
||||
if ends && clusters.get(*c).is_some_and(|c| (c.want - c.has).abs() > c.em * 1e-4) {
|
||||
out.push((from, i + 1));
|
||||
from = i + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if from < cluster.len() || out.is_empty() {
|
||||
out.push((from, cluster.len()));
|
||||
}
|
||||
(out, t, laid)
|
||||
}
|
||||
|
||||
/// The underline and strikethrough of `t` (laid out as `laid`) carried on to `end` along the
|
||||
/// baseline, in text space: the runs of a piece each draw bars of their own, and only the bars
|
||||
/// that end the piece (furthest along) are carried on.
|
||||
fn gaps(laid: &vectorcraft_text::TextLayout, db: &vectorcraft_text::FontDb, t: &TextObject, end: f64) -> BezPath {
|
||||
let bars: Vec<Rect> = vectorcraft_text::decorations(laid, db, t).iter().map(|(_, bar)| bar.bounding_box()).collect();
|
||||
let far = bars.iter().map(|b| b.x1).fold(f64::NEG_INFINITY, f64::max);
|
||||
let mut bp = BezPath::new();
|
||||
for b in bars.into_iter().filter(|b| b.x1 >= far - 1e-6) {
|
||||
// A thousandth of a point is short of anything drawn.
|
||||
if end > b.x1 + 1e-3 && end.is_finite() {
|
||||
bp.extend(shapes::rectangle(Rect::new(b.x1, b.y0, end, b.y1)).to_bezpath());
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// `t`'s runs with each cluster's tracking corrected by how far its advance in `laid` is from the
|
||||
/// sum of its characters' entries of `dx`; None when every cluster is already within a ten
|
||||
/// thousandth of an em of it. Layout adds a cluster's tracking once, so every character of a
|
||||
/// cluster takes the same value and a cluster stays in one run. Characters with the same tracking
|
||||
/// share a run.
|
||||
fn retracked(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) -> Option<Vec<TextRun>> {
|
||||
let (cluster, clusters) = clusters(t, laid, dx);
|
||||
if clusters.iter().all(|c| (c.want - c.has).abs() <= c.em * 1e-4) {
|
||||
return None;
|
||||
}
|
||||
let tracking: Vec<f64> = clusters
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let v = c.wanted().clamp(TRACKING.0, TRACKING.1);
|
||||
// Hundredths of a thousandth of an em, so that characters spaced alike share a run.
|
||||
if v.is_finite() { (v * 100.0).round() / 100.0 } else { 0.0 }
|
||||
})
|
||||
.collect();
|
||||
let mut out: Vec<TextRun> = Vec::with_capacity(t.runs.len());
|
||||
let mut i = 0;
|
||||
for r in &t.runs {
|
||||
for c in r.text.chars() {
|
||||
let tracking = cluster.get(i).and_then(|k| tracking.get(*k)).copied().unwrap_or(0.0);
|
||||
i += 1;
|
||||
let style = CharStyle { tracking, ..r.style.clone() };
|
||||
match out.last_mut() {
|
||||
Some(last) if last.style == style && last.inline.is_none() && r.inline.is_none() => last.text.push(c),
|
||||
_ => out.push(TextRun { text: c.to_string(), style, inline: r.inline.clone() }),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Does the file stop before its end-of-file record?
|
||||
fn ends_early(bytes: &[u8], kind: Kind) -> bool {
|
||||
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! writers play as they draw, and damaged files fail or import partly without a panic.
|
||||
|
||||
use vectorcraft_color::{Gradient, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Dash, Document, Node, NodeKind};
|
||||
use vectorcraft_doc::{AppearanceItem, Dash, Document, Node, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use crate::bytes::Out;
|
||||
@@ -823,6 +823,272 @@ fn clipped_text_is_clipped_to_its_rectangle() {
|
||||
assert!(matches!(children[1].kind, NodeKind::Text(_)));
|
||||
}
|
||||
|
||||
/// The first text object of `d`.
|
||||
fn first_text(d: &Document) -> TextObject {
|
||||
all(d)
|
||||
.into_iter()
|
||||
.find_map(|n| match n.kind {
|
||||
NodeKind::Text(t) => Some(*t),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Where each glyph of `t` starts across the document (points), and where the last one ends.
|
||||
fn glyph_xs(t: &TextObject) -> (Vec<f64>, f64) {
|
||||
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let xs = laid.glyphs.iter().map(|g| (t.xf * g.origin).x).collect();
|
||||
let end = laid.glyphs.last().map_or(0.0, |g| (t.xf * (g.origin + vectorcraft_geom::Vec2::new(g.advance, 0.0))).x);
|
||||
(xs, end)
|
||||
}
|
||||
|
||||
/// EXTTEXTOUTW of `s` at (`x`, 1500), with the advances `dx` when there are any.
|
||||
fn text_out(x: i32, s: &str, dx: &[i32]) -> Vec<u8> {
|
||||
let units: Vec<u8> = s.encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
let n = units.len() as i32 / 2;
|
||||
// The string 76 bytes from the record start, the advances after it on a 4-byte boundary.
|
||||
let dx_at = if dx.is_empty() { 0 } else { 76 + units.len().next_multiple_of(4) as i32 };
|
||||
let mut text = vec![0; 16];
|
||||
text.extend(le(&[1, 0, 0]));
|
||||
text.extend(le(&[x, 1500, n, 76, 0, 0, 0, 0, 0, dx_at]));
|
||||
text.extend(&units);
|
||||
text.resize(68 + units.len().next_multiple_of(4), 0);
|
||||
text.extend(le(dx));
|
||||
text
|
||||
}
|
||||
|
||||
/// EXTCREATEFONTINDIRECTW: a 10 mm Arial in slot 2.
|
||||
fn arial() -> Vec<u8> {
|
||||
font_of("Arial", false)
|
||||
}
|
||||
|
||||
/// EXTCREATEFONTINDIRECTW: a 10 mm `family` in slot 2, underlined when `underline` is set.
|
||||
fn font_of(family: &str, underline: bool) -> Vec<u8> {
|
||||
let mut font = le(&[2, -1000, 0, 0, 0, 400]);
|
||||
font.extend([0, u8::from(underline), 0, 0, 0, 0, 0, 0]);
|
||||
let name: Vec<u16> = family.encode_utf16().collect();
|
||||
font.extend(name.iter().copied().chain(std::iter::repeat_n(0, 32 - name.len())).flat_map(u16::to_le_bytes));
|
||||
font
|
||||
}
|
||||
|
||||
/// The text and glyph starts (millimeters, rounded to hundredths) of every text object in `d`.
|
||||
fn texts_at(d: &Document) -> Vec<(String, Vec<f64>)> {
|
||||
let mm = 72.0 / 25.4;
|
||||
all(d)
|
||||
.into_iter()
|
||||
.filter_map(|n| match n.kind {
|
||||
NodeKind::Text(t) => Some((t.plain_text(), glyph_xs(&t).0.iter().map(|x| (x / mm * 100.0).round() / 100.0).collect())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_spaced_by_its_advances() {
|
||||
let mm = 72.0 / 25.4;
|
||||
// "Hi" with advances of 20 and 10 mm, left, centered and right aligned (SETTEXTALIGN), its
|
||||
// line from 10 to 40 mm each time.
|
||||
for (align, x) in [(0, 1000), (6, 2500), (2, 4000)] {
|
||||
let records = vec![(22, le(&[align])), (82, arial()), (37, le(&[2])), (84, text_out(x, "Hi", &[2000, 1000]))];
|
||||
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
|
||||
let t = first_text(&back.document);
|
||||
assert_eq!(t.plain_text(), "Hi");
|
||||
assert!(t.runs.iter().all(|r| r.style.kerning == Some(0.0)), "{:?}", t.runs);
|
||||
let (xs, end) = glyph_xs(&t);
|
||||
assert_eq!(xs.len(), 2, "{align}");
|
||||
assert!((xs[0] - 10.0 * mm).abs() < 0.01 && (xs[1] - 30.0 * mm).abs() < 0.01, "{align}: {xs:?}");
|
||||
assert!((end - 40.0 * mm).abs() < 0.01, "{align}: {end}");
|
||||
}
|
||||
// Characters 5 mm apart and a last "x" 10 mm wide, whatever the font joins or reorders before
|
||||
// it: ligatures that the tracking drops, a letter with a combining mark and a conjunct. The
|
||||
// "x" starts 5 mm after each character before it, and ends 10 mm later.
|
||||
for s in ["ffix", "e\u{301}x", "\u{928}\u{94d}\u{924}x"] {
|
||||
let n = s.chars().count();
|
||||
let dx: Vec<i32> = (0..n).map(|i| if i + 1 == n { 1000 } else { 500 }).collect();
|
||||
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, s, &dx))];
|
||||
let t = first_text(&import(&hand_emf(5000, 3000, &records)).unwrap().document);
|
||||
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
let x = laid.glyphs.iter().find(|g| g.byte == s.len() - 1).map(|g| (t.xf * g.origin).x).unwrap();
|
||||
let want = 10.0 + 5.0 * (n - 1) as f64;
|
||||
assert!((x - want * mm).abs() < 0.01, "{s:?}: {x} {:?}", t.runs);
|
||||
let (_, end) = glyph_xs(&t);
|
||||
assert!((end - (want + 10.0) * mm).abs() < 0.01, "{s:?}: {end}");
|
||||
}
|
||||
// An advance further than tracking reaches (120 mm on a 10 mm em): the characters after it are
|
||||
// type of their own, where the advances put them, left or right aligned.
|
||||
for (align, x) in [(0, 1000), (2, 14500)] {
|
||||
let records = vec![(22, le(&[align])), (82, arial()), (37, le(&[2])), (84, text_out(x, "Hiy", &[12000, 500, 1000]))];
|
||||
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
|
||||
let texts: Vec<TextObject> = all(&back.document)
|
||||
.into_iter()
|
||||
.filter_map(|n| match n.kind {
|
||||
NodeKind::Text(t) => Some(*t),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let found: Vec<(String, Vec<f64>)> =
|
||||
texts.iter().map(|t| (t.plain_text(), glyph_xs(t).0.iter().map(|x| (x / mm * 100.0).round() / 100.0).collect())).collect();
|
||||
assert_eq!(found, vec![("H".to_string(), vec![10.0]), ("iy".to_string(), vec![130.0, 135.0])], "{align}");
|
||||
}
|
||||
// The same advance inside a ligature ("fi" in a font that joins it): the type splits between
|
||||
// the "f" and the "i".
|
||||
let records = vec![(82, font_of("Source Serif 4", false)), (37, le(&[2])), (84, text_out(1000, "fix", &[12000, 500, 1000]))];
|
||||
let found = texts_at(&import(&hand_emf(20000, 3000, &records)).unwrap().document);
|
||||
assert_eq!(found, vec![("f".to_string(), vec![10.0]), ("ix".to_string(), vec![130.0, 135.0])]);
|
||||
// Advances between the "fi" ligature's and the separate letters' (3.64, 3.08 and 5.26 mm), where
|
||||
// the ligature forms at one tracking and breaks at the next: the "x" starts at 16.72 mm.
|
||||
let records = vec![(82, font_of("Source Serif 4", false)), (37, le(&[2])), (84, text_out(1000, "fix", &[364, 308, 526]))];
|
||||
let t = first_text(&import(&hand_emf(5000, 3000, &records)).unwrap().document);
|
||||
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
let x = laid.glyphs.iter().find(|g| g.byte == 2).map(|g| (t.xf * g.origin).x).unwrap();
|
||||
let (_, end) = glyph_xs(&t);
|
||||
assert!((x - 16.72 * mm).abs() < 0.01 && (end - 21.98 * mm).abs() < 0.01, "{x} {end} {:?}", t.runs);
|
||||
// A tab, which layout advances to its tab stop, ends a piece: the "B" after a 15 mm tab starts
|
||||
// at 35 mm.
|
||||
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, "A\tB", &[1000, 1500, 1000]))];
|
||||
let found = texts_at(&import(&hand_emf(10000, 3000, &records)).unwrap().document);
|
||||
let b = found.iter().find(|(s, _)| s.ends_with('B')).and_then(|(_, xs)| xs.last().copied());
|
||||
assert_eq!(b, Some(35.0), "{found:?}");
|
||||
// A leading NUL's advance counts in the line's width: right aligned at 50 mm, the 10 mm NUL
|
||||
// starts at 10 mm and "Hi" at 20 mm.
|
||||
let records = vec![(22, le(&[2])), (82, arial()), (37, le(&[2])), (84, text_out(5000, "\0Hi", &[1000, 2000, 1000]))];
|
||||
let t = first_text(&import(&hand_emf(5000, 3000, &records)).unwrap().document);
|
||||
assert_eq!(t.plain_text(), "Hi");
|
||||
let (xs, end) = glyph_xs(&t);
|
||||
assert!((xs[0] - 20.0 * mm).abs() < 0.01 && (end - 50.0 * mm).abs() < 0.01, "{xs:?} {end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiline_text_with_advances_aligns_each_line() {
|
||||
let mm = 72.0 / 25.4;
|
||||
// "Hi\nHi" with advances of 20 and 10 mm on each line, left, centered and right aligned: each
|
||||
// line runs from 10 to 40 mm, as "Hi" alone does, the second on the baseline below the first.
|
||||
// A second line of 15 and 5 mm, centered or right aligned, leaves the first where it is.
|
||||
let at = |records: &[(u32, Vec<u8>)]| -> Vec<(f64, f64)> {
|
||||
let back = import(&hand_emf(5000, 3000, records)).unwrap();
|
||||
let mut at = vec![];
|
||||
for n in all(&back.document) {
|
||||
let NodeKind::Text(t) = n.kind else { continue };
|
||||
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
for g in laid.glyphs.iter().filter(|g| g.advance > 0.0) {
|
||||
let p = t.xf * g.origin;
|
||||
at.push(((p.x / mm * 100.0).round() / 100.0, (p.y / mm * 100.0).round() / 100.0));
|
||||
}
|
||||
}
|
||||
at
|
||||
};
|
||||
let mut drops = vec![];
|
||||
for (align, x) in [(0, 1000), (6, 2500), (2, 4000)] {
|
||||
let records = vec![(22, le(&[align])), (82, arial()), (37, le(&[2])), (84, text_out(x, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))];
|
||||
let found = at(&records);
|
||||
let xs: Vec<f64> = found.iter().map(|p| p.0).collect();
|
||||
assert_eq!(xs, vec![10.0, 30.0, 10.0, 30.0], "{align}: {found:?}");
|
||||
assert!(found[0].1 == found[1].1 && found[2].1 == found[3].1 && found[2].1 > found[0].1, "{align}: {found:?}");
|
||||
drops.push(found[2].1 - found[0].1);
|
||||
}
|
||||
assert!(drops.iter().all(|d| (d - drops[0]).abs() < 0.01), "{drops:?}");
|
||||
// Underlined and left aligned, each line's underline ends with its own advances: no bar runs on
|
||||
// past either line.
|
||||
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))];
|
||||
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
|
||||
assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. })));
|
||||
for (align, x, second) in [(6, 2500, [15.0, 30.0]), (2, 4000, [20.0, 35.0])] {
|
||||
let records = vec![(22, le(&[align])), (82, arial()), (37, le(&[2])), (84, text_out(x, "Hi\nHi", &[2000, 1000, 0, 1500, 500]))];
|
||||
let xs: Vec<f64> = at(&records).iter().map(|p| p.0).collect();
|
||||
assert_eq!(xs, vec![10.0, 30.0, second[0], second[1]], "{align}");
|
||||
}
|
||||
// An advance further than tracking reaches on the second line of centered type (at 100 mm):
|
||||
// that line splits where the advance puts its characters, and the first line stays in place.
|
||||
let records = vec![(22, le(&[6])), (82, arial()), (37, le(&[2])), (84, text_out(10000, "Hi\nHiy", &[2000, 1000, 0, 12000, 500, 1000]))];
|
||||
let found = texts_at(&import(&hand_emf(20000, 3000, &records)).unwrap().document);
|
||||
let want = vec![("Hi".to_string(), vec![85.0, 105.0]), ("H".to_string(), vec![32.5]), ("iy".to_string(), vec![152.5, 157.5])];
|
||||
assert_eq!(found, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emf_plus_driver_strings_keep_their_positions() {
|
||||
// An EMF+ only file: a 1000 pixel Arial (font object 0) and DrawDriverString of "Hi" in black,
|
||||
// as characters (CmapLookup), its glyphs at x = 1000 and 3000 pixels (10 and 30 mm).
|
||||
let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]);
|
||||
let mut font = [le(&[0xDBC0_1002u32 as i32]), le_f32(&[1000.0]), le(&[2, 0, 0, 5])].concat();
|
||||
font.extend("Arial".encode_utf16().chain([0]).flat_map(u16::to_le_bytes));
|
||||
let mut draw = le(&[0xFF00_0000u32 as i32, 1, 0, 2]);
|
||||
draw.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes));
|
||||
draw.extend(le_f32(&[1000.0, 1500.0, 3000.0, 1500.0]));
|
||||
let comment = emf_plus(&[(0x4001, 0, header), (0x4008, 6 << 8, font), (0x4036, 0x8000, draw), (0x4002, 0, vec![])]);
|
||||
let back = import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap();
|
||||
let t = first_text(&back.document);
|
||||
assert_eq!(t.plain_text(), "Hi");
|
||||
let (xs, _) = glyph_xs(&t);
|
||||
let mm = 72.0 / 25.4;
|
||||
assert_eq!(xs.len(), 2);
|
||||
assert!((xs[0] - 10.0 * mm).abs() < 0.01 && (xs[1] - 30.0 * mm).abs() < 0.01, "{xs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wmf_text_is_spaced_by_its_advances() {
|
||||
// CREATEFONTINDIRECT of a 10 pt Arial (slot 0), selected, and EXTTEXTOUT of "Hi" at x = 10 pt
|
||||
// with advances of 20 and 10 pt, at 20 units a point.
|
||||
let mut font = le16(&[-200, 0, 0, 0, 400]);
|
||||
font.extend([0u8; 8]);
|
||||
font.extend(b"Arial".iter().copied().chain(std::iter::repeat_n(0, 27)));
|
||||
let mut text = le16(&[500, 200, 2, 0]);
|
||||
text.extend(b"Hi");
|
||||
text.extend(le16(&[400, 200]));
|
||||
let records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0A32, text)];
|
||||
let t = first_text(&import(&hand_wmf(4000, 1000, &records)).unwrap().document);
|
||||
assert_eq!(t.plain_text(), "Hi");
|
||||
let (xs, end) = glyph_xs(&t);
|
||||
assert_eq!(xs.len(), 2);
|
||||
assert!((xs[0] - 10.0).abs() < 0.01 && (xs[1] - 30.0).abs() < 0.01 && (end - 40.0).abs() < 0.01, "{xs:?} {end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_type_keeps_its_underline_and_right_to_left_order() {
|
||||
let mm = 72.0 / 25.4;
|
||||
// Underlined "Hiy" with an advance further than tracking reaches after the "H": the bar runs on
|
||||
// from the end of the "H"'s underline to where "iy" starts, at 130 mm.
|
||||
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))];
|
||||
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
|
||||
assert_eq!(texts_at(&back.document), vec![("H".to_string(), vec![10.0]), ("iy".to_string(), vec![130.0, 135.0])]);
|
||||
let bars: Vec<Rect> =
|
||||
all(&back.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).filter_map(|n| n.geometric_bounds()).collect();
|
||||
assert_eq!(bars.len(), 1, "{bars:?}");
|
||||
let b = bars[0];
|
||||
assert!(b.x0 > 10.0 * mm && b.x0 < 130.0 * mm && (b.x1 - 130.0 * mm).abs() < 0.01 && b.height() < 2.0 * mm, "{b:?}");
|
||||
// The "H" and the "i" before the split are tracked apart and draw a bar each: only the bar that
|
||||
// ends the piece runs on, from the end of the "i" to 130 mm.
|
||||
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))];
|
||||
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
|
||||
assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0]), ("y".to_string(), vec![140.0])]);
|
||||
let gaps: Vec<Node> = all(&back.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect();
|
||||
assert_eq!(gaps.len(), 1);
|
||||
let NodeKind::Path { path, .. } = &gaps[0].kind else { panic!("a path") };
|
||||
let rects = path.to_bezpath().elements().iter().filter(|e| matches!(e, vectorcraft_geom::PathEl::MoveTo(_))).count();
|
||||
assert_eq!(rects, 1);
|
||||
let b = gaps[0].geometric_bounds().unwrap();
|
||||
assert!(b.x0 > 20.0 * mm && (b.x1 - 140.0 * mm).abs() < 0.01, "{b:?}");
|
||||
// Without an underline, nothing but the type.
|
||||
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))];
|
||||
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
|
||||
assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. })));
|
||||
// A last advance further than tracking reaches, right aligned at 140 mm: the "H" and the "i"
|
||||
// start at 10 and 20 mm, and the underline runs on from the "i" to 140 mm.
|
||||
let records = vec![(22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))];
|
||||
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
|
||||
assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0])]);
|
||||
let bars: Vec<Rect> =
|
||||
all(&back.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).filter_map(|n| n.geometric_bounds()).collect();
|
||||
assert_eq!(bars.len(), 1, "{bars:?}");
|
||||
assert!(bars[0].x0 > 20.0 * mm && (bars[0].x1 - 140.0 * mm).abs() < 0.01, "{bars:?}");
|
||||
// Right to left type with the same advance stays one text object, its characters in order.
|
||||
let s = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
|
||||
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, s, &[12000, 500, 500, 1000]))];
|
||||
let found = texts_at(&import(&hand_emf(20000, 3000, &records)).unwrap().document);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].0, s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_clip_rectangles_clip() {
|
||||
// EXCLUDECLIPRECT cuts the top-left of the picture out of the clip; the rectangle crosses it.
|
||||
|
||||
@@ -108,6 +108,9 @@ pub(crate) struct Exporter<'a> {
|
||||
paper: Rect,
|
||||
/// Overprinting fills and strokes are drawn as forms marked to overprint.
|
||||
pub overprint: bool,
|
||||
/// Overprinting characters' fills and strokes are drawn with Darken, as a separation's plate
|
||||
/// draws its overprinting fills and strokes ([`vectorcraft_doc::overprint::darken_overprints`]).
|
||||
pub darken_overprints: bool,
|
||||
/// An overprinting fill or stroke was drawn so.
|
||||
pub overprinted: bool,
|
||||
/// Characters with neither fill nor stroke, or whose fill is drawn as art (outlines filled
|
||||
|
||||
@@ -62,6 +62,7 @@ impl<'a> Exporter<'a> {
|
||||
in_knockout_mask: false,
|
||||
mask_art_left_out: false,
|
||||
overprint: false,
|
||||
darken_overprints: false,
|
||||
overprinted: false,
|
||||
invisible: false,
|
||||
inline_depth: 0,
|
||||
|
||||
@@ -39,14 +39,15 @@ impl Exporter<'_> {
|
||||
cover(&mut ms, page, if m.clip { 0 } else { 255 }, 1.0);
|
||||
}
|
||||
// Mask art is a picture of its own: it takes no part in a knockout group around the object,
|
||||
// and has no inks to overprint.
|
||||
// and has no inks to overprint (its characters do not darken either).
|
||||
let knockout = std::mem::take(&mut self.knockout);
|
||||
let overprint = std::mem::take(&mut self.overprint);
|
||||
let darken = std::mem::take(&mut self.darken_overprints);
|
||||
let image_left_out = self.image_left_out.replace(false);
|
||||
self.node(&mut ms, &m.art, page, true);
|
||||
let incomplete = self.image_left_out.unwrap_or(false);
|
||||
self.image_left_out = image_left_out.map(|outer| outer || incomplete);
|
||||
(self.knockout, self.overprint) = (knockout, overprint);
|
||||
(self.knockout, self.overprint, self.darken_overprints) = (knockout, overprint, darken);
|
||||
if incomplete {
|
||||
ms.pop();
|
||||
ms.finish();
|
||||
@@ -611,6 +612,20 @@ impl Exporter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::overprinting`] for a character fill or stroke, which has no blend mode of its own:
|
||||
/// with [`Self::darken_overprints`] an overprinting one is drawn with Darken (not a white one
|
||||
/// with Discard White Overprint).
|
||||
pub(super) fn char_overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) {
|
||||
let white = vectorcraft_doc::overprint::is_white(paint) && self.doc.setup.discard_white_overprint;
|
||||
if overprints && self.darken_overprints && !paint.is_none() && !white {
|
||||
s.push_blend_mode(krilla::blend::BlendMode::Darken);
|
||||
self.overprinting(s, overprints, paint, draw);
|
||||
s.pop();
|
||||
} else {
|
||||
self.overprinting(s, overprints, paint, draw);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `p` a paint PDF has no paint for when it paints a fill (`fill`) or a stroke, which
|
||||
/// [`Self::area`] draws as art: a pattern swatch or a gradient drawn as pixels
|
||||
/// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of spot
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::exporter::{GlyphLine, MAX_INLINE_DEPTH, in_range, norm, to_path, writable, xf};
|
||||
use super::exporter::{GlyphLine, MAX_INLINE_DEPTH, blend, in_range, norm, to_path, writable, xf};
|
||||
use super::images::embed;
|
||||
use super::{
|
||||
Affine, AppearanceItem, BezPath, BlendMode, Color, Cow, Embedding, Exporter, Fill, FillRule, Glyph, GlyphId, KrillaGlyph, ListMarker, Mark, Node,
|
||||
@@ -56,7 +56,7 @@ impl Exporter<'_> {
|
||||
let fill = &run.style.fill;
|
||||
// Colour bitmap glyphs (emoji) real text doesn't write: all of them, or those it leaves.
|
||||
let mut images: Option<Vec<usize>> = None;
|
||||
self.overprinting(s, run.style.overprint_fill, fill, |ex, s| {
|
||||
self.char_overprinting(s, run.style.overprint_fill, fill, |ex, s| {
|
||||
s.push_transform(&text_space);
|
||||
// The outlines left to fill as paths: all of them, or those real text leaves.
|
||||
let outlines = match plain.as_deref().filter(|_| !fill.is_none() && !ex.area_paint(fill, true)) {
|
||||
@@ -121,7 +121,7 @@ impl Exporter<'_> {
|
||||
if let Some(path) = path {
|
||||
// Character strokes are drawn in text space, with their cap, join and dashes.
|
||||
let st = run.style.stroke_layer();
|
||||
self.overprinting(s, st.overprint, &st.paint, |ex, s| {
|
||||
self.char_overprinting(s, st.overprint, &st.paint, |ex, s| {
|
||||
s.push_transform(&text_space);
|
||||
ex.stroke(s, &bp, &path, FillRule::NonZero, &st, page, layout.bounds);
|
||||
s.pop();
|
||||
@@ -157,9 +157,16 @@ impl Exporter<'_> {
|
||||
if !ex.area(s, path, krilla::paint::FillRule::NonZero, &fl.paint, (fl.opacity, fl.blend), tb, bp.bounding_box(), true)
|
||||
&& let Some(paint) = ex.paint(s, &fl.paint, tb)
|
||||
{
|
||||
let bl = fl.blend != BlendMode::Normal;
|
||||
if bl {
|
||||
s.push_blend_mode(blend(fl.blend));
|
||||
}
|
||||
s.set_stroke(None);
|
||||
s.set_fill(Some(Fill { paint, opacity: norm(fl.opacity), rule: krilla::paint::FillRule::NonZero }));
|
||||
s.draw_path(path);
|
||||
if bl {
|
||||
s.pop();
|
||||
}
|
||||
}
|
||||
}),
|
||||
AppearanceItem::Stroke(st) if st.visible && st.width > 0.0 => {
|
||||
|
||||
@@ -152,7 +152,7 @@ impl Writer {
|
||||
// readers (CoreGraphics) drop most of a page in a non-isolated group (#2156).
|
||||
let doc = ex.doc;
|
||||
let page_group = fits && !self.pdf13 && (doc.page_isolate || doc.page_knockout);
|
||||
let cmyk_page_group = fits && self.cmyk && !page_group && ex.shows_transparency();
|
||||
let cmyk_page_group = fits && !self.pdf13 && self.cmyk && !page_group && ex.shows_transparency();
|
||||
// Each copy draws within an equal share of the symbol objects the export has left
|
||||
// ([`vectorcraft_doc::MAX_SYMBOL_NODES`]), so every copy leaves out the same instances.
|
||||
let limit = ex.symbol_limit;
|
||||
|
||||
+209
-3
@@ -39,7 +39,7 @@ use kurbo::{Affine, Rect, Vec2};
|
||||
use serde::Serialize;
|
||||
use vectorcraft_color::cms::{self, ProfileKind};
|
||||
use vectorcraft_doc::marks::PrinterMarks;
|
||||
use vectorcraft_doc::overprint::{clear_overprints, darken_overprints};
|
||||
use vectorcraft_doc::overprint::{OverprintBlack, clear_overprints, darken_overprints};
|
||||
use vectorcraft_doc::{ColorMode, Document, Node, NodeKind};
|
||||
|
||||
pub use layout::{MAX_COPIES_PER_SHEET, MAX_TILES, TileGrid};
|
||||
@@ -181,7 +181,7 @@ pub fn keep_layers(nodes: &mut Vec<Arc<Node>>, which: PrintLayers) {
|
||||
|
||||
/// `doc` as `set` prints it: live effects applied (raster effects are rendered by the app first),
|
||||
/// only the layers that print, overprints in composite output as [`PrintAdvanced::overprints`]
|
||||
/// says.
|
||||
/// says, and black art overprinting in separations with [`PrintOutput::overprint_black`].
|
||||
pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, Document> {
|
||||
// The layers that do not print are left out first, so the art placed for symbols is only
|
||||
// the art that prints; the layers kept are shown.
|
||||
@@ -190,9 +190,213 @@ pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, D
|
||||
let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false };
|
||||
let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept);
|
||||
composite_overprints(&mut d, set);
|
||||
separation_overprint_black(&mut d, set);
|
||||
Cow::Owned(d)
|
||||
}
|
||||
|
||||
/// Output › Overprint Black in separations: every fill and stroke of solid 100% process black or
|
||||
/// 100% gray, each to within half a percent ([`vectorcraft_doc::overprint::is_black_ink`]), or a
|
||||
/// gradient whose every stop is (every point of a freeform one), the characters' too, overprints. Rich black, RGB and Lab black,
|
||||
/// tints below 99.5%, and colors linked to a spot swatch or to Registration keep
|
||||
/// knocking out ([`OverprintBlack::default`]). Art that overprints already keeps doing so. A
|
||||
/// symbol instance that repaints its art is judged by the paints it prints with
|
||||
/// ([`place_repainted_instances`]).
|
||||
fn separation_overprint_black(doc: &mut Document, set: &PrintSettings) {
|
||||
if set.output.mode != OutputMode::Separations || !set.output.overprint_black {
|
||||
return;
|
||||
}
|
||||
place_repainted_instances(doc);
|
||||
let mut spots = doc.spot_names();
|
||||
spots.push(vectorcraft_color::swatch::REGISTRATION.to_string());
|
||||
let op = OverprintBlack::default();
|
||||
let symbols = doc.symbols.iter_mut().map(|s| &mut s.art);
|
||||
for n in doc.layers.iter_mut().chain(symbols).chain(doc.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) {
|
||||
op.apply_deep(n, &spots);
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace each symbol instance in `doc`'s layers and patterns whose own fill or stroke changes
|
||||
/// ([`vectorcraft_doc::symbol_overrides::SymbolOverride`]) or fill stain repaint its symbol's art
|
||||
/// ([`repaints`]), or whose symbol's art holds such an instance at any depth, with that art as
|
||||
/// the instance prints it ([`Placing::instance`]). Then the same is done inside the art of the
|
||||
/// symbols type shows as inline graphics ([`inline_symbols`]), which draw their symbol's art as it
|
||||
/// is; the other symbols' own art stays as it is, and so do hidden objects and template layers.
|
||||
/// Once the layers and patterns, with the art placed for symbols already, hold
|
||||
/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects, the remaining instances stay as they are, and so
|
||||
/// do instances whose art would draw deeper than [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`].
|
||||
fn place_repainted_instances(doc: &mut Document) {
|
||||
let holders = repainting_symbols(doc);
|
||||
let art = || doc.layers.iter().chain(doc.patterns.iter().flat_map(|p| p.art.iter()));
|
||||
if holders.is_empty() && !art().any(|n| holds_repaint(n, &holders)) {
|
||||
return;
|
||||
}
|
||||
let held = art().map(|n| n.count_with_masks() as u64).fold(0u64, u64::saturating_add);
|
||||
let mut placing =
|
||||
Placing { holders, heights: vectorcraft_doc::depth::DrawnHeights::of(doc), budget: vectorcraft_doc::MAX_SYMBOL_NODES.saturating_sub(held) };
|
||||
// The art placed for an instance holds the instances inside it: each pass places those, up
|
||||
// to the depth objects are drawn to.
|
||||
for _ in 0..=vectorcraft_doc::depth::MAX_DRAWN_DEPTH {
|
||||
let mut changed = false;
|
||||
for i in 0..doc.layers.len() {
|
||||
if let Some(layer) = placing.subtree(doc, &doc.layers[i], 1) {
|
||||
doc.layers[i] = layer;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for p in 0..doc.patterns.len() {
|
||||
for i in 0..doc.patterns[p].art.len() {
|
||||
if let Some(art) = placing.subtree(doc, &doc.patterns[p].art[i], 1) {
|
||||
doc.patterns[p].art[i] = art;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let inline = inline_symbols(doc);
|
||||
for _ in 0..=vectorcraft_doc::depth::MAX_DRAWN_DEPTH {
|
||||
let mut changed = false;
|
||||
for i in 0..doc.symbols.len() {
|
||||
if inline.contains(&doc.symbols[i].name)
|
||||
&& let Some(art) = placing.subtree(doc, &doc.symbols[i].art, 1)
|
||||
{
|
||||
doc.symbols[i].art = art;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the symbols that type in `doc` shows as inline graphics, in its layers, symbols
|
||||
/// and patterns.
|
||||
fn inline_symbols(doc: &Document) -> HashSet<String> {
|
||||
fn visit(n: &Node, out: &mut HashSet<String>) {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
out.extend(t.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.symbol.clone()));
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
visit(c, out);
|
||||
}
|
||||
}
|
||||
let mut out = HashSet::new();
|
||||
for n in doc.layers.iter().chain(doc.symbols.iter().map(|s| &s.art)).chain(doc.patterns.iter().flat_map(|p| p.art.iter())) {
|
||||
visit(n, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Does symbol instance `n` repaint its symbol's art: with its own fill or stroke changes, or with
|
||||
/// its fill's stain?
|
||||
fn repaints(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::SymbolInstance { .. })
|
||||
&& (n.extras().symbol_overrides.iter().any(|o| o.fill.is_some() || o.stroke.is_some())
|
||||
|| vectorcraft_doc::symbol_overrides::stain(n).is_some())
|
||||
}
|
||||
|
||||
/// Does `n`'s subtree hold a repainting instance ([`repaints`]) or an instance of one of the
|
||||
/// symbols `holders`?
|
||||
fn holds_repaint(n: &Node, holders: &HashSet<String>) -> bool {
|
||||
repaints(n)
|
||||
|| matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if holders.contains(symbol))
|
||||
|| n.children().is_some_and(|c| c.iter().any(|c| holds_repaint(c, holders)))
|
||||
}
|
||||
|
||||
/// The names of the symbols whose art holds a repainting instance ([`repaints`]) at any depth,
|
||||
/// through the instances of other symbols too.
|
||||
fn repainting_symbols(doc: &Document) -> HashSet<String> {
|
||||
let mut out = HashSet::new();
|
||||
loop {
|
||||
let before = out.len();
|
||||
for s in &doc.symbols {
|
||||
if !out.contains(&s.name) && holds_repaint(&s.art, &out) {
|
||||
out.insert(s.name.clone());
|
||||
}
|
||||
}
|
||||
if out.len() == before {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`place_repainted_instances`] places instances with.
|
||||
struct Placing {
|
||||
/// The symbols whose art holds a repainting instance ([`repainting_symbols`]).
|
||||
holders: HashSet<String>,
|
||||
heights: vectorcraft_doc::depth::DrawnHeights,
|
||||
/// The objects left to place.
|
||||
budget: u64,
|
||||
}
|
||||
|
||||
impl Placing {
|
||||
/// `n`'s subtree, `n` placed `level` deep, with its instances that [`Self::instance`] places
|
||||
/// placed, copying only the nodes on the way to them; `None` when there is none. Hidden
|
||||
/// objects and template layers do not print and are left as they are.
|
||||
fn subtree(&mut self, doc: &Document, n: &Arc<Node>, level: usize) -> Option<Arc<Node>> {
|
||||
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
|
||||
return None;
|
||||
}
|
||||
if let Some(g) = self.instance(doc, n, level) {
|
||||
return Some(Arc::new(g));
|
||||
}
|
||||
let members: Vec<(usize, Arc<Node>)> =
|
||||
n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.subtree(doc, c, level + 1)?))).collect();
|
||||
if members.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut copy = Arc::clone(n);
|
||||
if let Some(children) = Arc::make_mut(&mut copy).children_mut() {
|
||||
for (i, c) in members {
|
||||
if let Some(slot) = children.get_mut(i) {
|
||||
*slot = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(copy)
|
||||
}
|
||||
|
||||
/// Symbol instance `n`, placed `level` deep, when it repaints its art ([`repaints`]) or its
|
||||
/// symbol is one of [`Self::holders`], as a group of that art placed as the exporter places
|
||||
/// it, with the instance's id, name, visibility, transparency, opacity mask, effects and
|
||||
/// attributes. `None` for other objects, for instances of a missing symbol, when the art does
|
||||
/// not fit in [`Self::budget`] (which it is taken from), and when it would draw deeper than
|
||||
/// [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`].
|
||||
fn instance(&mut self, doc: &Document, n: &Node, level: usize) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None };
|
||||
if !repaints(n) && !self.holders.contains(symbol) {
|
||||
return None;
|
||||
}
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
|
||||
// The most objects placing it can make, counted before it is placed.
|
||||
let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc));
|
||||
let left = self.budget.checked_sub(most)?;
|
||||
let placed = doc.place_symbol_art(symbol, &art, *xf)?;
|
||||
let mut g = Node::group(n.id, vec![Arc::new(placed)]);
|
||||
g.name = n.name.clone();
|
||||
g.visible = n.visible;
|
||||
g.opacity = n.opacity;
|
||||
g.blend = n.blend;
|
||||
g.isolate = n.isolate;
|
||||
// One element of an enclosing knockout group, as the instance is: its pieces never knock
|
||||
// each other out.
|
||||
g.knockout = vectorcraft_doc::Knockout::Off;
|
||||
g.knockout_shape = n.knockout_shape;
|
||||
g.appearance.effects = n.appearance.effects.clone();
|
||||
g.extras_mut().mask = n.extras().mask.clone();
|
||||
g.extras_mut().attrs = n.extras().attrs.clone();
|
||||
if self.heights.deepest(&g, level) > vectorcraft_doc::depth::MAX_DRAWN_DEPTH {
|
||||
return None;
|
||||
}
|
||||
self.budget = left;
|
||||
Some(g)
|
||||
}
|
||||
}
|
||||
|
||||
/// Overprinting fills and strokes in composite output: discarded (they knock out) or simulated
|
||||
/// (drawn with Darken, as Overprint Preview shows them), after which nothing overprints any
|
||||
/// more; or preserved. Separations always honour them.
|
||||
@@ -404,7 +608,7 @@ pub fn plan<'a>(doc: &'a Document, opts: &PrintOptions) -> Result<PrintPlan<'a>,
|
||||
let job = Job::new(doc, set, opts.postscript)?;
|
||||
let title = opts.title.clone().unwrap_or_else(|| job.doc.title.clone());
|
||||
let created = opts.created.or_else(vectorcraft_doc::metadata::output_time);
|
||||
let sep = Separator::new(&job.doc, set);
|
||||
let sep = Separator::new(&job.doc, set, opts.postscript);
|
||||
let plates: Vec<Document> = (0..job.plates.len()).filter_map(|p| job.ink(Some(p))).map(|i| sep.plate(&i.name)).collect();
|
||||
let marks = set.marks.printer_marks();
|
||||
let sheets = job
|
||||
@@ -482,6 +686,8 @@ fn print_inner(doc: &Document, opts: &PrintOptions, left_out: &mut HashSet<Strin
|
||||
ex.out = w.out.clone();
|
||||
// Composite output keeps overprints as the Advanced option says (plates darken them).
|
||||
ex.overprint = !separations && pdf.advanced.overprint == Overprint::Preserve;
|
||||
// A plate's overprinting characters darken, as its fills and strokes do.
|
||||
ex.darken_overprints = separations;
|
||||
ex.left_out = left_out.clone();
|
||||
}
|
||||
for &i in &plan.order {
|
||||
|
||||
@@ -5,12 +5,12 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_color::cms::{self, Cms, Model, ProfileKind};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors};
|
||||
use vectorcraft_doc::overprint::darken_overprints;
|
||||
use vectorcraft_doc::{ColorMode, Document, ImageBlob, Node, NodeKind};
|
||||
use vectorcraft_doc::overprint::{darken_overprints, is_white};
|
||||
use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind};
|
||||
|
||||
use super::{DEFAULT_FREQUENCY, PrintInk, PrintSettings};
|
||||
|
||||
@@ -78,11 +78,13 @@ pub(crate) struct Separator<'a> {
|
||||
pub doc: &'a Document,
|
||||
cms: Arc<Cms>,
|
||||
set: &'a PrintSettings,
|
||||
/// The plates are written as PostScript, which has no blending modes.
|
||||
postscript: bool,
|
||||
}
|
||||
|
||||
impl<'a> Separator<'a> {
|
||||
pub fn new(doc: &'a Document, set: &'a PrintSettings) -> Self {
|
||||
Self { doc, cms: separation_cms(doc, set), set }
|
||||
pub fn new(doc: &'a Document, set: &'a PrintSettings, postscript: bool) -> Self {
|
||||
Self { doc, cms: separation_cms(doc, set), set, postscript }
|
||||
}
|
||||
|
||||
/// How much of ink `plate` colour `c` (with swatch link `link`) prints, 0..1.
|
||||
@@ -131,6 +133,57 @@ impl<'a> Separator<'a> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether paint `p` puts none of ink `plate` down: a solid color, a gradient whose every stop
|
||||
/// does, or a freeform gradient with color points whose every point does (points carry no
|
||||
/// swatch link). On PostScript plates, to within half a percent (the other inks a black may
|
||||
/// carry and still count as black, [`vectorcraft_doc::overprint::is_black_ink`]).
|
||||
fn no_ink(&self, plate: &str, p: &Paint) -> bool {
|
||||
let none = if self.postscript { 0.005 } else { 0.0 };
|
||||
match p {
|
||||
Paint::Solid { color, swatch, tint } => self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))) <= none,
|
||||
Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
|
||||
Some(f) => f.points.iter().all(|pt| self.ink(plate, &pt.color, None) <= none),
|
||||
None => {
|
||||
!g.gradient.stops.is_empty()
|
||||
&& g.gradient.stops.iter().all(|s| self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates) <= none)
|
||||
}
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and
|
||||
/// overprinting character fills and strokes, that put none of ink `plate` down leave its plate
|
||||
/// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which
|
||||
/// knock out). A writer without blending modes (PostScript) then keeps the ink below them,
|
||||
/// where it would draw their Darken as a knockout.
|
||||
fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc<Node>, discard_white: bool) {
|
||||
let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p);
|
||||
let n = Arc::make_mut(a);
|
||||
for it in &mut n.appearance.items {
|
||||
let normal = match it {
|
||||
AppearanceItem::Fill(l) => l.blend == BlendMode::Normal,
|
||||
AppearanceItem::Stroke(l) => l.blend == BlendMode::Normal,
|
||||
};
|
||||
if normal && inkless(it.overprint(), it.paint()) {
|
||||
*it.paint_mut() = Paint::None;
|
||||
}
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
if inkless(r.style.overprint_fill, &r.style.fill) {
|
||||
r.style.fill = Paint::None;
|
||||
}
|
||||
if inkless(r.style.overprint_stroke, &r.style.stroke) {
|
||||
r.style.stroke = Paint::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
self.clear_inkless_overprints(plate, c, discard_white);
|
||||
}
|
||||
}
|
||||
|
||||
/// The document as plate `plate`: art, symbols, pattern tiles and images in the grey of the
|
||||
/// ink's coverage. Overprinting fills and strokes darken, so where they have none of this
|
||||
/// ink the plate below shows through instead of being knocked out.
|
||||
@@ -140,6 +193,7 @@ impl<'a> Separator<'a> {
|
||||
let mut colorized = BTreeSet::new();
|
||||
let nodes = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.patterns.iter_mut().flat_map(|p| p.art.iter_mut()));
|
||||
for n in nodes {
|
||||
self.clear_inkless_overprints(plate, n, discard_white);
|
||||
darken_overprints(n, discard_white);
|
||||
self.node(plate, Arc::make_mut(n));
|
||||
keep_colorized_pixels(n, &d.images, &mut colorized);
|
||||
|
||||
@@ -420,11 +420,15 @@ pub struct Placement {
|
||||
pub struct PrintScale {
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
/// The link between the width and the height: on, both are the same percentage. On for new
|
||||
/// settings; a saved scale without it reads as off, so its width and height stay as saved.
|
||||
#[serde(default)]
|
||||
pub linked: bool,
|
||||
}
|
||||
|
||||
impl Default for PrintScale {
|
||||
fn default() -> Self {
|
||||
Self { width: 100.0, height: 100.0 }
|
||||
Self { width: 100.0, height: 100.0, linked: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,6 +441,9 @@ pub struct PrintOutput {
|
||||
pub image: PrintImage,
|
||||
/// Separate spot colours into process inks: no spot plates.
|
||||
pub spots_to_process: bool,
|
||||
/// Separations: solid 100% black fills and strokes overprint, the characters' too, in the
|
||||
/// printed copy only ([`super::printed_document`]). Composite output leaves it unused.
|
||||
pub overprint_black: bool,
|
||||
/// Per-ink options, by ink name; inks not listed print with their defaults.
|
||||
pub inks: Vec<InkSettings>,
|
||||
}
|
||||
@@ -582,6 +589,12 @@ impl PrintSettings {
|
||||
within("placement.y", self.placement.y, -14_400.0, 14_400.0, " pt")?;
|
||||
within("scale.width", self.scale.width, 1.0, 1000.0, "%")?;
|
||||
within("scale.height", self.scale.height, 1.0, 1000.0, "%")?;
|
||||
if self.scale.linked && self.scale.width != self.scale.height {
|
||||
return Err(PdfError::BadSetting(format!(
|
||||
"scale: width ({}%) and height ({}%) must be equal while scale.linked is on",
|
||||
self.scale.width, self.scale.height
|
||||
)));
|
||||
}
|
||||
within("overlap", self.overlap, 0.0, 720.0, " pt")?;
|
||||
within("gutter", self.gutter, 0.0, 720.0, " pt")?;
|
||||
within("margin", self.margin, 0.0, 144.0, " pt")?;
|
||||
|
||||
@@ -105,6 +105,28 @@ fn defaults_and_json() {
|
||||
assert_eq!(Media::A4.size().map(|(w, h)| (w.round(), h.round())), Some((595.0, 842.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it() {
|
||||
let s = PrintSettings::default();
|
||||
assert!(s.scale.linked, "new settings keep W and H equal");
|
||||
assert_eq!(serde_json::to_value(&s).unwrap()["scale"], json!({"width": 100.0, "height": 100.0, "linked": true}));
|
||||
// Settings without a scale are new settings; a scale saved before the link reads as unlinked,
|
||||
// so its width and height print as they did.
|
||||
assert!(settings(json!({"copies": 2})).scale.linked);
|
||||
let old = settings(json!({"scaling": "custom", "scale": {"width": 50, "height": 200}}));
|
||||
assert_eq!((old.scale.width, old.scale.height, old.scale.linked), (50.0, 200.0, false));
|
||||
assert!(old.check().is_ok());
|
||||
// Linked, the two must be equal; the range still holds for both.
|
||||
let apart = settings(json!({"scale": {"width": 50, "height": 200, "linked": true}}));
|
||||
assert!(matches!(apart.check(), Err(PdfError::BadSetting(_))));
|
||||
for bad in
|
||||
[json!({"width": 0, "height": 0, "linked": true}), json!({"width": 1001, "height": 1001, "linked": true}), json!({"width": -5, "height": 50})]
|
||||
{
|
||||
assert!(matches!(settings(json!({ "scale": bad })).check(), Err(PdfError::BadSetting(_))), "{bad}");
|
||||
}
|
||||
assert!(settings(json!({"scale": {"width": 1000, "height": 1000, "linked": true}})).check().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn japanese_paper_sizes() {
|
||||
// The Japanese papers: JIS B4, B5 and B6 are the sizes Japanese printing uses (JIS X 6310),
|
||||
@@ -615,6 +637,239 @@ fn cmyk_and_a_spot_separate_into_five_plates() {
|
||||
assert_eq!(inks(&p[2]), [0.0, 40.0], "the gold's yellow");
|
||||
}
|
||||
|
||||
/// A 200 × 100 pt CMYK document filled with cyan, with spot swatch `Ink` (100% K) and the objects
|
||||
/// `art` over the cyan.
|
||||
fn over_cyan(art: Vec<Node>) -> Document {
|
||||
let mut d = doc(200.0, 100.0, &[(Rect::new(0.0, 0.0, 200.0, 100.0), Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)))]);
|
||||
d.color_mode = vectorcraft_doc::ColorMode::Cmyk;
|
||||
d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), global: true, spot: true });
|
||||
let layer = d.default_layer().unwrap();
|
||||
for mut n in art {
|
||||
n.id = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprint_black_keeps_the_inks_under_solid_black_on_separations() {
|
||||
let k = |v: f32| Paint::solid(Color::cmyk(0.0, 0.0, 0.0, v));
|
||||
let spot = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 1.0 };
|
||||
let stops = vec![GradientStop::new(0.0, Color::cmyk(0.0, 0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))];
|
||||
let fade = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let square = |x: f64, fill: Paint, stroke: Paint| {
|
||||
Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 4.0))
|
||||
};
|
||||
// (left edge, fill, whether the cyan below prints under it with the option on).
|
||||
let cases = [
|
||||
(10.0, k(1.0), true),
|
||||
(40.0, Paint::solid(Color::gray(1.0)), true),
|
||||
(70.0, Paint::solid(Color::cmyk(0.6, 0.4, 0.4, 1.0)), false),
|
||||
(100.0, k(0.99), false),
|
||||
(130.0, spot, false),
|
||||
(160.0, fade, false),
|
||||
];
|
||||
let mut art: Vec<Node> = cases.iter().map(|(x, p, _)| square(*x, p.clone(), Paint::None)).collect();
|
||||
// A black stroke with no fill: its left side runs down x = 184.
|
||||
art.push(square(184.0, Paint::None, k(1.0)));
|
||||
let d = over_cyan(art);
|
||||
let plates = |v: serde_json::Value| -> Vec<vectorcraft_testkit::raster::Image> {
|
||||
let opts = PrintOptions { settings: settings(v), ..Default::default() };
|
||||
plan(&d, &opts).unwrap().plates.iter().map(|p| render_region(p, Rect::new(0.0, 0.0, 200.0, 100.0), 1.0)).collect()
|
||||
};
|
||||
// Full ink at x on the plate (a rich black's 60% cyan is not).
|
||||
let inked = |img: &vectorcraft_testkit::raster::Image, x: f64| img.over_white(x as u32, 25)[0] < 40;
|
||||
let off = plates(json!({"output": {"mode": "separations"}}));
|
||||
let on = plates(json!({"output": {"mode": "separations", "overprintBlack": true}}));
|
||||
for (x, _, overprints) in &cases {
|
||||
assert!(!inked(&off[0], x + 10.0), "off: the art at {x} knocks the cyan out");
|
||||
assert_eq!(inked(&on[0], x + 10.0), *overprints, "on: the cyan under the art at {x}");
|
||||
}
|
||||
assert!(!inked(&off[0], 184.0) && inked(&on[0], 184.0), "a black stroke overprints too");
|
||||
assert!(inked(&on[0], 194.0), "inside the unfilled square: cyan");
|
||||
assert!(inked(&on[3], 20.0) && inked(&off[3], 20.0), "the black prints on the Black plate either way");
|
||||
assert!(!inked(&on[3], 2.0), "no black is added where there is none");
|
||||
// The K and gray squares put no cyan down, so the cyan plate draws them as nothing: a writer
|
||||
// without blending modes (PostScript) keeps the cyan under them too.
|
||||
let opts = PrintOptions {
|
||||
settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})),
|
||||
postscript: true,
|
||||
..Default::default()
|
||||
};
|
||||
let p = plan(&d, &opts).unwrap();
|
||||
let fills = |doc: &Document| {
|
||||
let mut count = 0;
|
||||
doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())));
|
||||
count
|
||||
};
|
||||
assert_eq!((fills(&d), fills(&p.plates[0]), fills(&p.plates[3])), (7, 5, 7), "the cyan plate, the Black plate");
|
||||
// The document keeps its own settings; composite output ignores the option.
|
||||
assert!(!d.layers.iter().any(|l| l.has_overprint()));
|
||||
let marked = |v| printed_document(&d, &settings(v)).layers.iter().any(|l| l.has_overprint());
|
||||
assert!(marked(json!({"output": {"mode": "separations", "overprintBlack": true}})));
|
||||
assert!(!marked(json!({"output": {"overprintBlack": true}})), "composite");
|
||||
assert!(!marked(json!({"output": {"mode": "separations"}})), "off by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates() {
|
||||
// 0.4% cyan beside 100% K counts as black, as do a freeform gradient of black points and a
|
||||
// linear gradient of black stops, and the cyan plate draws them all as nothing.
|
||||
let near = Paint::solid(Color::cmyk(0.004, 0.0, 0.0, 1.0));
|
||||
let k = Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, k), GradientStop::new(1.0, k)]));
|
||||
let points = vec![FreeformPoint::new(kurbo::Point::new(45.0, 20.0), k), FreeformPoint::new(kurbo::Point::new(55.0, 30.0), Color::gray(1.0))];
|
||||
g.freeform = Some(Freeform { points, ..Default::default() });
|
||||
// A linear gradient draws its black stops, not the cyan point it still holds.
|
||||
let mut linear = g.clone();
|
||||
linear.gradient.kind = GradientKind::Linear;
|
||||
if let Some(f) = &mut linear.freeform {
|
||||
f.points[1].color = Color::cmyk(1.0, 0.0, 0.0, 0.0);
|
||||
}
|
||||
let square = |x: f64, fill: Paint| {
|
||||
Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, Paint::None, 0.0))
|
||||
};
|
||||
let d = over_cyan(vec![square(10.0, near), square(40.0, Paint::Gradient(Box::new(g))), square(70.0, Paint::Gradient(Box::new(linear)))]);
|
||||
let opts = PrintOptions {
|
||||
settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})),
|
||||
postscript: true,
|
||||
..Default::default()
|
||||
};
|
||||
let p = plan(&d, &opts).unwrap();
|
||||
let fills = |doc: &Document| {
|
||||
let mut count = 0;
|
||||
doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())));
|
||||
count
|
||||
};
|
||||
assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 4), "the cyan plate, the Black plate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() {
|
||||
// 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript
|
||||
// plate draws it as nothing (it has no blending modes).
|
||||
let mut square = Node::path(
|
||||
vectorcraft_doc::NodeId(0),
|
||||
shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)),
|
||||
Appearance::basic(Paint::solid(Color::cmyk(0.004, 0.0, 0.0, 1.0)), Paint::None, 0.0),
|
||||
);
|
||||
if let Some(f) = square.appearance.fill_mut() {
|
||||
f.overprint = true;
|
||||
}
|
||||
let d = over_cyan(vec![square]);
|
||||
let fills = |postscript: bool| {
|
||||
let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() };
|
||||
let p = plan(&d, &opts).unwrap();
|
||||
let mut count = 0;
|
||||
p.plates[0].walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())));
|
||||
count
|
||||
};
|
||||
assert_eq!((fills(false), fills(true)), (2, 1), "the cyan plate as PDF, as PostScript");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprinting_type_leaves_the_inks_below_on_separations() {
|
||||
let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), ..Default::default() };
|
||||
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style);
|
||||
let mut d = over_cyan(vec![Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text)))]);
|
||||
let darkens = |d: &Document, v| String::from_utf8_lossy(&job(d, v).bytes).contains("/Darken");
|
||||
let seps = json!({"output": {"mode": "separations"}});
|
||||
assert!(!darkens(&d, seps.clone()), "black type knocks out");
|
||||
assert!(darkens(&d, json!({"output": {"mode": "separations", "overprintBlack": true}})), "Overprint Black: the type overprints");
|
||||
// A character fill set to overprint does so on the plates without the option too.
|
||||
let layer = d.default_layer().unwrap();
|
||||
let id = d.node(layer).and_then(|l| l.children()).and_then(|c| c.last()).map(|n| n.id).unwrap();
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { panic!("type") };
|
||||
t.runs[0].style.overprint_fill = true;
|
||||
assert!(darkens(&d, seps), "an overprinting character fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_type_objects_own_black_fill_overprints_on_separations() {
|
||||
// No character fill: the type object's own fill paints the characters.
|
||||
let style = vectorcraft_doc::CharStyle { fill: Paint::None, ..Default::default() };
|
||||
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style);
|
||||
let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text)));
|
||||
n.appearance = Appearance::basic(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), Paint::None, 0.0).into();
|
||||
let d = over_cyan(vec![n]);
|
||||
let darkens = |v| String::from_utf8_lossy(&job(&d, v).bytes).contains("/Darken");
|
||||
assert!(!darkens(json!({"output": {"mode": "separations"}})), "it knocks out");
|
||||
assert!(darkens(json!({"output": {"mode": "separations", "overprintBlack": true}})), "Overprint Black: it overprints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprint_black_follows_a_symbol_instances_own_fill_on_separations() {
|
||||
use vectorcraft_doc::symbol_overrides::SymbolOverride;
|
||||
let (k, magenta) = (Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 1.0, 0.0, 0.0));
|
||||
let square = |x: f64, c: Color| {
|
||||
let r = shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0));
|
||||
Arc::new(Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(Paint::solid(c), Paint::None, 0.0)))
|
||||
};
|
||||
let instance = |symbol: &str, fill: Color| {
|
||||
let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: Default::default() });
|
||||
n.extras_mut().symbol_overrides = vec![SymbolOverride { path: vec![], fill: Some(Paint::solid(fill)), ..Default::default() }];
|
||||
n
|
||||
};
|
||||
// An instance of "Outer", whose art is the magenta symbol's instance painted black, moved right.
|
||||
let outer =
|
||||
Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Outer".into(), xf: kurbo::Affine::translate((140.0, 0.0)) });
|
||||
let mut d = over_cyan(vec![instance("Magenta", k), instance("Black", magenta), outer]);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Magenta".into(), art: square(10.0, magenta) });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Black".into(), art: square(40.0, k) });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Outer".into(), art: Arc::new(instance("Magenta", k)) });
|
||||
let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), ..Default::default() };
|
||||
let p = plan(&d, &opts).unwrap();
|
||||
let cyan = render_region(&p.plates[0], Rect::new(0.0, 0.0, 200.0, 100.0), 1.0);
|
||||
let inked = |x: u32| cyan.over_white(x, 25)[0] < 40;
|
||||
assert!(inked(20), "a magenta symbol's instance painted black overprints the cyan");
|
||||
assert!(!inked(50), "a black symbol's instance painted magenta knocks the cyan out");
|
||||
assert!(inked(160), "the instance painted black inside another symbol's art overprints too");
|
||||
assert!(!d.symbols.iter().any(|s| s.art.has_overprint()), "the document keeps its own settings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprint_black_follows_instance_paints_in_inline_graphics() {
|
||||
use vectorcraft_doc::symbol_overrides::SymbolOverride;
|
||||
// Type shows symbol "Holder" inline; its art is an instance of a black symbol painted magenta.
|
||||
let k = Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0));
|
||||
let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mut inst = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Black".into(), xf: Default::default() });
|
||||
let magenta = Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0));
|
||||
inst.extras_mut().symbol_overrides = vec![SymbolOverride { path: vec![], fill: Some(magenta), ..Default::default() }];
|
||||
let mut text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", Default::default());
|
||||
text.runs.push(vectorcraft_doc::TextRun::inline(vectorcraft_doc::InlineArt::new("Holder"), Default::default()));
|
||||
let mut d = over_cyan(vec![Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text)))]);
|
||||
let black = Arc::new(Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(k, Paint::None, 0.0)));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: true, name: "Black".into(), art: black });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(inst) });
|
||||
let printed = printed_document(&d, &settings(json!({"output": {"mode": "separations", "overprintBlack": true}})));
|
||||
let holder = printed.symbols.iter().find(|s| s.name == "Holder").unwrap();
|
||||
let mut instances = 0;
|
||||
holder.art.walk(&mut |n: &Node| instances += usize::from(matches!(n.kind, NodeKind::SymbolInstance { .. })));
|
||||
assert_eq!(instances, 0, "the instance is placed as the art it prints");
|
||||
assert!(!holder.art.has_overprint(), "its magenta fill knocks out");
|
||||
assert!(matches!(d.symbols[1].art.kind, NodeKind::SymbolInstance { .. }), "the document keeps its art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprinting_type_in_an_opacity_mask_does_not_darken_on_separations() {
|
||||
// Mask art has no inks: an overprinting gray character in an inverted clipping mask keeps its
|
||||
// luminance on every plate.
|
||||
let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.5)), overprint_fill: true, ..Default::default() };
|
||||
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style);
|
||||
let mut mask = vectorcraft_doc::OpacityMask::new(Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))), true);
|
||||
mask.invert = true;
|
||||
let square = Node::path(
|
||||
vectorcraft_doc::NodeId(0),
|
||||
shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 90.0)),
|
||||
Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0),
|
||||
)
|
||||
.with_mask(Some(Box::new(mask)));
|
||||
let d = over_cyan(vec![square]);
|
||||
let bytes = job(&d, json!({"output": {"mode": "separations"}})).bytes;
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("/Darken"), "the mask's character is drawn as it is");
|
||||
}
|
||||
|
||||
/// A 100 pt CMYK document with spot swatch `Gold` and a square filled with gradient `g`.
|
||||
fn gold_gradient_doc(g: GradientPaint) -> Document {
|
||||
let mut d = doc(100.0, 100.0, &[(Rect::new(0.0, 0.0, 50.0, 50.0), Paint::Gradient(Box::new(g)))]);
|
||||
|
||||
@@ -59,11 +59,11 @@ pub fn drawn_bounds(doc: &Document, n: &Node) -> Option<Rect> {
|
||||
}
|
||||
|
||||
/// For a path or compound path whose own Rasterize effect is followed by Transform effects that
|
||||
/// move the art once ([`crate::effects::rasterize_stage`]): `n` with those Transform effects
|
||||
/// hidden, which the image is made of, and the map they move the image by. The canvas draws the
|
||||
/// image on its own pixel grid and moves it, and the room around the art, with the map. `None`
|
||||
/// for other objects.
|
||||
pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, vectorcraft_geom::Affine)> {
|
||||
/// move or copy the art ([`crate::effects::rasterize_stage`]): `n` with those Transform effects
|
||||
/// hidden, which the image is made of, and the maps they place the image by, the lowest first
|
||||
/// (one per copy, the original's last). The canvas draws the image on its own pixel grid and
|
||||
/// places it, and the room around the art, through each map. `None` for other objects.
|
||||
pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Vec<vectorcraft_geom::Affine>)> {
|
||||
fx::rasterize_stage(doc, n)
|
||||
}
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ pub(crate) use bounds::{
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use entries::Drawn;
|
||||
pub(crate) use entries::{DocInputs, FxGeom, Inputs, Reads, ShadowEntry};
|
||||
pub(crate) use entries::{DocInputs, FxGeom, Inputs, Kept, Reads, ShadowEntry};
|
||||
pub(crate) use pixels::paint_names;
|
||||
pub(crate) use predicates::{has_fx, has_object_fx};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -49,12 +49,13 @@ pub(crate) fn effected_path_carrying(doc: &Document, n: &Node, bp: &BezPath) ->
|
||||
}
|
||||
|
||||
/// `n`, a path or compound path whose own Rasterize effect is followed by Transform effects that
|
||||
/// move its image ([`effects::rasterize_stage`]), with those Transform effects hidden, and the map
|
||||
/// they move the image by ([`effects::stage_map`]): the image is made of that node's art on its
|
||||
/// own pixel grid, then drawn through the map. `None` for any other object, when the node without
|
||||
/// those Transform effects is drawn through its art ([`has_object_fx`]: a Transform effect that
|
||||
/// copies it, Crop Marks, a 3D effect…), and when the art before the Transform effects is empty.
|
||||
pub(crate) fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Affine)> {
|
||||
/// move or copy its image ([`effects::rasterize_stage`]), with those Transform effects hidden, and
|
||||
/// the maps they place the image by, the lowest first ([`effects::stage_maps`]): the image is made
|
||||
/// of that node's art on its own pixel grid, then drawn through each map. `None` for any other
|
||||
/// object, when the node without those Transform effects is drawn through its art
|
||||
/// ([`has_object_fx`]: Crop Marks, a 3D effect…), and when the art before the Transform effects is
|
||||
/// empty.
|
||||
pub(crate) fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Vec<Affine>)> {
|
||||
if !has_fx(n) {
|
||||
return None;
|
||||
}
|
||||
@@ -65,15 +66,21 @@ pub(crate) fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Affine)
|
||||
return None;
|
||||
}
|
||||
let g = effected_path(doc, &stage, &node_bezpath(n)?);
|
||||
let map = effects::stage_map(&n.appearance.effects, &at, &vectorcraft_geom::PathData::from_bezpath(&g))?;
|
||||
Some((stage, map))
|
||||
let maps = effects::stage_maps(&n.appearance.effects, &at, &vectorcraft_geom::PathData::from_bezpath(&g))?;
|
||||
Some((stage, maps))
|
||||
}
|
||||
|
||||
/// The box `map` ([`rasterize_stage`]) takes `b` to; `None` when it flattens it to a line or a
|
||||
/// point, which leaves nothing to draw.
|
||||
pub(crate) fn staged_reach(map: Affine, b: Rect) -> Option<Rect> {
|
||||
/// Does `map` ([`rasterize_stage`]) place an image? Not when it flattens it to a line or a point,
|
||||
/// which leaves nothing to draw.
|
||||
pub(crate) fn places(map: Affine) -> bool {
|
||||
let det = map.determinant();
|
||||
(det.is_finite() && det.abs() > 1e-12).then(|| map.transform_rect_bbox(b))
|
||||
det.is_finite() && det.abs() > 1e-12
|
||||
}
|
||||
|
||||
/// The box the maps of [`rasterize_stage`] take `b` to, all placements together; `None` when each
|
||||
/// one flattens it ([`places`]).
|
||||
pub(crate) fn staged_reach(maps: &[Affine], b: Rect) -> Option<Rect> {
|
||||
maps.iter().filter(|m| places(**m)).map(|m| m.transform_rect_bbox(b)).reduce(|a, r| a.union(r))
|
||||
}
|
||||
|
||||
pub(super) fn item_effects(item: &AppearanceItem) -> &[Effect] {
|
||||
@@ -103,10 +110,10 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
{
|
||||
return cull_bounds(symbols, &art);
|
||||
}
|
||||
// A Rasterize image moved by the Transform effects after it reaches as far as the map takes
|
||||
// what the art before them reaches, the image included.
|
||||
if let Some((stage, map)) = rasterize_stage(symbols.document(), n) {
|
||||
return staged_reach(map, visual_bounds(symbols, &stage)?);
|
||||
// A Rasterize image moved or copied by the Transform effects after it reaches as far as the
|
||||
// maps take what the art before them reaches, the image included.
|
||||
if let Some((stage, maps)) = rasterize_stage(symbols.document(), n) {
|
||||
return staged_reach(&maps, visual_bounds(symbols, &stage)?);
|
||||
}
|
||||
let bp = node_bezpath(n)?;
|
||||
let ctx = GeomContext { doc: Some(symbols.document()), ..GeomContext::of(n) };
|
||||
@@ -483,8 +490,8 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
if let Some(art) = effects::crop_marks_art(n) {
|
||||
return drawn_bounds(symbols, &art);
|
||||
}
|
||||
if let Some((stage, map)) = rasterize_stage(symbols.document(), n) {
|
||||
return staged_reach(map, painted_reach(symbols, &stage)?);
|
||||
if let Some((stage, maps)) = rasterize_stage(symbols.document(), n) {
|
||||
return staged_reach(&maps, painted_reach(symbols, &stage)?);
|
||||
}
|
||||
let ran = ran(symbols.document(), n);
|
||||
let b = drawn_bounds_ran(symbols, n, Some(&ran))?;
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(super) struct Content<'a> {
|
||||
/// The image of the last Rasterize before a split in an effect stack ([`Renderer::raster_fx`]). It
|
||||
/// is made the first time the effects after the split draw the content and drawn from here the
|
||||
/// other times, so the content before the split is drawn once.
|
||||
pub(super) struct Kept {
|
||||
pub(crate) struct Kept {
|
||||
/// Where the effects after the split take the content from: the visible area grown by how
|
||||
/// far they paint.
|
||||
pub(super) window: Rect,
|
||||
@@ -39,6 +39,17 @@ pub(super) struct Kept {
|
||||
/// [`Renderer::rasterize_image`]'s limits: the content is then drawn in that frame.
|
||||
pub(super) frame: Option<(Affine, f64)>,
|
||||
pub(super) image: std::cell::RefCell<Option<KeptImage>>,
|
||||
/// Kept for the placements of a path's Rasterize image that the Transform effects after it
|
||||
/// copy ([`Renderer::draw_staged`]): it holds only the image on its own grid
|
||||
/// ([`KeptImage::Grid`]), and each placement keeps its own raster across frames.
|
||||
pub(super) shared: bool,
|
||||
}
|
||||
|
||||
impl Kept {
|
||||
/// A [`Kept`] for the placements of one path's Rasterize image (`shared`).
|
||||
pub(super) fn for_placements() -> Self {
|
||||
Kept { window: Rect::ZERO, frame: None, image: std::cell::RefCell::new(None), shared: true }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -95,7 +95,9 @@ impl Renderer {
|
||||
let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink));
|
||||
// Made again at this zoom and rotation (after a pan), a raster cropped to the view covers a
|
||||
// margin around the view too, so that later pans within the margin draw it.
|
||||
let again = key.and_then(|key| self.pixel_fx.get(&key)).is_some_and(|e| e.linear == linear) && content.kept.is_none() && !f.opts.dragging;
|
||||
let again = key.and_then(|key| self.pixel_fx.get(&key)).is_some_and(|e| e.linear == linear)
|
||||
&& content.kept.is_none_or(|k| k.shared)
|
||||
&& !f.opts.dragging;
|
||||
let room = match margin {
|
||||
Some(m) if !fits && again => {
|
||||
let e = pan_margin((screen.width(), screen.height()), m, PIXEL_BUDGET, f64::from(crate::MAX_RASTER_SIDE));
|
||||
@@ -289,7 +291,7 @@ impl Renderer {
|
||||
// A raster kept for this view alone at a lower resolution than the view's is resampled to the
|
||||
// view's pixels once: each frame that draws it then copies it pixel for pixel, where sampling
|
||||
// it again across the whole view cost several times as much as a plain fill.
|
||||
let view_raster = key.is_some() && in_view.is_some() && k < 1.0 && content.kept.is_none();
|
||||
let view_raster = key.is_some() && in_view.is_some() && k < 1.0 && content.kept.is_none_or(|k| k.shared);
|
||||
let (image, x0, y0, k) = match view_raster.then(|| self.resampled(f, image.clone(), (x0, y0), k, screen)).flatten() {
|
||||
Some((image, x, y)) => (image, x, y, 1.0),
|
||||
None => (image, x0, y0, k),
|
||||
@@ -308,8 +310,9 @@ impl Renderer {
|
||||
self.pixel_fx.insert(key, entry);
|
||||
self.trim_fx_rasters(FX_RASTER_BUDGET);
|
||||
}
|
||||
// An image over the limits was drawn at a frame's resolution: its raster is kept.
|
||||
match content.kept.filter(|kept| kept.image.borrow().is_none()) {
|
||||
// An image over the limits was drawn at a frame's resolution: its raster is kept. The
|
||||
// placements of a copied image each draw their own (`Kept::shared`).
|
||||
match content.kept.filter(|kept| !kept.shared && kept.image.borrow().is_none()) {
|
||||
Some(kept) => {
|
||||
let place = f.view.inverse() * Affine::translate((x0, y0)) * Affine::scale(1.0 / k);
|
||||
*kept.image.borrow_mut() = Some(KeptImage::Raster(image.clone(), place, failed, image_left_out));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage};
|
||||
use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, Made, Reads, Shadow, ShadowEntry};
|
||||
use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry};
|
||||
use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted};
|
||||
use super::raster::{
|
||||
DRAG_PIXEL_BUDGET, MAX_RASTERIZE, PIXEL_BUDGET, ViewCrop, content_changing, doc_raster_ppi, image_size, linear_key, pan_margin, pcolor,
|
||||
@@ -10,6 +10,10 @@ use super::{
|
||||
blend_mode, effects, fill_rule, peniko,
|
||||
};
|
||||
|
||||
/// The cache slots of placement `k` of a path's Rasterize image ([`Renderer::draw_staged`]) start
|
||||
/// at `k << PLACEMENT_SLOT_SHIFT`, past those of its effects and of its fills and strokes.
|
||||
const PLACEMENT_SLOT_SHIFT: u32 = 20;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many silhouettes of drop shadows and outer glows renderers on this thread have drawn:
|
||||
@@ -367,11 +371,11 @@ impl Renderer {
|
||||
|
||||
/// [`rasterize_stage`] of `n`, kept across frames when `owner` is `n` as held in its document
|
||||
/// (then `true` in the third place: the stage is kept, and so are its caches).
|
||||
fn rasterize_stage_of(&mut self, f: &Frame, n: &Node, owner: Option<Arc<Node>>) -> Option<(Arc<Node>, Affine, bool)> {
|
||||
fn rasterize_stage_of(&mut self, f: &Frame, n: &Node, owner: Option<Arc<Node>>) -> Option<(Arc<Node>, Arc<[Affine]>, bool)> {
|
||||
// Checked first: this runs for every path with effects drawn.
|
||||
effects::rasterize_stage(&n.appearance.effects)?;
|
||||
let Some(owner) = owner else {
|
||||
return rasterize_stage(f.symbols.document(), n).map(|(stage, map)| (Arc::new(stage), map, false));
|
||||
return rasterize_stage(f.symbols.document(), n).map(|(stage, maps)| (Arc::new(stage), maps.into(), false));
|
||||
};
|
||||
let key = Arc::as_ptr(&owner) as usize;
|
||||
let stamp = self.stamp;
|
||||
@@ -379,31 +383,45 @@ impl Renderer {
|
||||
&& Arc::ptr_eq(&e.0, &owner)
|
||||
{
|
||||
e.3 = stamp;
|
||||
return Some((e.1.clone(), e.2, true));
|
||||
return Some((e.1.clone(), e.2.clone(), true));
|
||||
}
|
||||
let (stage, map) = rasterize_stage(f.symbols.document(), n)?;
|
||||
let stage = Arc::new(stage);
|
||||
self.fx_stages.insert(key, (owner, stage.clone(), map, stamp));
|
||||
Some((stage, map, true))
|
||||
let (stage, maps) = rasterize_stage(f.symbols.document(), n)?;
|
||||
let (stage, maps): (Arc<Node>, Arc<[Affine]>) = (Arc::new(stage), maps.into());
|
||||
self.fx_stages.insert(key, (owner, stage.clone(), maps.clone(), stamp));
|
||||
Some((stage, maps, true))
|
||||
}
|
||||
|
||||
/// Draw `stage`, the node a path's Rasterize image is made from ([`rasterize_stage`]), through
|
||||
/// `map`, the Transform effects after that Rasterize effect: its art and its image, on the
|
||||
/// image's own pixel grid, move with the map. A map that flattens the art leaves nothing to
|
||||
/// draw. `bp` is the path's own path; with `kept`, `stage` is kept across frames and so are
|
||||
/// the geometry and rasters drawn for it.
|
||||
fn draw_staged(&mut self, ctx: &mut RenderContext, f: &Frame, (stage, map, kept): (Arc<Node>, Affine, bool), bp: &BezPath, rule: FillRule) {
|
||||
let det = map.determinant();
|
||||
if !(det.is_finite() && det.abs() > 1e-12) {
|
||||
return;
|
||||
/// each of `maps`, the Transform effects after that Rasterize effect, the lowest first: its art
|
||||
/// and its image, on the image's own pixel grid, move with each map. A map that flattens the
|
||||
/// art leaves nothing to draw. `bp` is the path's own path; with `kept`, `stage` is kept across
|
||||
/// frames and so are the geometry and rasters drawn for it. With more than one map, the image
|
||||
/// is made once for all of them ([`Kept::for_placements`]), and each placement keeps its own
|
||||
/// rasters in its own cache slots.
|
||||
fn draw_staged(
|
||||
&mut self,
|
||||
ctx: &mut RenderContext,
|
||||
f: &Frame,
|
||||
(stage, maps, kept): (Arc<Node>, Arc<[Affine]>, bool),
|
||||
bp: &BezPath,
|
||||
rule: FillRule,
|
||||
) {
|
||||
let shared = (maps.len() > 1).then(|| std::rc::Rc::new(Kept::for_placements()));
|
||||
for (k, map) in maps.iter().enumerate() {
|
||||
let det = map.determinant();
|
||||
if !(det.is_finite() && det.abs() > 1e-12) {
|
||||
continue;
|
||||
}
|
||||
// A pixel's size in document units through the view and the map, measured as a frame
|
||||
// measures it from its view.
|
||||
let px = f.px / det.abs().sqrt();
|
||||
let fr = Frame { view: f.view * *map, visible: map.inverse().transform_rect_bbox(f.visible), px, output: f.output * *map, ..*f };
|
||||
let outer = if kept { self.fx_owner.replace(stage.clone()) } else { self.fx_owner.take() };
|
||||
self.fx_placement = shared.as_ref().map(|s| (k << PLACEMENT_SLOT_SHIFT, s.clone()));
|
||||
self.draw_shape_fx(ctx, &fr, &stage, bp, rule);
|
||||
self.fx_placement = None;
|
||||
self.fx_owner = outer;
|
||||
}
|
||||
// A pixel's size in document units through the view and the map, measured as a frame
|
||||
// measures it from its view.
|
||||
let px = f.px / det.abs().sqrt();
|
||||
let fr = Frame { view: f.view * map, visible: map.inverse().transform_rect_bbox(f.visible), px, output: f.output * map, ..*f };
|
||||
let outer = if kept { self.fx_owner.replace(stage.clone()) } else { self.fx_owner.take() };
|
||||
self.draw_shape_fx(ctx, &fr, &stage, bp, rule);
|
||||
self.fx_owner = outer;
|
||||
}
|
||||
|
||||
/// [`Self::draw_shape_fx`] on the effected geometry `g`, with the items' cached geometry:
|
||||
@@ -435,7 +453,10 @@ impl Renderer {
|
||||
let bounds = rasterize_bounds(f.symbols, n, &rfx);
|
||||
// Under Rasterize the content reaches as far as its fills' and strokes' raster effects paint.
|
||||
let reach = bounds.map_or(reach, |b| reach.union(b));
|
||||
let content = Content { node: n, owner: None, cache: Some(0), reach, object: reach, outline: Some((g, rule)), bounds, kept: None };
|
||||
// One of several placements of a path's Rasterize image ([`Self::draw_staged`]).
|
||||
let placement = self.fx_placement.take();
|
||||
let (slot, kept) = placement.as_ref().map_or((0, None), |(slot, kept)| (*slot, Some(&**kept)));
|
||||
let content = Content { node: n, owner: None, cache: Some(slot), reach, object: reach, outline: Some((g, rule)), bounds, kept };
|
||||
let mut items = items;
|
||||
self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.paint_items(c, fr, paints, g, rule, &gctx, items.as_deref_mut()));
|
||||
ctx.set_transform(Affine::IDENTITY);
|
||||
@@ -829,7 +850,11 @@ impl Renderer {
|
||||
w.inflate(o, o)
|
||||
});
|
||||
let frame = last_over.then_some((f.view, f.px));
|
||||
let kept = (split > at).then(|| Kept { window, frame, image: std::cell::RefCell::new(None) });
|
||||
// One of several placements of a path's Rasterize image ([`Self::draw_staged`])
|
||||
// starts from the image on its own grid that the placements share.
|
||||
let placements = content.kept.filter(|k| k.shared);
|
||||
let grid = placements.and_then(|k| k.image.borrow().clone().filter(|i| matches!(i, KeptImage::Grid(..))));
|
||||
let kept = (split > at).then(|| Kept { window, frame, image: std::cell::RefCell::new(grid), shared: false });
|
||||
let inner = Content {
|
||||
node: content.node,
|
||||
owner: content.owner,
|
||||
@@ -854,6 +879,13 @@ impl Renderer {
|
||||
kept: content.kept.filter(|_| split == at),
|
||||
};
|
||||
self.raster_fx(ctx, f, &outer, after, &mut |r, c, fr| r.raster_fx(c, fr, &inner, before, paint));
|
||||
// The image made on its own grid is the one the other placements draw.
|
||||
if let (Some(shared), Some(kept)) = (placements, &kept)
|
||||
&& shared.image.borrow().is_none()
|
||||
&& let Some(grid @ KeptImage::Grid(..)) = kept.image.borrow().clone()
|
||||
{
|
||||
*shared.image.borrow_mut() = Some(grid);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,11 @@ type MeasuredArt = (Arc<Node>, Arc<Node>, Option<u64>);
|
||||
/// raster effects resolution (its bits) with a brush library (its key).
|
||||
type ThreeDArt = (std::sync::Weak<Node>, Option<((u64, u64), Option<Rect>)>);
|
||||
|
||||
/// A node whose Rasterize image the Transform effects after it place ([`fx::rasterize_stage`]):
|
||||
/// the node, the node it draws its image from, the maps that place the image, and the frame it
|
||||
/// was last drawn in.
|
||||
type FxStage = (Arc<Node>, Arc<Node>, Arc<[Affine]>, u64);
|
||||
|
||||
/// Reusable renderer (keeps the render context, geometry and glyph caches between frames; decoded
|
||||
/// images are shared by all renderers, see [`set_image_cache_budget`]).
|
||||
pub struct Renderer {
|
||||
@@ -126,9 +131,11 @@ pub struct Renderer {
|
||||
/// Live-effect geometry per node ([`fx::FxGeom`]), keyed by `Arc` identity like `geom`.
|
||||
fx_geom: PtrMap<usize, fx::FxGeom>,
|
||||
/// Per node whose Rasterize image moves with the Transform effects after it, keyed by `Arc`
|
||||
/// identity like `fx_geom`: the node, the node it draws its image from and the map that moves
|
||||
/// the image ([`fx::rasterize_stage`]), and the frame it was last drawn in.
|
||||
fx_stages: PtrMap<usize, (Arc<Node>, Arc<Node>, Affine, u64)>,
|
||||
/// identity like `fx_geom` ([`FxStage`]).
|
||||
fx_stages: PtrMap<usize, FxStage>,
|
||||
/// While one of several placements of a path's Rasterize image is drawn: the first cache slot
|
||||
/// of that placement's rasters and where the image is kept for all of them ([`fx::Kept`]).
|
||||
fx_placement: Option<(usize, std::rc::Rc<fx::Kept>)>,
|
||||
stamp: u64,
|
||||
/// Opacity folded into paint alpha for the leaf being drawn (avoids a compositing layer).
|
||||
alpha: f32,
|
||||
|
||||
@@ -57,6 +57,7 @@ impl Renderer {
|
||||
live_root: None,
|
||||
fx_geom: PtrMap::default(),
|
||||
fx_stages: PtrMap::default(),
|
||||
fx_placement: None,
|
||||
stamp: 0,
|
||||
alpha: 1.0,
|
||||
contexts: Vec::new(),
|
||||
|
||||
@@ -517,3 +517,100 @@ fn rasterize_before_a_hidden_transform_keeps_its_image() {
|
||||
Arc::make_mut(&mut hidden.children_mut(Some(l)).unwrap()[0]).appearance.effects[1].visible = false;
|
||||
assert!(plain.pixels == draw(&hidden, 10.0, 400).pixels);
|
||||
}
|
||||
|
||||
/// Red triangles ([`triangle`]), one for each list of effects in `each`, the first lowest, in a
|
||||
/// document whose raster effects resolution is 72 ppi.
|
||||
fn stacked(each: &[Vec<(&str, Value)>]) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 72.0;
|
||||
let l = d.layers[0].id;
|
||||
for (i, fx) in each.iter().enumerate() {
|
||||
let mut n = Node::path(d.alloc_id(), triangle(), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0));
|
||||
n.appearance.effects = fx.iter().map(|(id, params)| Effect { id: (*id).into(), params: params.clone(), visible: true }).collect();
|
||||
d.insert(Some(l), i, n).unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// Each copy a Transform effect after Rasterize makes carries the image made before it: the canvas
|
||||
/// draws the same pixels as one object moved once for each copy, the last copy lowest and the
|
||||
/// original on top, turned with each copy's map, the pixel grid and the white room around the art
|
||||
/// included. The image is made once for all of them, and the drawn bounds take in every copy.
|
||||
#[test]
|
||||
fn rasterize_then_copying_transform_places_the_image_on_each_copy() {
|
||||
let raster = ("rasterize", hard(json!({"background": "white", "addAround": 1})));
|
||||
let moved = |params: Value| vec![raster.clone(), ("distort.transform", params)];
|
||||
let cases = [
|
||||
(json!({"moveH": 30, "copies": 2}), [json!({"moveH": 60}), json!({"moveH": 30})]),
|
||||
// Overlapping copies: the white room of the original covers the copies below it.
|
||||
(json!({"rotate": 90, "copies": 2}), [json!({"rotate": 180}), json!({"rotate": 90})]),
|
||||
(json!({"reflectX": true, "copies": 2}), [json!({}), json!({"reflectX": true})]),
|
||||
];
|
||||
for (params, [lowest, middle]) in cases {
|
||||
let copied = doc(triangle(), &moved(params.clone()), 72.0);
|
||||
let want = stacked(&[moved(lowest), moved(middle), vec![raster.clone()]]);
|
||||
let drawn = || crate::fx::RASTERIZED.with(std::cell::Cell::get);
|
||||
let before = drawn();
|
||||
let r = draw(&copied, 4.0, 400);
|
||||
assert_eq!(drawn() - before, 1, "{params}: one image for the three placements");
|
||||
let w = draw(&want, 4.0, 400);
|
||||
let off = r.pixels.iter().zip(&w.pixels).filter(|(a, b)| a.abs_diff(**b) > 2).count();
|
||||
assert_eq!(off, 0, "{params}");
|
||||
assert!(r.pixels.chunks(4).any(|p| p[3] > 0), "{params}");
|
||||
let n = copied.layers[0].children().unwrap()[0].clone();
|
||||
let b = crate::drawn_bounds(&copied, &n).unwrap();
|
||||
let want_b = want.layers[0].children().unwrap().iter().filter_map(|c| crate::drawn_bounds(&want, c)).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(
|
||||
[b.x0 - want_b.x0, b.y0 - want_b.y0, b.x1 - want_b.x1, b.y1 - want_b.y1].iter().all(|d| d.abs() < 1e-6),
|
||||
"{params}: {b:?} {want_b:?}"
|
||||
);
|
||||
}
|
||||
// Three placements 30 pt apart, each the 20 pt art and 1 pt of white around it: 9..91 pt.
|
||||
let copied = doc(triangle(), &moved(json!({"moveH": 30, "copies": 2})), 72.0);
|
||||
let n = copied.layers[0].children().unwrap()[0].clone();
|
||||
let b = crate::drawn_bounds(&copied, &n).unwrap();
|
||||
assert!((b.x0 - 9.0).abs() < 1e-9 && (b.x1 - 91.0).abs() < 1e-9 && (b.y0 - 9.0).abs() < 1e-9 && (b.y1 - 31.0).abs() < 1e-9, "{b:?}");
|
||||
// A renderer that keeps the placements' rasters draws the next frame without making the image.
|
||||
let mut renderer = Renderer::new();
|
||||
let opts = RenderOptions { background: None, artboards: false, ..Default::default() };
|
||||
let rotated = doc(triangle(), &moved(json!({"rotate": 90, "copies": 2})), 72.0);
|
||||
let first = renderer.render(&rotated, 400, 400, Affine::scale(4.0), &opts);
|
||||
let drawn = || crate::fx::RASTERIZED.with(std::cell::Cell::get);
|
||||
let before = drawn();
|
||||
let again = renderer.render(&rotated, 400, 400, Affine::scale(4.0), &opts);
|
||||
assert_eq!(drawn() - before, 0);
|
||||
assert!(first.pixels == again.pixels);
|
||||
}
|
||||
|
||||
/// A shadow listed between Rasterize and a Transform effect with copies paints around each
|
||||
/// placement of the image, as it does around one object moved once for each copy, and the image
|
||||
/// is still made once for all the placements.
|
||||
#[test]
|
||||
fn rasterize_then_shadow_then_copying_transform_makes_the_image_once() {
|
||||
let raster = ("rasterize", hard(json!({"background": "white", "addAround": 1})));
|
||||
let shadow = ("stylize.dropShadow", json!({"mode": "normal", "opacity": 100, "x": 2, "y": 2, "blur": 0, "color": "#0000ff"}));
|
||||
let moved = |params: Value| vec![raster.clone(), shadow.clone(), ("distort.transform", params)];
|
||||
let copied = doc(triangle(), &moved(json!({"moveH": 30, "copies": 2})), 72.0);
|
||||
let want = stacked(&[moved(json!({"moveH": 60})), moved(json!({"moveH": 30})), vec![raster.clone(), shadow.clone()]]);
|
||||
let drawn = || crate::fx::RASTERIZED.with(std::cell::Cell::get);
|
||||
let before = drawn();
|
||||
let r = draw(&copied, 4.0, 400);
|
||||
assert_eq!(drawn() - before, 1, "one image for the three placements");
|
||||
let w = draw(&want, 4.0, 400);
|
||||
let off = r.pixels.iter().zip(&w.pixels).filter(|(a, b)| a.abs_diff(**b) > 2).count();
|
||||
assert_eq!(off, 0);
|
||||
assert!(r.pixels.chunks(4).any(|p| p[2] > 200 && p[0] < 50 && p[3] > 200), "the shadow is drawn");
|
||||
}
|
||||
|
||||
/// Copies that a Transform effect after Rasterize scales to nothing leave nothing to draw or
|
||||
/// measure; the original, which the effect leaves where it is, is still drawn and measured.
|
||||
#[test]
|
||||
fn rasterize_then_copies_scaled_to_nothing_are_left_out() {
|
||||
let raster = ("rasterize", hard(json!({"background": "white"})));
|
||||
let d = doc(triangle(), &[raster.clone(), ("distort.transform", json!({"scaleH": 0, "copies": 3}))], 72.0);
|
||||
let plain = doc(triangle(), &[raster], 72.0);
|
||||
assert!(draw(&d, 10.0, 400).pixels == draw(&plain, 10.0, 400).pixels);
|
||||
let bounds = |d: &Document| crate::drawn_bounds(d, &d.layers[0].children().unwrap()[0]);
|
||||
assert_eq!(bounds(&d), bounds(&plain));
|
||||
assert!(bounds(&d).is_some());
|
||||
}
|
||||
@@ -10,6 +10,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-svg = { workspace = true }
|
||||
craft-mime = { workspace = true }
|
||||
# Which paths stored in documents may be opened.
|
||||
craft-docpath = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
|
||||
+15
-11
@@ -592,17 +592,8 @@ fn fnv1a_from(h: u64, bytes: &[u8]) -> u64 {
|
||||
|
||||
/// Standard base64 (RFC 4648, with padding).
|
||||
pub fn base64_encode(data: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for c in data.chunks(3) {
|
||||
let b = [c[0], *c.get(1).unwrap_or(&0), *c.get(2).unwrap_or(&0)];
|
||||
let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
|
||||
out.push(T[(n >> 18) as usize & 63] as char);
|
||||
out.push(T[(n >> 12) as usize & 63] as char);
|
||||
out.push(if c.len() > 1 { T[(n >> 6) as usize & 63] as char } else { '=' });
|
||||
out.push(if c.len() > 2 { T[n as usize & 63] as char } else { '=' });
|
||||
}
|
||||
out
|
||||
// SVG data URLs need one unwrapped line, not MIME's folded base64_lines variant.
|
||||
craft_mime::transfer::base64(data)
|
||||
}
|
||||
|
||||
/// Escape text for XML content and attribute values.
|
||||
@@ -704,6 +695,19 @@ mod tests {
|
||||
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_binary_payload_stays_standard_padded_and_unwrapped() {
|
||||
let data: Vec<u8> = (0..=255).collect();
|
||||
assert_eq!(
|
||||
base64_encode(&data),
|
||||
"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="
|
||||
);
|
||||
assert_eq!(base64_encode(&[0xfb, 0xff, 0xff]), "+///");
|
||||
assert_eq!(base64_encode(&[0xfb]), "+w==");
|
||||
assert_eq!(base64_encode(&[0xfb, 0xff]), "+/8=");
|
||||
assert_eq!(base64_encode(&[0; 60]), "A".repeat(80));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers() {
|
||||
assert_eq!(fmt_num(1.0, 3), "1");
|
||||
|
||||
@@ -17,6 +17,7 @@ use crate::GlyphImage;
|
||||
use crate::colr::ColourContent;
|
||||
use vectorcraft_doc::color::Color;
|
||||
|
||||
mod added;
|
||||
mod alternates;
|
||||
mod build;
|
||||
mod cache;
|
||||
@@ -33,6 +34,9 @@ mod stylistic_sets;
|
||||
mod traits;
|
||||
mod wanted;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use added::recently_added_of;
|
||||
pub use added::{RECENTLY_ADDED_WITHIN, RecentlyAdded};
|
||||
pub use alternates::GlyphAlternate;
|
||||
pub(crate) use alternates::listed;
|
||||
pub use build::style_weight;
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Recently added fonts: the installed families with a font file created on this computer in the
|
||||
//! last 30 days ([`FontDb::recently_added`]).
|
||||
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use super::FontDb;
|
||||
|
||||
/// How long a family counts as recently added after its newest font file was created: 30 days.
|
||||
pub const RECENTLY_ADDED_WITHIN: Duration = Duration::from_secs(30 * 24 * 60 * 60);
|
||||
|
||||
/// The installed families added recently ([`FontDb::recently_added`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RecentlyAdded {
|
||||
/// The families by their catalog names, the one with the newest font file first. Families
|
||||
/// whose newest files were created at the same instant are in name order, case ignored.
|
||||
pub families: Vec<String>,
|
||||
/// The list is the same for every time from the one asked for up to this instant, and is to be
|
||||
/// asked for again from it on: when a listed family's newest file turns
|
||||
/// [`RECENTLY_ADDED_WITHIN`] old, or when a file dated after the time asked for starts to
|
||||
/// count. `None`: the list stays as it is until fonts are installed or removed.
|
||||
pub recheck_at: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl FontDb {
|
||||
/// The installed families with a font file created within [`RECENTLY_ADDED_WITHIN`] before
|
||||
/// `now`, the boundary included, newest first. A family's date is that of its newest font file
|
||||
/// created at or before `now`. A file without a creation time (the file system keeps none)
|
||||
/// or dated after `now` does not count, so a family with no other file is left out. The
|
||||
/// creation time is when the file was made on this computer: copying a font in or installing
|
||||
/// it makes a new file, while a font kept elsewhere and linked or activated by a font manager
|
||||
/// is dated by the file the link leads to. Fonts loaded from bytes and the bundled fonts are
|
||||
/// never listed. Empty on wasm, which has no installed fonts.
|
||||
pub fn recently_added(&self, now: SystemTime) -> RecentlyAdded {
|
||||
let catalog = self.read_catalog();
|
||||
recently_added_of(catalog.values().map(|c| (c.name.as_str(), c.faces.iter().map(|f| f.created))), now)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`FontDb::recently_added`] of `families`, each a name with the creation times of its faces'
|
||||
/// files (`None`: unknown).
|
||||
pub(crate) fn recently_added_of<'a, T>(families: impl IntoIterator<Item = (&'a str, T)>, now: SystemTime) -> RecentlyAdded
|
||||
where
|
||||
T: IntoIterator<Item = Option<SystemTime>>,
|
||||
{
|
||||
let mut dated: Vec<(SystemTime, &str)> = Vec::new();
|
||||
let mut recheck_at: Option<SystemTime> = None;
|
||||
let mut sooner = |t: SystemTime| recheck_at = Some(recheck_at.map_or(t, |r| r.min(t)));
|
||||
for (name, times) in families {
|
||||
let mut newest: Option<SystemTime> = None;
|
||||
for t in times.into_iter().flatten() {
|
||||
if t > now {
|
||||
sooner(t);
|
||||
} else if newest.is_none_or(|n| t > n) {
|
||||
newest = Some(t);
|
||||
}
|
||||
}
|
||||
let Some(newest) = newest else { continue };
|
||||
match newest.checked_add(RECENTLY_ADDED_WITHIN) {
|
||||
Some(leaves) if leaves < now => {}
|
||||
Some(leaves) => {
|
||||
sooner(leaves);
|
||||
dated.push((newest, name));
|
||||
}
|
||||
None => dated.push((newest, name)),
|
||||
}
|
||||
}
|
||||
dated.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase())).then_with(|| a.1.cmp(b.1)));
|
||||
RecentlyAdded { families: dated.into_iter().map(|(_, name)| name.to_string()).collect(), recheck_at }
|
||||
}
|
||||
@@ -24,6 +24,9 @@ pub(super) struct CatalogFace {
|
||||
/// Weight and italic as the style lists them (by its name, or a named instance's axes).
|
||||
pub(super) weight: f32,
|
||||
pub(super) italic: bool,
|
||||
/// When the file was created ([`FontDb::recently_added`]); `None` when the file system keeps
|
||||
/// no creation time.
|
||||
pub(super) created: Option<std::time::SystemTime>,
|
||||
}
|
||||
|
||||
/// The installed fonts by ASCII-lowercased family name (lookups ignore ASCII case, as
|
||||
|
||||
@@ -419,6 +419,8 @@ impl FontDb {
|
||||
if !named && !is_font_file(&p) && !crate::suitcase::is_suitcase(&p) {
|
||||
continue;
|
||||
}
|
||||
// The file's creation time, once for all its faces (a collection holds several).
|
||||
let created = std::fs::metadata(&p).and_then(|m| m.created()).ok();
|
||||
for FaceStyle { family, native_family, style, keys, weight, italic, traits, .. } in file_face_names(&p) {
|
||||
for (k, a) in Alias::of(&family, &style, &keys) {
|
||||
aliases.entry(k).or_default().push(a);
|
||||
@@ -440,7 +442,7 @@ impl FontDb {
|
||||
entry.native = native_family;
|
||||
}
|
||||
let (weight, italic) = (weight.unwrap_or_else(|| style_weight(&style)), italic || style_italic(&style));
|
||||
entry.faces.push(CatalogFace { style, path: p.clone(), weight, italic });
|
||||
entry.faces.push(CatalogFace { style, path: p.clone(), weight, italic, created });
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,9 +42,9 @@ pub use features::{
|
||||
};
|
||||
pub use fontdb::{
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GlyphAlternate, GlyphCategory,
|
||||
GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind,
|
||||
WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs,
|
||||
set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
|
||||
GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded,
|
||||
StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir,
|
||||
set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
|
||||
};
|
||||
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
|
||||
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
|
||||
|
||||
@@ -26,6 +26,7 @@ mod kept_layouts;
|
||||
mod kerning_before;
|
||||
mod ligature_carets;
|
||||
mod path_joins;
|
||||
mod recently_added;
|
||||
mod ruby;
|
||||
mod scripts;
|
||||
mod shape_plans;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Recently added fonts ([`FontDb::recently_added`]): which installed families count, in which
|
||||
//! order, and until when, at a time the tests choose.
|
||||
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use crate::fontdb::recently_added_of;
|
||||
use crate::*;
|
||||
|
||||
const DAY: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
|
||||
/// A fixed instant the tests count from.
|
||||
fn now() -> SystemTime {
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000)
|
||||
}
|
||||
|
||||
/// `days` days (and `secs` seconds) before [`now`].
|
||||
fn ago(days: u32, secs: u64) -> Option<SystemTime> {
|
||||
now().checked_sub(DAY * days + Duration::from_secs(secs))
|
||||
}
|
||||
|
||||
/// [`recently_added_of`] for families with these creation times, at `at`.
|
||||
fn added(families: &[(&str, &[Option<SystemTime>])], at: SystemTime) -> RecentlyAdded {
|
||||
recently_added_of(families.iter().map(|(name, times)| (*name, times.iter().copied())), at)
|
||||
}
|
||||
|
||||
/// A family counts for 30 days after its newest file was created, the 30th day's last instant
|
||||
/// included; the newest comes first.
|
||||
#[test]
|
||||
fn families_added_in_the_last_30_days_are_listed_newest_first() {
|
||||
let families: &[(&str, &[Option<SystemTime>])] =
|
||||
&[("Older", &[ago(29, 0)]), ("Boundary", &[ago(30, 0)]), ("Expired", &[ago(30, 1)]), ("Newest", &[ago(0, 5)]), ("Middle", &[ago(3, 0)])];
|
||||
let list = added(families, now());
|
||||
assert_eq!(list.families, ["Newest", "Middle", "Older", "Boundary"]);
|
||||
assert_eq!(list.recheck_at, Some(now()), "Boundary leaves after this instant");
|
||||
// A day and a second later, the two oldest have left, without the files changing.
|
||||
let later = added(families, now() + DAY + Duration::from_secs(1));
|
||||
assert_eq!(later.families, ["Newest", "Middle"]);
|
||||
assert_eq!(later.recheck_at, ago(3, 0).map(|t| t + RECENTLY_ADDED_WITHIN));
|
||||
}
|
||||
|
||||
/// A family is dated by its newest file at or before the time asked for. Files without a creation
|
||||
/// time, or dated after that time, do not count, and a family with no other file is left out until
|
||||
/// its future-dated file's time comes.
|
||||
#[test]
|
||||
fn a_family_is_dated_by_its_newest_valid_file() {
|
||||
let future = now() + DAY;
|
||||
let families: &[(&str, &[Option<SystemTime>])] = &[
|
||||
("Several", &[ago(40, 0), ago(2, 0), None, Some(future)]),
|
||||
("Unknown", &[None, None]),
|
||||
("Future", &[Some(future)]),
|
||||
("Old", &[ago(31, 0)]),
|
||||
("One", &[ago(1, 0)]),
|
||||
];
|
||||
let list = added(families, now());
|
||||
assert_eq!(list.families, ["One", "Several"]);
|
||||
assert_eq!(list.recheck_at, Some(future), "the future-dated files count from their time on");
|
||||
assert_eq!(added(families, future).families, ["Future", "Several", "One"]);
|
||||
assert!(added(&[("Unknown", &[None])], now()).recheck_at.is_none());
|
||||
}
|
||||
|
||||
/// Families added at the same instant are in name order, case ignored, whatever order the
|
||||
/// catalog gives them in.
|
||||
#[test]
|
||||
fn families_added_at_the_same_instant_are_in_name_order() {
|
||||
let t = ago(1, 0);
|
||||
let families: &[(&str, &[Option<SystemTime>])] = &[("delta", &[t]), ("Bravo", &[t]), ("alpha", &[t]), ("Charlie", &[t])];
|
||||
assert_eq!(added(families, now()).families, ["alpha", "Bravo", "Charlie", "delta"]);
|
||||
let reversed: Vec<_> = families.iter().rev().copied().collect();
|
||||
assert_eq!(added(&reversed, now()).families, ["alpha", "Bravo", "Charlie", "delta"]);
|
||||
}
|
||||
|
||||
/// Nothing installed, or nothing dated: an empty list with nothing to recheck.
|
||||
#[test]
|
||||
fn no_dated_families_list_nothing() {
|
||||
assert_eq!(added(&[], now()), RecentlyAdded::default());
|
||||
assert_eq!(FontDb::with_font_dirs(vec![]).recently_added(now()), RecentlyAdded::default(), "the bundled fonts are not installed fonts");
|
||||
}
|
||||
@@ -298,6 +298,30 @@ fn rescanning_drops_loaded_fonts_removed_since() {
|
||||
assert_eq!(db.outline(&again, glyph).elements(), db.outline(&face, glyph).elements());
|
||||
}
|
||||
|
||||
/// The scan dates each installed family by its font files' creation times: a family installed
|
||||
/// just now is recently added for 30 days, and leaves the list when its files are removed and the
|
||||
/// folders scanned again. Where the file system keeps no creation time, nothing is listed.
|
||||
#[test]
|
||||
fn installed_fonts_are_recently_added_by_their_files_creation_time() {
|
||||
let dir = font_dir("recently-added");
|
||||
let regular = dir.join("Sysfont-Regular.ttf");
|
||||
let created = std::fs::metadata(®ular).and_then(|m| m.created()).ok();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let now = std::time::SystemTime::now();
|
||||
let list = db.recently_added(now);
|
||||
let Some(created) = created else {
|
||||
assert_eq!(list, RecentlyAdded::default(), "no creation times: nothing is dated");
|
||||
return;
|
||||
};
|
||||
assert_eq!(list.families, [FAMILY]);
|
||||
assert!(list.recheck_at.is_some_and(|t| t >= created + RECENTLY_ADDED_WITHIN), "{list:?}");
|
||||
assert!(db.recently_added(now + RECENTLY_ADDED_WITHIN + std::time::Duration::from_secs(60)).families.is_empty(), "31 days on");
|
||||
std::fs::remove_file(®ular).unwrap();
|
||||
std::fs::remove_file(dir.join("Sub/Sysfont-Bold.TTF")).unwrap();
|
||||
assert_eq!(db.load_system_fonts(), 0);
|
||||
assert_eq!(db.recently_added(now), RecentlyAdded::default(), "removed fonts leave the list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_scan_serves_the_first_lookup() {
|
||||
let dir = font_dir("background");
|
||||
|
||||
+108
-1
@@ -2,7 +2,8 @@
|
||||
//!
|
||||
//! Flare: drag sets the center and its size and turns the rays as the pointer moves up or down
|
||||
//! (Shift holds their turn, ↑/↓ add or remove rays and Ctrl/Cmd keeps the center's size while the
|
||||
//! drag sizes the halo; click without dragging opens the Flare Tool Options), then a click sets the
|
||||
//! drag sizes the halo; click without dragging opens the Flare Tool Options, and Alt-click (Option
|
||||
//! on macOS) draws a flare there with them at once), then a click sets the
|
||||
//! end point of the rings (↑/↓ add or remove rings and ~ places them anew); Space held during
|
||||
//! either drag moves the flare. The rest comes
|
||||
//! from the tool's options (the Flare Tool Options, which last). Reshape: a click on a selected
|
||||
@@ -59,6 +60,9 @@ pub struct FlareTool {
|
||||
/// The pointer at the last press or drag, from which Space held moves the flare.
|
||||
last: Point,
|
||||
began: bool,
|
||||
/// Whether Alt (Option on macOS) was held when the button went down for the center: a release
|
||||
/// without a drag then draws a flare with the options at once.
|
||||
alt_press: bool,
|
||||
/// Ray count changed with ↑/↓ during the center drag (None = the options' count).
|
||||
rays: Option<u64>,
|
||||
/// Ring count changed with ↑/↓ while the rings' end point is placed (None = the options' count).
|
||||
@@ -89,6 +93,7 @@ impl Default for FlareTool {
|
||||
hover: Point::ZERO,
|
||||
last: Point::ZERO,
|
||||
began: false,
|
||||
alt_press: false,
|
||||
rays: None,
|
||||
rings: None,
|
||||
ring_seed: None,
|
||||
@@ -225,6 +230,20 @@ impl FlareTool {
|
||||
fn center_diameter(&self, dist: f64) -> f64 {
|
||||
self.held.map_or(2.0 * dist, |(d, ..)| d)
|
||||
}
|
||||
|
||||
/// Alt-click (Option-click on macOS) at `c`: one flare drawn with the options as they are, as one
|
||||
/// command, so a refusal (a click beyond the plane's horizon) reaches the caller as an error.
|
||||
/// While the perspective grid shows with an active plane, the flare goes on that plane with its
|
||||
/// sizes in plane units from the click, as the Flare Tool Options opened by a click draw it.
|
||||
fn click_flare(&self, cx: &ToolContext, c: Point) -> Vec<Action> {
|
||||
let params = flare_params(&self.options(), c);
|
||||
let grid = crate::distort::perspective::PerspectiveGrid::current(cx.doc);
|
||||
if grid.visible && grid.plane != crate::distort::perspective::Plane::None {
|
||||
vec![Action::Exec("perspective.draw".into(), json!({ "command": "shape.flare", "params": params, "at": [c.x, c.y] }))]
|
||||
} else {
|
||||
vec![Action::Exec("shape.flare".into(), params)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Tool for FlareTool {
|
||||
@@ -252,6 +271,7 @@ impl Tool for FlareTool {
|
||||
self.held = None;
|
||||
self.growth = None;
|
||||
self.turn = 0.0;
|
||||
self.alt_press = ev.mods.alt;
|
||||
}
|
||||
self.last = ev.pos;
|
||||
vec![]
|
||||
@@ -298,6 +318,8 @@ impl Tool for FlareTool {
|
||||
self.placed = Some((c, self.center_diameter(p.distance(c))));
|
||||
self.held = None;
|
||||
vec![]
|
||||
} else if std::mem::take(&mut self.alt_press) {
|
||||
self.click_flare(cx, c)
|
||||
} else {
|
||||
vec![Action::Dialog("flare".into(), json!({ "x": c.x, "y": c.y }))]
|
||||
}
|
||||
@@ -855,6 +877,91 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Alt-click (Option-click on macOS): with Alt held when the button goes down, a release without
|
||||
/// a drag draws one flare at the click with the options as they are, Rays and Rings off included,
|
||||
/// and opens no dialog. A plain click, or Alt pressed only for the release, opens the Flare Tool
|
||||
/// Options; an Alt drag draws the flare in two stages as any drag does; Escape drops the press.
|
||||
#[test]
|
||||
fn alt_click_draws_a_flare_with_the_options_at_once() {
|
||||
use crate::testutil::*;
|
||||
use vectorcraft_doc::Selection;
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let alt = Mods { alt: true, ..Default::default() };
|
||||
let click = |t: &mut FlareTool, down: Mods, up: Mods| {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0, 140.0).with_mods(down));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 120.0, 140.0).with_mods(up))
|
||||
};
|
||||
let mut t = FlareTool::default();
|
||||
for (k, v) in [("diameter", json!(40)), ("rays", json!(7)), ("growth", json!(80)), ("ringsOn", json!(false))] {
|
||||
t.set_option(k, &v);
|
||||
}
|
||||
let options = t.options();
|
||||
let a = click(&mut t, alt, alt);
|
||||
let c = Point::new(120.0, 140.0);
|
||||
let v = flare_params(&options, c);
|
||||
assert_eq!(a, vec![Action::Exec("shape.flare".into(), v.clone())]);
|
||||
assert_eq!(
|
||||
(v["cx"].as_f64(), v["cy"].as_f64(), v["diameter"].as_f64(), v["rays"].as_u64(), v["growth"].as_f64(), v["rings"].as_u64()),
|
||||
(Some(120.0), Some(140.0), Some(40.0), Some(7), Some(80.0), Some(0))
|
||||
);
|
||||
assert_eq!(t.options(), options, "the click leaves the options as they are");
|
||||
assert!(!t.busy());
|
||||
// Alt let go before the release still counts; Alt pressed only for the release does not.
|
||||
assert_eq!(click(&mut t, alt, Mods::default()), vec![Action::Exec("shape.flare".into(), v)]);
|
||||
let dialog = vec![Action::Dialog("flare".into(), json!({ "x": 120.0, "y": 140.0 }))];
|
||||
assert_eq!(click(&mut t, Mods::default(), alt), dialog);
|
||||
assert_eq!(click(&mut t, Mods::default(), Mods::default()), dialog, "a plain click after an Alt-click opens the dialog");
|
||||
// An Alt drag places the center and waits for the rings' end point, as any drag does.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(alt));
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 100.0).with_mods(alt)).first(), Some(&Action::Begin("Flare".into())));
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 140.0, 100.0).with_mods(alt)), vec![]);
|
||||
assert!(t.placed.is_some());
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 200.0).with_mods(alt));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 300.0, 200.0).with_mods(alt));
|
||||
assert_eq!(a.last(), Some(&Action::Commit));
|
||||
assert_eq!((flare_preview(&a)["diameter"].as_f64(), flare_preview(&a)["x2"].as_f64()), (Some(80.0), Some(300.0)));
|
||||
// Escape before the release drops the press: no flare and no dialog.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0, 140.0).with_mods(alt));
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![]);
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 120.0, 140.0).with_mods(alt)), vec![]);
|
||||
}
|
||||
|
||||
/// With the perspective grid showing and a plane active, an Alt-click draws the flare on that
|
||||
/// plane from the click (`perspective.draw` with `at`), as the click-opened dialog does.
|
||||
#[test]
|
||||
fn alt_click_draws_on_the_active_perspective_plane() {
|
||||
use crate::distort::perspective::{PerspectiveGrid, Plane};
|
||||
use crate::testutil::*;
|
||||
use vectorcraft_doc::Selection;
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let alt = Mods { alt: true, ..Default::default() };
|
||||
let c = Point::new(300.0, 380.0);
|
||||
let mut t = FlareTool::default();
|
||||
PerspectiveGrid { visible: true, plane: Plane::Left, ..PerspectiveGrid::current(&d) }.store(&mut d);
|
||||
let mut alt_click = |d: &vectorcraft_doc::Document| {
|
||||
let cx = cx(d, &s, &p);
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, c.x, c.y).with_mods(alt));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, c.x, c.y).with_mods(alt))
|
||||
};
|
||||
let params = flare_params(&FlareTool::default().options(), c);
|
||||
let on_plane = json!({ "command": "shape.flare", "params": params, "at": [c.x, c.y] });
|
||||
assert_eq!(alt_click(&d), vec![Action::Exec("perspective.draw".into(), on_plane)]);
|
||||
// With no active plane, or the grid hidden, the flare is drawn flat.
|
||||
for g in [
|
||||
PerspectiveGrid { plane: Plane::None, ..PerspectiveGrid::current(&d) },
|
||||
PerspectiveGrid { visible: false, ..PerspectiveGrid::current(&d) },
|
||||
] {
|
||||
let mut d = d.clone();
|
||||
g.store(&mut d);
|
||||
assert_eq!(alt_click(&d), vec![Action::Exec("shape.flare".into(), params.clone())]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Equal vertical travel gives equal rotation, regardless of event partitioning.
|
||||
#[test]
|
||||
fn flare_drag_turns_the_rays_and_shift_holds_their_turn() {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The place cursor (`file.place.queue` loads it with files): a click places the current file at
|
||||
//! 100% with its top-left corner at the click, a drag places it at the dragged size (its aspect
|
||||
//! kept), ←/→ and ↑/↓ cycle the files and Esc discards the current one. Each placement is one
|
||||
//! `file.place`; after the last file the previous tool comes back.
|
||||
//! `file.place`, with `showImportOptions: true` for a Shift-click; after the last file the
|
||||
//! previous tool comes back.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
@@ -93,6 +94,10 @@ impl Tool for PlaceTool {
|
||||
let (Some(r), Some(e)) = (self.target(a, ev.pos, cx.tol(3.0)), self.entry()) else { return vec![] };
|
||||
let mut p = e.params.clone();
|
||||
p["rect"] = json!([r.x0, r.y0, r.width(), r.height()]);
|
||||
// A Shift-click (not a drag) asks for the file's import options before placing it.
|
||||
if ev.mods.shift && (ev.pos.x - a.x).abs().max((ev.pos.y - a.y).abs()) < cx.tol(3.0) {
|
||||
p["showImportOptions"] = json!(true);
|
||||
}
|
||||
let mut acts = vec![Action::Exec("file.place".into(), p)];
|
||||
acts.extend(self.discard());
|
||||
return acts;
|
||||
@@ -232,6 +237,33 @@ mod tests {
|
||||
assert!(!t.claims_key(&c, ToolKey::Escape), "an empty cursor takes no keys");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shift_click_asks_for_the_import_options_and_a_shift_drag_does_not() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Default::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let mut t = loaded(3);
|
||||
t.pointer(&c, &ev(PointerKind::Down, 10.0, 10.0).with_mods(shift));
|
||||
let acts = t.pointer(&c, &ev(PointerKind::Up, 11.0, 10.0).with_mods(shift));
|
||||
let asked = json!({"path": "f0.png", "rect": [10.0, 10.0, 40.0, 20.0], "showImportOptions": true});
|
||||
assert_eq!(acts, vec![Action::Exec("file.place".into(), asked)]);
|
||||
assert_eq!(t.options()["names"], json!(["f1.png", "f2.png"]), "the cursor goes on to the next file");
|
||||
// A Shift-drag places at the dragged size, as a drag does.
|
||||
t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0).with_mods(shift));
|
||||
t.pointer(&c, &ev(PointerKind::Drag, 20.0, 90.0).with_mods(shift));
|
||||
let acts = t.pointer(&c, &ev(PointerKind::Up, 20.0, 90.0).with_mods(shift));
|
||||
assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f1.png", "rect": [20.0, 60.0, 80.0, 40.0]})));
|
||||
// Shift released before the button: a plain click.
|
||||
t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift));
|
||||
let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0));
|
||||
assert_eq!(acts[0], Action::Exec("file.place".into(), json!({"path": "f2.png", "rect": [0.0, 0.0, 40.0, 20.0]})));
|
||||
assert_eq!(acts.last(), Some(&Action::SwitchTool("pen".into())));
|
||||
// An empty cursor places nothing on a Shift-click.
|
||||
t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0).with_mods(shift));
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0).with_mods(shift)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measurement_labels_gate_the_place_size_readout() {
|
||||
let (d, _) = doc_with_rect();
|
||||
|
||||
+111
-14
@@ -14,6 +14,14 @@
|
||||
//! release keeps the copies and the last shape as one undo step
|
||||
//! (<https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469>).
|
||||
//!
|
||||
//! With the Ellipse tool, three Shift-clicks draw the circle through the three points clicked
|
||||
//! (`shape.circleThroughPoints`). Once a point is placed, a Shift-click on the selection's handles
|
||||
//! or widgets places a point too. Escape, a click without Shift, a drag, a press without Shift on the
|
||||
//! selection or a shape widget, and an edit, Undo or Redo made outside the tool drop the points
|
||||
//! placed so far.
|
||||
//! While the perspective grid shows with an active plane, a Shift-click opens the size dialog, as a
|
||||
//! click does, and the shape goes on the plane.
|
||||
//!
|
||||
//! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle,
|
||||
//! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at
|
||||
//! once: a drag on a live rectangle's or polygon's corner widget rounds its corners and a drag on
|
||||
@@ -142,6 +150,26 @@ pub struct ShapeTool {
|
||||
/// While Backtick is held in a drag, the pointer position the next copy is measured from: where
|
||||
/// the last copy was left, or where the drag first had the key down.
|
||||
copy_from: Option<Point>,
|
||||
/// Ellipse tool: the points placed by Shift-clicks so far (fewer than three); the third
|
||||
/// Shift-click draws the circle through them ([`circle_through_points`]).
|
||||
through: Vec<Point>,
|
||||
/// Where the pointer was last seen while `through` holds points, for the circle's preview.
|
||||
hover: Option<Point>,
|
||||
/// The press in progress came with Shift held, with the Ellipse tool and no active perspective
|
||||
/// plane: a click places a point.
|
||||
places_point: bool,
|
||||
}
|
||||
|
||||
/// Whether the perspective grid shows with an active plane: shapes then go on the plane.
|
||||
fn perspective_plane_shown(cx: &ToolContext) -> bool {
|
||||
let g = crate::distort::perspective::PerspectiveGrid::current(cx.doc);
|
||||
g.visible && g.plane != crate::distort::perspective::Plane::None
|
||||
}
|
||||
|
||||
/// The command three Shift-clicks with the Ellipse tool run: the circle through their points.
|
||||
fn circle_through_points(points: &[Point]) -> (String, Value) {
|
||||
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
("shape.circleThroughPoints".into(), json!({ "points": pairs }))
|
||||
}
|
||||
|
||||
/// The options that keys and Ctrl/Cmd change while a shape is dragged out.
|
||||
@@ -195,11 +223,20 @@ impl ShapeTool {
|
||||
guides: vec![],
|
||||
measure: None,
|
||||
snapped: false,
|
||||
through: vec![],
|
||||
hover: None,
|
||||
places_point: false,
|
||||
copies: vec![],
|
||||
copy_from: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a press with `m` places another point for a circle: Shift with the Ellipse tool once
|
||||
/// a point is placed. Such a press skips the selection's handles and widgets.
|
||||
fn placing_point(&self, m: Mods) -> bool {
|
||||
self.id == "ellipse" && m.shift && !self.through.is_empty()
|
||||
}
|
||||
|
||||
/// With Backtick `held` at pointer `raw`, leave a copy of the shape the drag shows (`cmd` and
|
||||
/// `params`) once the pointer is [`COPY_SPACING`] screen points from the last copy, or from
|
||||
/// where the key was first held. A shape with no width, height or length, one the same as the
|
||||
@@ -644,24 +681,33 @@ impl Tool for ShapeTool {
|
||||
match ev.kind {
|
||||
PointerKind::Move => {
|
||||
// Over a widget a press would drag, no Smart Guide for a new shape's start.
|
||||
if self.over_widget(cx, ev.pos)
|
||||
|| self.over_handle(cx, ev.pos).is_some()
|
||||
|| self.over_center(cx, ev.pos)
|
||||
|| self.over_rotate(cx, ev.pos).is_some()
|
||||
if !self.placing_point(ev.mods)
|
||||
&& (self.over_widget(cx, ev.pos)
|
||||
|| self.over_handle(cx, ev.pos).is_some()
|
||||
|| self.over_center(cx, ev.pos)
|
||||
|| self.over_rotate(cx, ev.pos).is_some())
|
||||
{
|
||||
self.snap.clear();
|
||||
// A press there drags the widget or the selection, which drops the points.
|
||||
self.hover = None;
|
||||
} else {
|
||||
self.snap.hover(cx, ev.pos, &[], None);
|
||||
// The snapped point: the third Shift-click lands where the press snaps.
|
||||
let p = self.snap.hover(cx, ev.pos, &[], None);
|
||||
self.hover = (!self.through.is_empty()).then_some(p);
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
if self.press_widget(cx, ev) {
|
||||
self.snap.clear();
|
||||
return vec![];
|
||||
}
|
||||
if let Some(out) = self.press_selection(cx, ev) {
|
||||
return out;
|
||||
if !self.placing_point(ev.mods) {
|
||||
if self.press_widget(cx, ev) {
|
||||
self.snap.clear();
|
||||
self.through.clear();
|
||||
return vec![];
|
||||
}
|
||||
if let Some(out) = self.press_selection(cx, ev) {
|
||||
self.through.clear();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
let p = self.snap.press(cx, ev.pos, &[], None);
|
||||
if self.id == "lineSegment" {
|
||||
@@ -673,6 +719,7 @@ impl Tool for ShapeTool {
|
||||
self.start = Some(p);
|
||||
self.last = ev.pos;
|
||||
self.began = false;
|
||||
self.places_point = self.id == "ellipse" && ev.mods.shift && !perspective_plane_shown(cx);
|
||||
self.inner = None;
|
||||
self.before_drag = None;
|
||||
self.clear_copies();
|
||||
@@ -749,8 +796,20 @@ impl Tool for ShapeTool {
|
||||
self.clear_copies();
|
||||
if self.began {
|
||||
self.began = false;
|
||||
self.through.clear();
|
||||
vec![Action::Commit]
|
||||
} else if self.places_point {
|
||||
// A Shift-click places a point; the third draws the circle through the three.
|
||||
self.through.push(s);
|
||||
self.hover = None;
|
||||
if self.through.len() < 3 {
|
||||
return vec![];
|
||||
}
|
||||
let (c, v) = circle_through_points(&self.through);
|
||||
self.through.clear();
|
||||
vec![Action::Exec(c, v)]
|
||||
} else {
|
||||
self.through.clear();
|
||||
// Alt (draw from centre) is passed on, so the size dialog can centre the shape on the click.
|
||||
let args = if ev.mods.alt { json!({ "x": s.x, "y": s.y, "alt": true }) } else { json!({ "x": s.x, "y": s.y }) };
|
||||
vec![Action::Dialog(self.id.into(), args)]
|
||||
@@ -779,6 +838,17 @@ impl Tool for ShapeTool {
|
||||
_ => vec![],
|
||||
};
|
||||
}
|
||||
// Escape drops the points Shift-clicks placed for a circle; the document stays as it is. A
|
||||
// press that has not begun a drag is dropped too, so its release places no point.
|
||||
if key == ToolKey::Escape && !self.began && !self.through.is_empty() {
|
||||
self.through.clear();
|
||||
self.hover = None;
|
||||
if self.start.take().is_some() {
|
||||
self.places_point = false;
|
||||
self.snap.clear();
|
||||
}
|
||||
return vec![];
|
||||
}
|
||||
let Some(s) = self.start.filter(|_| self.began) else { return vec![] };
|
||||
let changed = match (self.id, key) {
|
||||
("polygon", ToolKey::Up) => {
|
||||
@@ -813,6 +883,7 @@ impl Tool for ShapeTool {
|
||||
} else if key == ToolKey::Escape {
|
||||
self.start = None;
|
||||
self.began = false;
|
||||
self.through.clear();
|
||||
self.inner = None;
|
||||
self.clear_copies();
|
||||
if let Some(o) = self.before_drag.take() {
|
||||
@@ -857,9 +928,23 @@ impl Tool for ShapeTool {
|
||||
match (&self.widget, &self.selection) {
|
||||
(Some(WidgetDrag::Corner(_)), _) => matches!(key, ToolKey::Up | ToolKey::Down),
|
||||
(_, Some(_)) => key == ToolKey::Escape,
|
||||
_ => false,
|
||||
_ => key == ToolKey::Escape && !self.through.is_empty(),
|
||||
}
|
||||
}
|
||||
/// Points placed by Shift-clicks for a circle: Escape drops them.
|
||||
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
|
||||
!self.through.is_empty()
|
||||
}
|
||||
/// The pointer left the canvas: the circle's preview through it goes.
|
||||
fn hover_ended(&mut self, _cx: &ToolContext) {
|
||||
self.hover = None;
|
||||
}
|
||||
/// An edit, Undo or Redo made outside the tool, or another document, drops the points placed
|
||||
/// for a circle.
|
||||
fn history_moved(&mut self) {
|
||||
self.through.clear();
|
||||
self.hover = None;
|
||||
}
|
||||
/// The widget being dragged, the Smart Guides of the shape being drawn or the selection being
|
||||
/// moved, and its size, angle or offset label.
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
@@ -872,6 +957,17 @@ impl Tool for ShapeTool {
|
||||
let tangent = self.tangent_line.line().filter(|_| self.start.is_some());
|
||||
let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() };
|
||||
o.extend(self.guides.iter().cloned());
|
||||
// The points Shift-clicks placed, and after two of them the circle through them and the
|
||||
// pointer, dashed.
|
||||
for p in &self.through {
|
||||
o.push(Overlay::Anchor { p: *p, color: crate::draw2::FEEDBACK, filled: true, size: 6.0 });
|
||||
}
|
||||
if let ([a, b], Some(h)) = (self.through.as_slice(), self.hover)
|
||||
&& let Some((c, r)) = vectorcraft_geom::shapes::circle_through(*a, *b, h)
|
||||
{
|
||||
let path = vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath();
|
||||
o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: true });
|
||||
}
|
||||
if let Some((p, text)) = &self.measure {
|
||||
o.push(Overlay::Measure { p: *p, text: text.clone() });
|
||||
}
|
||||
@@ -930,8 +1026,9 @@ impl Tool for ShapeTool {
|
||||
None => {}
|
||||
}
|
||||
// A press takes the corner and pie widgets first, then the box's handles, then the centre
|
||||
// point, then the zone just outside a corner; everywhere else it draws a new shape.
|
||||
if idle {
|
||||
// point, then the zone just outside a corner; everywhere else it draws a new shape. A
|
||||
// Shift-press that places another point for a circle skips them all.
|
||||
if idle && !self.placing_point(m) {
|
||||
if shows_shape_widgets(self.id) && corners::over_widget(cx, p, false) {
|
||||
return Cursor::CornerRadius;
|
||||
}
|
||||
|
||||
@@ -601,6 +601,212 @@ fn click_opens_dialog() {
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 10.0, 10.0)), vec![Action::Dialog("star".into(), json!({"x": 10.0, "y": 10.0}))]);
|
||||
}
|
||||
|
||||
/// With the Ellipse tool, the first two Shift-clicks place points (shown as marks, and with two
|
||||
/// placed, the circle through them and the pointer is previewed); the third runs the circle
|
||||
/// command through the three. A Shift-click with another shape tool still opens its dialog.
|
||||
#[test]
|
||||
fn three_shift_clicks_with_the_ellipse_tool_run_the_circle_through_them() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
let click = |t: &mut ShapeTool, x: f64, y: f64| {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift))
|
||||
};
|
||||
assert_eq!(click(&mut t, 10.0, 10.0), vec![]);
|
||||
assert_eq!(click(&mut t, 90.0, 10.0), vec![]);
|
||||
assert!(t.ends_on_escape(&cx) && t.claims_key(&cx, ToolKey::Escape));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 10.0, 70.0));
|
||||
let o = t.overlays(&cx);
|
||||
assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}");
|
||||
let preview = o.iter().find_map(|o| match o {
|
||||
Overlay::Path { path, dashed: true, .. } => Some(path.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let b = vectorcraft_geom::Shape::bounding_box(&preview.expect("the circle is previewed"));
|
||||
assert!(b.x0.abs() < 1e-9 && (b.y0 + 10.0).abs() < 1e-9 && (b.x1 - 100.0).abs() < 1e-9 && (b.y1 - 90.0).abs() < 1e-9, "{b:?}");
|
||||
assert_eq!(
|
||||
click(&mut t, 10.0, 70.0),
|
||||
vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": [[10.0, 10.0], [90.0, 10.0], [10.0, 70.0]]}))]
|
||||
);
|
||||
assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty());
|
||||
// Another shape tool keeps its dialog on a Shift-click.
|
||||
let mut r = ShapeTool::new("rectangle");
|
||||
assert_eq!(click(&mut r, 10.0, 10.0), vec![Action::Dialog("rectangle".into(), json!({"x": 10.0, "y": 10.0}))]);
|
||||
}
|
||||
|
||||
/// With Smart Guides on, the preview passes through the point the pointer snaps to, which is where
|
||||
/// the third Shift-click lands.
|
||||
#[test]
|
||||
fn the_circle_preview_passes_through_the_snapped_pointer() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
for (x, y) in [(300.0, 0.0), (300.0, 200.0)] {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift));
|
||||
}
|
||||
// Near the rectangle's corner anchor at (100, 100): the circle through (300, 0), (300, 200)
|
||||
// and (100, 100) has its center at (225, 100) and radius 125.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 98.0, 102.0));
|
||||
let preview = t.overlays(&cx).into_iter().find_map(|o| match o {
|
||||
Overlay::Path { path, dashed: true, .. } => Some(path),
|
||||
_ => None,
|
||||
});
|
||||
let b = vectorcraft_geom::Shape::bounding_box(&preview.expect("the circle is previewed"));
|
||||
let want = [100.0, -25.0, 350.0, 225.0];
|
||||
assert!([b.x0, b.y0, b.x1, b.y1].iter().zip(want).all(|(a, w)| (a - w).abs() < 1e-9), "{b:?}");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 98.0, 102.0).with_mods(shift));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 98.0, 102.0).with_mods(shift));
|
||||
assert!(matches!(&a[..], [Action::Exec(_, v)] if v["points"][2] == json!([100.0, 100.0])), "{a:?}");
|
||||
}
|
||||
|
||||
/// Escape, a plain click and a drag drop the points Shift-clicks placed, so the next Shift-click
|
||||
/// starts a new circle.
|
||||
#[test]
|
||||
fn escape_a_click_or_a_drag_drops_the_shift_clicked_points() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
let shift_click = |t: &mut ShapeTool, x: f64, y: f64| {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift))
|
||||
};
|
||||
shift_click(&mut t, 10.0, 10.0);
|
||||
shift_click(&mut t, 90.0, 10.0);
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![]);
|
||||
assert!(!t.ends_on_escape(&cx));
|
||||
shift_click(&mut t, 10.0, 10.0);
|
||||
shift_click(&mut t, 90.0, 10.0);
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0));
|
||||
assert_eq!(
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 50.0, 50.0)),
|
||||
vec![Action::Dialog("ellipse".into(), json!({"x": 50.0, "y": 50.0}))]
|
||||
);
|
||||
assert!(!t.ends_on_escape(&cx), "a plain click drops them");
|
||||
shift_click(&mut t, 10.0, 10.0);
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 50.0).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 90.0, 90.0).with_mods(shift));
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 90.0, 90.0).with_mods(shift)), vec![Action::Commit]);
|
||||
assert!(!t.ends_on_escape(&cx), "a Shift-drag draws a circle and drops them");
|
||||
// A move of the selection by its centre point drops them too.
|
||||
let (d, s) = unfilled_live_rect();
|
||||
let c = ToolContext { smart_guides: false, ..crate::testutil::cx(&d, &s, &p) };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
for (x, y) in [(10.0, 10.0), (90.0, 10.0)] {
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift));
|
||||
}
|
||||
assert!(t.ends_on_escape(&c));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 160.0));
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 160.0)), vec![Action::Commit]);
|
||||
assert!(!t.ends_on_escape(&c), "a move of the selection drops them");
|
||||
}
|
||||
|
||||
/// Escape pressed while the third Shift-click is held drops the points and the press, so the
|
||||
/// release draws no circle.
|
||||
#[test]
|
||||
fn escape_during_the_third_shift_click_drops_the_points_and_the_press() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
for (x, y) in [(10.0, 10.0), (90.0, 10.0)] {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift));
|
||||
}
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 70.0).with_mods(shift));
|
||||
assert!(t.claims_key(&cx, ToolKey::Escape));
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, shift), vec![]);
|
||||
assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty());
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 10.0, 70.0).with_mods(shift)), vec![]);
|
||||
assert!(!t.ends_on_escape(&cx), "the release places no point");
|
||||
}
|
||||
|
||||
/// Once a point is placed, a Shift-click on the selection's side handle or centre point places a
|
||||
/// point instead of scaling or moving the selection, and the cursor over them is the crosshair.
|
||||
#[test]
|
||||
fn shift_clicks_on_the_selection_place_points_once_one_is_placed() {
|
||||
let (d, s) = unfilled_live_rect();
|
||||
let p = paint();
|
||||
let c = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
let centre = Point::new(150.0, 150.0);
|
||||
assert_eq!(t.cursor(&c, centre, shift), Cursor::Move, "no point placed yet: the centre point moves");
|
||||
let click = |t: &mut ShapeTool, x: f64, y: f64| {
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift))
|
||||
};
|
||||
assert_eq!(click(&mut t, 10.0, 10.0), vec![]);
|
||||
assert_eq!(t.cursor(&c, centre, shift), Cursor::Crosshair);
|
||||
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move, "without Shift a press still moves the selection");
|
||||
assert_eq!(click(&mut t, 100.0, 150.0), vec![], "the left side handle");
|
||||
assert!(!t.busy());
|
||||
assert_eq!(
|
||||
click(&mut t, centre.x, centre.y),
|
||||
vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": [[10.0, 10.0], [100.0, 150.0], [150.0, 150.0]]}))]
|
||||
);
|
||||
}
|
||||
|
||||
/// The pointer leaving the canvas removes the circle's preview, and an edit, Undo or Redo made
|
||||
/// outside the tool drops the points placed so far.
|
||||
#[test]
|
||||
fn leaving_the_canvas_or_an_outside_edit_clears_the_circle_in_progress() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
let click = |t: &mut ShapeTool, x: f64, y: f64| {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift))
|
||||
};
|
||||
let dashed = |t: &ShapeTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { dashed: true, .. }));
|
||||
click(&mut t, 10.0, 10.0);
|
||||
click(&mut t, 90.0, 10.0);
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 10.0, 70.0));
|
||||
assert!(dashed(&t));
|
||||
t.hover_ended(&cx);
|
||||
assert!(!dashed(&t), "no preview through a pointer off the canvas");
|
||||
assert!(t.ends_on_escape(&cx), "the points stay");
|
||||
t.history_moved();
|
||||
assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty());
|
||||
assert_eq!(click(&mut t, 10.0, 70.0), vec![], "the next Shift-click starts a new circle");
|
||||
}
|
||||
|
||||
/// While the perspective grid shows with an active plane, a Shift-click with the Ellipse tool opens
|
||||
/// the size dialog, whose shape goes on the plane, as before.
|
||||
#[test]
|
||||
fn a_shift_click_on_an_active_perspective_plane_opens_the_dialog() {
|
||||
let (mut d, _) = doc_with_rect();
|
||||
crate::distort::perspective::PerspectiveGrid::preset(2, Rect::new(0.0, 0.0, 612.0, 792.0)).store(&mut d);
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = ShapeTool::new("ellipse");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0).with_mods(shift));
|
||||
assert_eq!(
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 10.0, 10.0).with_mods(shift)),
|
||||
vec![Action::Dialog("ellipse".into(), json!({"x": 10.0, "y": 10.0}))]
|
||||
);
|
||||
assert!(!t.ends_on_escape(&cx));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_click_passes_draw_from_centre_to_the_dialog() {
|
||||
let (d, _) = doc_with_rect();
|
||||
|
||||
@@ -974,10 +974,12 @@ fn black_gray_white(gray: [u8; 3]) -> TraceParams {
|
||||
|
||||
/// A black disc and a gray square on white, blurred by 1 to 3 pixels: the edge pixels around the
|
||||
/// disc as light as the gray read as blends of black and white, so the gray is one shape (the
|
||||
/// square) and no gray lines the disc, with the colors found or named. At a blur of 3 pixels, with
|
||||
/// the colors named, a gray of 128 is still one shape, a gray of 200 leaves 4 slivers of no area,
|
||||
/// and a light gray (230) leaves at most 8 slivers, touching the disc's edge at no more than 4 of
|
||||
/// 192 samples. (Without named colors, an image blurred by 3 pixels traces without its gray.)
|
||||
/// square) and no gray lines the disc, with the colors found or named. A light gray (230) blurred by
|
||||
/// 1.5 pixels leaves at most 4 slivers of up to 3 pixels, touching the disc's edge at no more than 4
|
||||
/// of 192 samples. At a blur of 3 pixels, with the colors named, a gray of 128 is still one shape, a
|
||||
/// gray of 200 leaves 4 slivers of no area, and a light gray leaves at most 8 slivers, touching the
|
||||
/// disc's edge at no more than 4 of 192 samples. (Without named colors, an image blurred by 3 pixels
|
||||
/// traces without its gray.)
|
||||
#[test]
|
||||
fn blurred_black_edges_beside_gray_leave_no_gray_slivers() {
|
||||
const INK: [u8; 3] = [4, 4, 3];
|
||||
@@ -1013,6 +1015,10 @@ fn blurred_black_edges_beside_gray_leave_no_gray_slivers() {
|
||||
grays.sort_unstable();
|
||||
grays.pop();
|
||||
match (gray[0], blur == 3.0) {
|
||||
(230, false) if blur == 1.5 => {
|
||||
assert!(grays.len() <= 4 && grays.iter().all(|&n| n <= 3), "{what}: slivers {grays:?}");
|
||||
assert!(rim <= 4, "{what}: {rim} of 192 samples along the disc's edge traced gray");
|
||||
}
|
||||
(230, true) => {
|
||||
assert!(grays.len() <= 8, "{what}: {} slivers; {paths:?}", grays.len());
|
||||
assert!(rim <= 4, "{what}: {rim} of 192 samples along the disc's edge traced gray");
|
||||
@@ -1031,15 +1037,26 @@ fn blurred_black_edges_beside_gray_leave_no_gray_slivers() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A soft-edged gray band 2 to 4 pixels wide lying along a black disc, blurred by 1.5 or 2 pixels,
|
||||
/// traces as black and white: its pixels are reached from the disc and from the white through
|
||||
/// pixels that keep getting darker and lighter, as across a blurred black-to-white edge. A band 8
|
||||
/// pixels wide keeps at least half of its gray. With sharp edges every band stays gray.
|
||||
/// A soft-edged gray band lying along a black disc traces as black and white, with at most one of
|
||||
/// every 16 samples traced gray, when it is 2 to 4 pixels wide and blurred by 1.5 or 2 pixels, 2 or
|
||||
/// 3 pixels wide and blurred by 3 pixels, or 2 pixels wide and blurred by 1 pixel: its pixels are
|
||||
/// reached from the disc and from the white through pixels that keep getting darker and lighter, as
|
||||
/// across a blurred black-to-white edge. A band 8 pixels wide keeps at least half of its gray at
|
||||
/// blurs of 1 to 3 pixels. The bands 3 and 4 pixels wide of the three grays, blurred by 1 pixel,
|
||||
/// keep about 60 of their 336 samples gray, and those 4 pixels wide, blurred by 3 pixels, about 39
|
||||
/// of 192. With sharp edges every band stays gray, and with edges blurred by 0.6 pixels a band 3 to
|
||||
/// 8 pixels wide keeps at least 4 of every 5 samples gray, and the bands 2 to 4 pixels wide of the
|
||||
/// three grays keep about 306 of their 432 samples gray: beside a sharp edge, a path that comes to a
|
||||
/// pixel of the gray stops there.
|
||||
#[test]
|
||||
fn a_soft_gray_band_along_black_traces_as_black_and_white() {
|
||||
const INK: [u8; 3] = [4, 4, 3];
|
||||
// The samples traced gray over the three grays: of the bands 2 to 4 pixels wide blurred by 0.6
|
||||
// pixels, of the bands 3 and 4 pixels wide blurred by 1 pixel, and of the bands 4 pixels wide
|
||||
// blurred by 3 pixels.
|
||||
let (mut nearly_sharp, mut blur_one, mut blur_three) = (0, 0, 0);
|
||||
for gray in [[230u8, 230, 230], [200, 200, 200], [128, 128, 128]] {
|
||||
for blur in [0.0, 1.5, 2.0] {
|
||||
for blur in [0.0, 0.6, 1.0, 1.5, 2.0, 3.0] {
|
||||
for wide in [2u8, 3, 4, 8] {
|
||||
let img = render(120, 60, blur, |x, y| {
|
||||
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
|
||||
@@ -1058,25 +1075,48 @@ fn a_soft_gray_band_along_black_traces_as_black_and_white() {
|
||||
.count();
|
||||
let all = 16 * usize::from(wide);
|
||||
let what = format!("gray {}, blur {blur}, {wide} px band: {kept} of {all} samples traced gray", gray[0]);
|
||||
let lost = if blur == 1.0 {
|
||||
wide <= 2
|
||||
} else if blur == 3.0 {
|
||||
wide <= 3
|
||||
} else {
|
||||
wide <= 4
|
||||
};
|
||||
if blur == 0.0 {
|
||||
assert_eq!(kept, all, "{what}");
|
||||
} else if wide <= 4 {
|
||||
assert_eq!(kept, 0, "{what}");
|
||||
} else {
|
||||
} else if blur == 0.6 {
|
||||
if wide >= 3 {
|
||||
assert!(5 * kept >= 4 * all, "{what}");
|
||||
}
|
||||
if wide <= 4 {
|
||||
nearly_sharp += kept;
|
||||
}
|
||||
} else if lost {
|
||||
assert!(16 * kept <= all, "{what}");
|
||||
} else if wide == 8 {
|
||||
assert!(2 * kept >= all, "{what}");
|
||||
} else if blur == 1.0 {
|
||||
blur_one += kept;
|
||||
} else if blur == 3.0 {
|
||||
blur_three += kept;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!((300..=312).contains(&nearly_sharp), "bands 2 to 4 px wide blurred by 0.6 px: {nearly_sharp} of 432 samples traced gray");
|
||||
assert!((56..=64).contains(&blur_one), "bands 3 and 4 px wide blurred by 1 px: {blur_one} of 336 samples traced gray");
|
||||
assert!((36..=42).contains(&blur_three), "bands 4 px wide blurred by 3 px: {blur_three} of 192 samples traced gray");
|
||||
}
|
||||
|
||||
/// A soft-edged gray spoke two or three pixels wide running straight out of a black disc, blurred
|
||||
/// by 1 or 1.5 pixels, loses 3 or 4 of its 16 samples nearest the disc and keeps the rest.
|
||||
/// by 1 or 1.5 pixels, loses 3 or 4 of its 16 samples nearest the disc and keeps the rest. Blurred
|
||||
/// by 2 pixels, a spoke three pixels wide loses 2 or 3 of them, and one two pixels wide traces as
|
||||
/// black and white along its whole length.
|
||||
#[test]
|
||||
fn a_soft_gray_spoke_loses_a_few_pixels_where_it_meets_black() {
|
||||
const INK: [u8; 3] = [4, 4, 3];
|
||||
for gray in [[230u8, 230, 230], [128, 128, 128]] {
|
||||
for blur in [1.0, 1.5] {
|
||||
for blur in [1.0, 1.5, 2.0] {
|
||||
for wide in [2.0, 3.0] {
|
||||
let img = render(120, 60, blur, |x, y| {
|
||||
Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 {
|
||||
@@ -1092,7 +1132,12 @@ fn a_soft_gray_spoke_loses_a_few_pixels_where_it_meets_black() {
|
||||
let near = (44..60).filter(|&x| top_color(&res, at(x)) == Some(gray)).count();
|
||||
let far = (60..86).filter(|&x| top_color(&res, at(x)) == Some(gray)).count();
|
||||
let what = format!("gray {}, blur {blur}, {wide} px spoke", gray[0]);
|
||||
assert!((12..=13).contains(&near), "{what}: {near} of the 16 samples nearest the disc traced gray");
|
||||
if blur == 2.0 && wide == 2.0 {
|
||||
assert_eq!(near + far, 0, "{what}: {near} and {far} samples traced gray");
|
||||
continue;
|
||||
}
|
||||
let kept = if blur == 2.0 { 13..=14 } else { 12..=13 };
|
||||
assert!(kept.contains(&near), "{what}: {near} of the 16 samples nearest the disc traced gray");
|
||||
assert_eq!(far, 26, "{what}: the rest of the spoke");
|
||||
}
|
||||
}
|
||||
@@ -1100,8 +1145,8 @@ fn a_soft_gray_spoke_loses_a_few_pixels_where_it_meets_black() {
|
||||
}
|
||||
|
||||
/// A soft-edged light gray stroke 2 pixels wide beside a black disc, blurred by 1.5 pixels: 2
|
||||
/// pixels from the disc it keeps less than half of its gray, 4 pixels away it loses a few pixels,
|
||||
/// and 6 or 8 pixels away it keeps all of it.
|
||||
/// pixels from the disc it keeps about 10 of its 34 samples gray, 4 pixels away about 25, and 6 or
|
||||
/// 8 pixels away all of them.
|
||||
#[test]
|
||||
fn a_soft_gray_stroke_near_black_loses_gray_by_its_distance() {
|
||||
const INK: [u8; 3] = [4, 4, 3];
|
||||
@@ -1121,8 +1166,8 @@ fn a_soft_gray_stroke_near_black_loses_gray_by_its_distance() {
|
||||
let kept = (12..46).filter(|&y| top_color(&res, Point::new(x0 + 1.0, f64::from(y) + 0.5)) == Some(GRAY)).count();
|
||||
let what = format!("{gap} px from the disc: {kept} of 34 samples traced gray");
|
||||
match gap {
|
||||
2 => assert!(2 * kept < 34, "{what}"),
|
||||
4 => assert!((24..34).contains(&kept), "{what}"),
|
||||
2 => assert!((7..=13).contains(&kept), "{what}"),
|
||||
4 => assert!((22..=28).contains(&kept), "{what}"),
|
||||
_ => assert_eq!(kept, 34, "{what}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,17 +256,23 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4]
|
||||
/// a class of `best` that `other` leaves out. For a class left out that lies between the classes of
|
||||
/// `other` on the line between them, a path of pixels from `i` that keeps going toward one class of
|
||||
/// `other` gets past the class left out within [`WALK`] steps through the eight neighbors, and so
|
||||
/// does one that keeps going toward the other. For a class left out that lies beyond both classes of
|
||||
/// `other` on that line, the pixel has a neighbor on each side of that class, or a neighbor on each
|
||||
/// side of the pixel itself, none past the class of `other` nearer the class left out, and a chain
|
||||
/// of neighbors from the pixel to that nearer class or a flat area of it (`flat`), each nearer it
|
||||
/// than the one before. (A black-to-white edge pixel as light as a gray has a darker neighbor and a
|
||||
/// lighter one, or, on an edge blurred over several pixels, reaches darker and lighter pixels through
|
||||
/// pixels that keep getting darker or lighter; from a gray stroke on white, a path that keeps getting
|
||||
/// darker ends in the stroke, at the gray; a gray-to-black edge pixel has a lighter neighbor and a
|
||||
/// darker one, and lighter pixels lead to the flat gray; a pale line one pixel wide on black has only
|
||||
/// darker neighbors; the pixels beside a blurred pale line's middle reach no flat gray; and a white
|
||||
/// gap between black and gray has a neighbor lighter than the gray.)
|
||||
/// does one that keeps going toward the other. When the first step of one path comes to a pixel
|
||||
/// that stands for its class of `other` (the edge on that side is sharp), the other path stops at
|
||||
/// a pixel within [`PURE`] of the class left out that it comes to before it gets past that class.
|
||||
/// For a class left out that lies beyond both classes of `other` on that line, the pixel has a
|
||||
/// neighbor on each side of that class, or a neighbor on each side of the pixel itself, none past
|
||||
/// the class of `other` nearer the class left out, and a chain of neighbors from the pixel to that
|
||||
/// nearer class or a flat area of it (`flat`), each nearer it than the one before.
|
||||
///
|
||||
/// (A black-to-white edge pixel as light as a gray has a darker neighbor and a lighter one, or, on
|
||||
/// an edge blurred over several pixels, reaches darker and lighter pixels through pixels that keep
|
||||
/// getting darker or lighter; from a gray stroke on white, a path that keeps getting darker ends in
|
||||
/// the stroke, at the gray; from the outer pixels of a gray band along black, with nearly sharp
|
||||
/// edges, the first step outward is white and the path toward black comes to the band's gray; a
|
||||
/// gray-to-black edge pixel has a lighter neighbor and a darker one, and lighter pixels lead to the
|
||||
/// flat gray; a pale line one pixel wide on black has only darker neighbors; the pixels beside a
|
||||
/// blurred pale line's middle reach no flat gray; and a white gap between black and gray has a
|
||||
/// neighbor lighter than the gray.)
|
||||
///
|
||||
/// When it does, the number of steps the longer of the two paths takes to a pixel that stands for its
|
||||
/// class of `other` (`stands_for`), the largest over the classes left out. It is `NEARBY + 1` when a
|
||||
@@ -350,26 +356,40 @@ fn across_edge(
|
||||
}
|
||||
false
|
||||
};
|
||||
// A path from `i` toward `a` (`toward` -1) or `b` (`toward` 1): each step goes to the neighbor
|
||||
// near the line that lies farthest that way, while it lies farther than the pixel before (the
|
||||
// first step is taken whatever `i` itself is). `None` when it does not get more than `PURE` past
|
||||
// `tc` in [`WALK`] steps; otherwise the steps to the first pixel past it that stands for `class`
|
||||
// (`stands_for`), or `NEARBY + 1`.
|
||||
let walk = |toward: f64, tc: f64, class: usize| {
|
||||
// Whether pixel `j` comes within `PURE` of class `c`.
|
||||
let within = |j: usize, c: usize| {
|
||||
let (Some(q), Some(cv)) = (pix.get(j), classes.get(c)) else { return false };
|
||||
(0..4).map(|k| (f64::from(q[k]) - cv[k]).powi(2)).sum::<f64>().sqrt() < PURE
|
||||
};
|
||||
// The neighbor of pixel `j` near the line that lies farthest toward `a` (`toward` -1) or `b`
|
||||
// (`toward` 1), with its place.
|
||||
let next = |j: usize, toward: f64| around(j).filter_map(|n| at(n).map(|tn| (n, tn))).max_by(|p, q| (p.1 * toward).total_cmp(&(q.1 * toward)));
|
||||
// A path from `i` toward `a` or `b`: each step goes to [`next`], while it lies farther than the
|
||||
// pixel before (the first step is taken whatever `i` itself is). `None` when it does not get more
|
||||
// than `PURE` past `tc` in [`WALK`] steps; otherwise the steps to the first pixel past it that
|
||||
// stands for `class` (`stands_for`), or `NEARBY + 1`. With `halt`, the path also ends at a pixel
|
||||
// within `PURE` of that class that it comes to before it gets past `tc`.
|
||||
let walk = |toward: f64, tc: f64, class: usize, halt: Option<usize>| {
|
||||
let (mut cur, mut t) = (i, f64::NEG_INFINITY * toward);
|
||||
let mut past = false;
|
||||
for step in 1..=WALK {
|
||||
match around(cur).filter_map(|j| at(j).map(|tj| (j, tj))).max_by(|p, q| (p.1 * toward).total_cmp(&(q.1 * toward))) {
|
||||
match next(cur, toward) {
|
||||
Some((j, tj)) if (tj - t) * toward > 0.0 => (cur, t) = (j, tj),
|
||||
_ => break,
|
||||
}
|
||||
past = past || (t - tc) * toward * len > PURE;
|
||||
if !past && halt.is_some_and(|h| within(cur, h)) {
|
||||
break;
|
||||
}
|
||||
if past && stands_for.get(cur).copied().flatten() == Some(class) {
|
||||
return Some(step);
|
||||
}
|
||||
}
|
||||
past.then_some(NEARBY + 1)
|
||||
};
|
||||
// Whether the first step of a path toward `class` (`toward` as in [`walk`]) comes to a pixel that
|
||||
// stands for it: the edge on that side is sharp.
|
||||
let sharp = |toward: f64, class: usize| next(i, toward).is_some_and(|(j, _)| stands_for.get(j).copied().flatten() == Some(class));
|
||||
if left_out.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -377,8 +397,9 @@ fn across_edge(
|
||||
for &c in &left_out {
|
||||
let (tc, _) = place(*classes.get(c)?);
|
||||
if (0.0..=1.0).contains(&tc) {
|
||||
let ra = walk(-1.0, tc, *a)?;
|
||||
let rb = walk(1.0, tc, *b)?;
|
||||
// When one side's edge is sharp, the other side's path stops at a pixel of the class left out.
|
||||
let ra = walk(-1.0, tc, *a, sharp(1.0, *b).then_some(c))?;
|
||||
let rb = walk(1.0, tc, *b, sharp(-1.0, *a).then_some(c))?;
|
||||
reach = reach.max(ra.max(rb));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -89,6 +89,7 @@ impl VectorcraftApp {
|
||||
selection_box: None,
|
||||
selection_bounds: None,
|
||||
content_bounds: None,
|
||||
pixel_aligned: None,
|
||||
plugin_keys: Default::default(),
|
||||
placed_keys: Default::default(),
|
||||
cursors: Default::default(),
|
||||
|
||||
@@ -61,6 +61,9 @@ pub struct CanvasCache {
|
||||
pub selection_bounds: Option<((u64, u64), Option<vectorcraft_geom::Rect>)>,
|
||||
/// [`VectorcraftApp::content_bounds`] for (document uid, revision).
|
||||
pub content_bounds: Option<((u64, u64), Option<vectorcraft_geom::Rect>)>,
|
||||
/// The Transform panel's Align to Pixel Grid state (on, off or mixed, and whether every
|
||||
/// selected object can be aligned) for (document uid, revision).
|
||||
pub pixel_aligned: Option<((u64, u64), Option<PixelAligned>)>,
|
||||
/// [`CacheKey::plugins`] by document uid, with the plug-in revision
|
||||
/// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at.
|
||||
pub plugin_keys: std::collections::HashMap<u64, (u64, u64)>,
|
||||
@@ -108,6 +111,10 @@ pub type SliceCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_doc::SliceArea
|
||||
/// uid, revision).
|
||||
pub type LivePaintGapsCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_tools::Overlay>>);
|
||||
|
||||
/// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they
|
||||
/// agree and `None` when they differ, with whether every one can be aligned.
|
||||
pub type PixelAligned = (Option<bool>, bool);
|
||||
|
||||
/// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision).
|
||||
pub type PrintTilingCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_pdf::TilingPage>>);
|
||||
|
||||
|
||||
@@ -423,6 +423,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, view_info);
|
||||
draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs), &mut shared_paths);
|
||||
app.canvas.shared_paths = shared_paths;
|
||||
crate::panels::tabs::paint_stop_guide(app, &painter, &xf);
|
||||
if !revolve_edit {
|
||||
shaper_widget_overlay(app, &painter, &xf);
|
||||
crate::panels::three_d::paint_graphic_handles(app, &painter, &xf);
|
||||
|
||||
@@ -36,6 +36,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let target = fields["target"].clone();
|
||||
let Some(o) = fields.as_object_mut() else { return Err("no blend options".into()) };
|
||||
o.retain(|k, _| matches!(k.as_str(), "spacing" | "steps" | "distance" | "orientation"));
|
||||
let opened = Value::Object(o.clone());
|
||||
o.insert("__opened".into(), opened);
|
||||
o.insert("__target".into(), target);
|
||||
o.insert("preview".into(), json!(true));
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
@@ -47,13 +49,33 @@ fn on_blend(d: &Dialog) -> bool {
|
||||
d.str("__target") == "blend"
|
||||
}
|
||||
|
||||
/// `object.blend.options` parameters from the fields.
|
||||
/// The field set when the spacing or its count is picked or typed in the dialog: OK then applies
|
||||
/// it to every selected blend, even when it matches the first blend's.
|
||||
const SET_SPACING: &str = "__setSpacing";
|
||||
|
||||
/// The field set when an orientation button is clicked, as [`SET_SPACING`] for the orientation.
|
||||
const SET_ORIENTATION: &str = "__setOrientation";
|
||||
|
||||
/// `object.blend.options` parameters from the fields set in the dialog or differing from the
|
||||
/// values it opened with, so each selected blend keeps its own values for the rest.
|
||||
fn params(d: &Dialog) -> Value {
|
||||
let mut p = json!({"spacing": d.str("spacing"), "orientation": d.str("orientation")});
|
||||
match d.str("spacing").as_str() {
|
||||
"steps" => p["steps"] = json!(d.f64("steps", 5.0).round().clamp(1.0, 1000.0)),
|
||||
"distance" => p["distance"] = json!(d.f64("distance", 10.0)),
|
||||
_ => {}
|
||||
let opened = |k: &str| d.fields.get("__opened").and_then(|o| o.get(k)).cloned().unwrap_or(Value::Null);
|
||||
let mode = d.str("spacing");
|
||||
let count = match mode.as_str() {
|
||||
"steps" => Some(("steps", d.f64("steps", 5.0).round().clamp(1.0, 1000.0))),
|
||||
"distance" => Some(("distance", d.f64("distance", 10.0))),
|
||||
_ => None,
|
||||
};
|
||||
let mut p = json!({});
|
||||
if d.bool(SET_SPACING) || opened("spacing") != json!(mode) || count.is_some_and(|(k, v)| opened(k).as_f64() != Some(v)) {
|
||||
p["spacing"] = json!(mode);
|
||||
if let Some((k, v)) = count {
|
||||
p[k] = json!(v);
|
||||
}
|
||||
}
|
||||
let orientation = d.str("orientation");
|
||||
if d.bool(SET_ORIENTATION) || opened("orientation") != json!(orientation) {
|
||||
p["orientation"] = json!(orientation);
|
||||
}
|
||||
p
|
||||
}
|
||||
@@ -66,11 +88,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| {
|
||||
if let Some((value, _)) = widgets::dropdown(ui, "blend-spacing", shown, &labels, 150.0).and_then(|i| SPACING.get(i)) {
|
||||
d.fields.insert("spacing".into(), json!(value));
|
||||
d.fields.insert(SET_SPACING.into(), json!(true));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
match mode.as_str() {
|
||||
"distance" => {
|
||||
form::length(ui, d, "distance", unit, 72.0);
|
||||
if form::length(ui, d, "distance", unit, 72.0) {
|
||||
d.fields.insert(SET_SPACING.into(), json!(true));
|
||||
}
|
||||
}
|
||||
// Smooth Color picks the count itself: the field shows the steps, disabled.
|
||||
m => {
|
||||
@@ -78,6 +103,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.add_enabled_ui(m == "steps", |ui| {
|
||||
if let Some(n) = widgets::range_field(ui, "blend-steps", steps, 1.0..=1000.0, "", 0, 72.0) {
|
||||
d.fields.insert("steps".into(), json!(n));
|
||||
d.fields.insert(SET_SPACING.into(), json!(true));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -89,6 +115,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
for (value, along, tip) in [("page", false, tl!("Align to Page")), ("path", true, tl!("Align to Path"))] {
|
||||
if orientation_button(ui, along, path == along, tip) {
|
||||
d.fields.insert("orientation".into(), json!(value));
|
||||
d.fields.insert(SET_ORIENTATION.into(), json!(true));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -193,6 +220,52 @@ mod tests {
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_several_blends_ok_sets_only_the_fields_changed() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let blend = |app: &mut VectorcraftApp, y: f64, options: Value| {
|
||||
let ids: Vec<Value> =
|
||||
[0.0, 200.0].map(|x| app.run("shape.rectangle", json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].clone()).into();
|
||||
app.run("select.set", json!({ "ids": ids })).unwrap();
|
||||
app.run("object.blend.make", options).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let a = blend(&mut app, 0.0, json!({"spacing": "steps", "steps": 3}));
|
||||
let b = blend(&mut app, 100.0, json!({"spacing": "distance", "distance": 12, "orientation": "path"}));
|
||||
let both = |app: &VectorcraftApp| {
|
||||
let (sa, sb) = (spec(app, a), spec(app, b));
|
||||
((sa.spacing, sa.orientation), (sb.spacing, sb.orientation))
|
||||
};
|
||||
app.run("select.set", json!({"ids": [a, b]})).unwrap();
|
||||
// The dialog shows the first blend's options; changing only the orientation leaves each
|
||||
// blend's spacing as it was.
|
||||
app.run("ui.blendOptions", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("orientation".into(), json!("path"));
|
||||
frame(&mut app);
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
let path = BlendOrientation::AlignToPath;
|
||||
assert_eq!(both(&app), ((BlendSpacing::Steps(3), path), (BlendSpacing::Distance(12.0), path)));
|
||||
// Changing only the step count gives both blends that count and keeps their orientation.
|
||||
app.run("object.blend.options", json!({"id": b, "orientation": "page"})).unwrap();
|
||||
app.run("ui.blendOptions", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("steps".into(), json!(8));
|
||||
frame(&mut app);
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(both(&app), ((BlendSpacing::Steps(8), path), (BlendSpacing::Steps(8), BlendOrientation::AlignToPage)));
|
||||
// Clicking the orientation the first blend already has applies it to every selected blend.
|
||||
app.run("ui.blendOptions", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert(SET_ORIENTATION.into(), json!(true));
|
||||
frame(&mut app);
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(both(&app), ((BlendSpacing::Steps(8), path), (BlendSpacing::Steps(8), path)));
|
||||
// OK without changes changes nothing and records no undo step.
|
||||
let depth = app.session.doc().unwrap().history.undo.len();
|
||||
app.run("ui.blendOptions", json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), depth);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_nothing_selected_it_sets_what_new_blends_start_with() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
heading: |d| tl!(&d.str("__label")).to_string(),
|
||||
heading: heading_label,
|
||||
body: |app, ui, d| {
|
||||
let command = d.str("__command");
|
||||
let (lengths, order) = (lengths(&command), order(&command));
|
||||
@@ -62,6 +62,23 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
|
||||
/// The dialog's heading (`__label`, English) in the UI language.
|
||||
fn heading_label(d: &Dialog) -> String {
|
||||
heading_in(crate::i18n::current(), &d.str("__label"))
|
||||
}
|
||||
|
||||
/// `label` as a heading in `lang`. A menu item opens the dialog with its label less the "…", so
|
||||
/// the menu item's row (the label with "…") is looked up first, without its "…", and then the
|
||||
/// plain row, as the effect dialog's heading is (`effect.rs`, `heading_label`).
|
||||
fn heading_in(lang: crate::i18n::Lang, label: &str) -> String {
|
||||
use crate::i18n::{has, tr};
|
||||
let dotted = format!("{label}…");
|
||||
if has(lang, &dotted) {
|
||||
return tr(lang, &dotted).trim_end_matches('…').trim_end().to_string();
|
||||
}
|
||||
tr(lang, label).to_string()
|
||||
}
|
||||
|
||||
/// Does this dialog show a Preview checkbox? Grid Repeat Options does: the public page for the
|
||||
/// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does
|
||||
/// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path
|
||||
@@ -391,6 +408,42 @@ mod tests {
|
||||
assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}");
|
||||
}
|
||||
|
||||
/// Object › Path › Clean Up… opens this dialog headed "Clean Up", which most catalogs hold only
|
||||
/// as the menu label "Clean Up…" (#7991). In French the heading and every option are translated.
|
||||
#[test]
|
||||
fn clean_up_dialog_is_drawn_in_the_ui_language() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let entries = crate::menus::menu_entries(&app);
|
||||
let item = entries.iter().find(|e| e.path == ["Object", "Path"] && e.label == "Clean Up…").expect("listed");
|
||||
let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
|
||||
crate::menus::invoke(&mut app, &cmd, p);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("__label"), "Clean Up");
|
||||
crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap());
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
let heading = heading_label(app.ui.dialog.as_ref().unwrap());
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
assert_eq!(heading, "Nettoyer");
|
||||
for s in ["Nettoyer", "Points isolés", "Objets sans fond ni contour", "Tracés de texte vides"] {
|
||||
assert!(shown.contains(s), "{s} in {shown}");
|
||||
}
|
||||
for s in ["Clean Up", "Stray Points", "Unpainted Objects", "Empty Text Paths"] {
|
||||
assert!(!shown.contains(s), "{s} left in English: {shown}");
|
||||
}
|
||||
assert_eq!(heading_label(app.ui.dialog.as_ref().unwrap()), "Clean Up", "English keeps the label");
|
||||
// Every language with complete menus has the options, and heads the dialog as the menu
|
||||
// item that opened it reads (Hindi also has a plain "Clean Up" row with other wording).
|
||||
for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) {
|
||||
let menu = crate::i18n::tr(lang, &item.label);
|
||||
assert_ne!(menu, item.label, "{}: menu item", lang.code());
|
||||
assert_eq!(heading_in(lang, "Clean Up"), menu.trim_end_matches('…').trim_end(), "{}: heading", lang.code());
|
||||
for key in ["strayPoints", "unpaintedObjects", "emptyTextPaths"] {
|
||||
let label = form::humanize(key);
|
||||
assert!(crate::i18n::has(lang, label.trim_end_matches(':')), "{}: {label}", lang.code());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document with a rectangle made a 2 x 2 Grid Repeat and selected, its Repeat Options
|
||||
/// dialog open.
|
||||
fn grid_options_app() -> VectorcraftApp {
|
||||
|
||||
@@ -69,6 +69,11 @@ pub(super) fn defaults(kind: &str) -> Option<&'static Value> {
|
||||
/// Set when the Print Tiling tool placed the pages (`tileOrigin`): the placement is ignored.
|
||||
const PLACED: &str = "tileOrigin.placed";
|
||||
|
||||
/// The link between Scale W and H.
|
||||
const SCALE_LINKED: &str = "scale.linked";
|
||||
/// Scale W and H as [`link_scale`] last left them, to tell which one changed since.
|
||||
const SCALE_SEEN: &str = "__scaleSeen";
|
||||
|
||||
/// The fields that aren't print settings.
|
||||
const NOT_SETTINGS: [&str; 5] = ["printer", "toFile", "discard", "preset", "name"];
|
||||
|
||||
@@ -97,6 +102,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str());
|
||||
fields.insert("preset".into(), json!(preset));
|
||||
fields.insert(LOADED.into(), json!(preset));
|
||||
see_scale(&mut fields);
|
||||
app.ui.dialog = Some(Dialog { kind: KIND.into(), fields });
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -118,6 +124,7 @@ fn sync_preset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
d.fields.insert(LOADED.into(), json!(name));
|
||||
let set = app.session.print_preset_settings(&name).ok_or_else(|| format!("no print preset named `{name}`"))?;
|
||||
d.fields.extend(fields_of(&set)?);
|
||||
see_scale(&mut d.fields);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -148,6 +155,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result<Value, St
|
||||
fields.insert(EDITING.into(), json!(editing));
|
||||
fields.insert("__section".into(), json!(SECTIONS[0]));
|
||||
fields.insert("__sheet".into(), json!(0));
|
||||
see_scale(&mut fields);
|
||||
app.ui.dialog = Some(Dialog { kind: PRESET_KIND.into(), fields });
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -155,6 +163,9 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result<Value, St
|
||||
/// Save Preset (the preset editor's OK): `print.presets.save`, then back to Edit → Print Presets on
|
||||
/// it. A new preset may not take the name of another one.
|
||||
fn confirm_preset(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let mut d = d.clone();
|
||||
link_scale(&mut d);
|
||||
let d = &d;
|
||||
let (name, editing) = (d.str("name"), d.str(EDITING));
|
||||
let p = if editing.is_empty() {
|
||||
if app.session.print_preset_settings(&name).is_some() {
|
||||
@@ -188,6 +199,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
// Done's flag holds for this press only: the dialog may stay open.
|
||||
let done = d.fields.remove("discard").is_some_and(|v| v == true);
|
||||
let synced = sync_preset(app, &mut d);
|
||||
link_scale(&mut d);
|
||||
app.ui.dialog = Some(d.clone());
|
||||
synced?;
|
||||
// While Save Preset… asks for a name, OK (and Enter) saves the preset instead.
|
||||
@@ -217,6 +229,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
if let Err(e) = sync_preset(app, d) {
|
||||
app.status(e);
|
||||
}
|
||||
link_scale(d);
|
||||
if d.kind == PRESET_KIND {
|
||||
row_with(ui, tl!("Preset name:"), TOP_LABEL_WIDTH, |ui| {
|
||||
form::text_edit(ui, d, "name", 288.0);
|
||||
@@ -577,6 +590,75 @@ fn whole(ui: &mut egui::Ui, d: &mut Dialog, path: &str, range: std::ops::RangeIn
|
||||
});
|
||||
}
|
||||
|
||||
/// A Scale percentage at `path`, 1–1000 %: the value typed, once one was.
|
||||
fn percent(ui: &mut egui::Ui, d: &mut Dialog, path: &str, enabled: bool) -> Option<f64> {
|
||||
let v = get(d, path).as_f64().unwrap_or(100.0);
|
||||
let typed = ui.add_enabled_ui(enabled, |ui| widgets::range_field(ui, path, v, 1.0..=1000.0, "%", 3, 64.0)).inner;
|
||||
if let Some(x) = typed {
|
||||
set(d, path, json!(x));
|
||||
}
|
||||
typed
|
||||
}
|
||||
|
||||
/// The link after Scale W and H: on, either field sets both, and turning it on sets H to W. With
|
||||
/// the keyboard on it, Space or Enter toggles it unless it is dimmed.
|
||||
fn scale_link(ui: &mut egui::Ui, d: &mut Dialog, linked: bool) {
|
||||
const NAME: &str = "Constrain Width and Height Proportions";
|
||||
let size = crate::panels::transform::CONSTRAIN_LINK_SIZE;
|
||||
let (_, at) = ui.allocate_exact_size(egui::Vec2::splat(size), egui::Sense::click());
|
||||
let enabled = ui.is_enabled();
|
||||
let keyed = enabled
|
||||
&& at.has_focus()
|
||||
&& ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Space) | i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
|
||||
let resp = widgets::paint_icon_button(ui, at, if linked { "link" } else { "link-2-off" }, NAME, linked);
|
||||
// Off is a state too: screen readers hear the link as off, not as a plain button.
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, linked, tl!(NAME)));
|
||||
if resp.clicked() || keyed {
|
||||
set(d, SCALE_LINKED, json!(!linked));
|
||||
link_scale(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// While the Scale link is on, keep H equal to W: the field that changed since the last call (a
|
||||
/// field typed in, or `ui.dialog.set`) gives its value to the other, and when neither changed H
|
||||
/// takes W, as turning the link on does. As `print.setup` reads a `scale`: one set with W and H
|
||||
/// apart and without a `linked` key turns the link off, one that leaves out W, H or `linked` (or
|
||||
/// gives `null`) keeps it as it was, and one that changes both W and H apart while linked is left
|
||||
/// as it is (and stays changed on later calls), for confirming to refuse.
|
||||
fn link_scale(d: &mut Dialog) {
|
||||
let seen = d.fields.get(SCALE_SEEN).cloned().unwrap_or_default();
|
||||
if let Some(Value::Object(s)) = d.fields.get_mut("scale") {
|
||||
let num = |s: &serde_json::Map<String, Value>, k: &str| s.get(k).and_then(Value::as_f64);
|
||||
let stated = |s: &serde_json::Map<String, Value>, k: &str| s.get(k).is_some_and(|v| !v.is_null());
|
||||
if s.get("linked").is_none() && num(s, "width").zip(num(s, "height")).is_some_and(|(w, h)| w != h) {
|
||||
s.insert("linked".into(), json!(false));
|
||||
}
|
||||
for (i, k) in ["width", "height", "linked"].into_iter().enumerate() {
|
||||
if !stated(s, k) && !seen[i].is_null() {
|
||||
s.insert(k.into(), seen[i].clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let (w, h) = (get(d, "scale.width").clone(), get(d, "scale.height").clone());
|
||||
if get(d, SCALE_LINKED).as_bool() == Some(true) && w.as_f64() != h.as_f64() {
|
||||
let (w_kept, h_kept) = (seen[0].as_f64() == w.as_f64(), seen[1].as_f64() == h.as_f64());
|
||||
if (w_kept && !h_kept) || w.as_f64().is_none() {
|
||||
set(d, "scale.width", h);
|
||||
} else if h_kept || seen.is_null() {
|
||||
set(d, "scale.height", w);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
see_scale(&mut d.fields);
|
||||
}
|
||||
|
||||
/// Remember Scale W, H and the link as the fields hold them, for [`link_scale`].
|
||||
fn see_scale(fields: &mut serde_json::Map<String, Value>) {
|
||||
let s = fields.get("scale").cloned().unwrap_or_default();
|
||||
fields.insert(SCALE_SEEN.into(), json!([s["width"], s["height"], s["linked"]]));
|
||||
}
|
||||
|
||||
fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let unit = app.session.general_unit();
|
||||
row(ui, tl!("Copies:"), |ui| {
|
||||
@@ -662,10 +744,16 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
});
|
||||
row(ui, tl!("Scale:"), |ui| {
|
||||
let on = scaling == PrintScaling::Custom || tiles;
|
||||
let linked = get(d, SCALE_LINKED).as_bool() == Some(true);
|
||||
ui.label(tl!("W:"));
|
||||
number(ui, d, "scale.width", "%", on);
|
||||
if let Some(w) = percent(ui, d, "scale.width", on).filter(|_| linked) {
|
||||
set(d, "scale.height", json!(w));
|
||||
}
|
||||
ui.label(tl!("H:"));
|
||||
number(ui, d, "scale.height", "%", on);
|
||||
if let Some(h) = percent(ui, d, "scale.height", on).filter(|_| linked) {
|
||||
set(d, "scale.width", json!(h));
|
||||
}
|
||||
ui.add_enabled_ui(on, |ui| scale_link(ui, d, linked));
|
||||
});
|
||||
row(ui, tl!("Overlap:"), |ui| length(ui, d, "overlap", unit, tiles));
|
||||
row(ui, tl!("Tile Range:"), |ui| text(ui, d, "tileRange", tiles));
|
||||
@@ -689,6 +777,7 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result<Value, String>) {
|
||||
});
|
||||
let separations = choice::<OutputMode>(d, "output.mode") == Some(OutputMode::Separations);
|
||||
flag(ui, d, "output.spotsToProcess", tl!("Convert All Spot Colors to Process"), separations);
|
||||
flag(ui, d, "output.overprintBlack", tl!("Overprint Black"), separations);
|
||||
heading(ui, tl!("Document Ink Options"));
|
||||
let inks = pv.as_ref().ok().and_then(|v| v["inks"].as_array()).map(Vec::as_slice).unwrap_or_default();
|
||||
if !separations || inks.is_empty() {
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
//! `__color` (the colour table's selected colour, by source), `__presetName` (shown while saving a
|
||||
//! preset) and `__hasSlices`. Save… remembers
|
||||
//! the settings and writes the files (`file.saveForWeb`); Done only remembers them; Preview in
|
||||
//! Browser opens the HTML page (`file.saveForWeb.browser`). The previews are what Save writes:
|
||||
//! Browser opens the HTML page (`file.saveForWeb.browser`). While Alt (Option on macOS) is held,
|
||||
//! Cancel reads Reset, which puts the remembered settings back and leaves the dialog open
|
||||
//! (`ui.dialogReset`). The previews are what Save writes:
|
||||
//! [`webexport::preview_image`], decoded back, cached until the art or a setting changes.
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -39,6 +41,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
ok: Some("Save…"),
|
||||
ok_label: Some(|app| if io::is_web(app) { "Download" } else { "Save…" }),
|
||||
discard: Some("Done"),
|
||||
reset: Some(reset),
|
||||
min_width: PREVIEW_W + GAP + SIDE_W,
|
||||
inputs: |_| &["path", "preset"],
|
||||
..DialogSpec::FORM
|
||||
@@ -71,14 +74,8 @@ const QUALITIES: [(&str, u8); 5] = [("Low", 10), ("Medium", 30), ("High", 60), (
|
||||
|
||||
/// Open on the document's active artboard, keeping the other remembered settings.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let n = app.session.active().ok_or("no document")?.doc.artboards.len();
|
||||
let mut s = app.session.last_web_settings();
|
||||
s.artboard = Some(crate::panels::artboards::selected(app, n));
|
||||
// A document with no artboards has no valid index.
|
||||
if s.artboard.is_some_and(|a| a >= n) {
|
||||
s.artboard = None;
|
||||
}
|
||||
let mut fields = settings_fields(&s);
|
||||
app.session.active().ok_or("no document")?;
|
||||
let mut fields = settings_fields(&remembered(app));
|
||||
let slices = app.session.active().is_some_and(|st| !st.doc.slice_layout().is_empty());
|
||||
fields.extend([
|
||||
("__view".into(), json!("2up")),
|
||||
@@ -90,6 +87,27 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The remembered settings (the defaults when none are remembered) on the document's active
|
||||
/// artboard; no artboard when the document has none.
|
||||
fn remembered(app: &VectorcraftApp) -> WebSettings {
|
||||
let n = app.session.active().map_or(0, |st| st.doc.artboards.len());
|
||||
let mut s = app.session.last_web_settings();
|
||||
s.artboard = Some(crate::panels::artboards::selected(app, n)).filter(|a| *a < n);
|
||||
s
|
||||
}
|
||||
|
||||
/// Reset (Cancel with Alt or Option held, or `ui.dialogReset`): the settings go back to the
|
||||
/// remembered ones on the document's active artboard ([`remembered`]), and a pending `preset`, a
|
||||
/// pending Done (`discard`, which a failed Done leaves), the preset name being typed and the
|
||||
/// selected color table entry are dropped. The view, zoom, connection speed and `path` stay,
|
||||
/// nothing is remembered or written, and the dialog stays open.
|
||||
fn reset(app: &VectorcraftApp, d: &mut Dialog) {
|
||||
for key in ["preset", "discard", "__presetName", "__color"] {
|
||||
d.fields.remove(key);
|
||||
}
|
||||
d.fields.extend(settings_fields(&remembered(app)));
|
||||
}
|
||||
|
||||
/// The settings as dialog fields.
|
||||
fn settings_fields(s: &WebSettings) -> Map<String, Value> {
|
||||
s.to_json().as_object().cloned().unwrap_or_default()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! Star, Line Segment, Arc and Spiral tool options, and the two grids (size, divider counts and skews, switches).
|
||||
//! The Line Segment, Arc and grid dialogs are also their tools' Tool Options (a double-click on the
|
||||
//! tool, [`open_options`]): OK then sets the options the tool's next drag and click use, and draws
|
||||
//! nothing.
|
||||
//! nothing. Arc Segment Tool Options also shows a picture of the arc its fields describe.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
@@ -181,6 +181,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
});
|
||||
} else if d.kind == "arc" {
|
||||
arc_form(ui, d, unit);
|
||||
if d.bool(TOOL_OPTIONS) {
|
||||
ui.add_space(8.0);
|
||||
arc_preview(ui, d, &app.session);
|
||||
}
|
||||
} else if LINKED.contains(&d.kind.as_str()) {
|
||||
linked_size_form(ui, d, unit);
|
||||
} else {
|
||||
@@ -262,6 +266,110 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
|
||||
form::check(ui, d, "fillArc", tl!("Fill Arc"));
|
||||
}
|
||||
|
||||
/// The size of the arc picture in Arc Segment Tool Options, and its margin around the arc.
|
||||
const ARC_PREVIEW: egui::Vec2 = egui::vec2(160.0, 120.0);
|
||||
const ARC_PREVIEW_MARGIN: f32 = 12.0;
|
||||
|
||||
/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`], kept as the tool
|
||||
/// keeps them: a slope from -100 to 100, a Base Along of Y or else X), as `shape.arc` draws it
|
||||
/// with its reference point at the origin and General › Constrain Angle `constrain` (degrees)
|
||||
/// turning it about that point. `None` when a length or the slope is not finite.
|
||||
fn arc_preview_path(d: &Dialog, constrain: f64) -> Option<vectorcraft_geom::path::PathData> {
|
||||
let o = arc_options(d);
|
||||
let num = |key: &str| o[key].as_f64().filter(|v| v.is_finite());
|
||||
let (lx, ly, slope) = (num("lengthX")?, num("lengthY")?, num("slope")?.clamp(-100.0, 100.0));
|
||||
let base_x = !o["baseAlong"].as_str().is_some_and(|b| b.eq_ignore_ascii_case("y"));
|
||||
let closed = o["closed"].as_bool().unwrap_or(false);
|
||||
let path = vectorcraft_geom::shapes::arc_segment(Point::ZERO, arc_reference(d), lx, ly, base_x, slope, closed);
|
||||
Some(match vectorcraft_geom::constrain_rotation(constrain) {
|
||||
Some(rotation) => path.transformed(vectorcraft_geom::rotate_deg(rotation)),
|
||||
None => path,
|
||||
})
|
||||
}
|
||||
|
||||
/// The arc in the dialog's picture, in screen points: its outline's points, whether it is closed,
|
||||
/// and where its reference point sits.
|
||||
struct ArcPreview {
|
||||
outline: Vec<egui::Pos2>,
|
||||
closed: bool,
|
||||
reference: egui::Pos2,
|
||||
}
|
||||
|
||||
/// The arc of [`arc_preview_path`] fitted into `rect` with [`ARC_PREVIEW_MARGIN`] around it,
|
||||
/// keeping its proportions. `None` when the fields describe no arc or the fitted points are not
|
||||
/// finite.
|
||||
fn arc_preview_shape(d: &Dialog, constrain: f64, rect: egui::Rect) -> Option<ArcPreview> {
|
||||
let path = arc_preview_path(d, constrain)?;
|
||||
let b = path.bounds()?.union_pt(Point::ZERO);
|
||||
let (room_w, room_h) = (f64::from(rect.width() - 2.0 * ARC_PREVIEW_MARGIN), f64::from(rect.height() - 2.0 * ARC_PREVIEW_MARGIN));
|
||||
// A side far thinner than the other (a length of 0) does not limit the scale.
|
||||
let extent = b.width().max(b.height());
|
||||
let fit = |side: f64, room: f64| if side > extent * 1e-6 { room / side } else { f64::INFINITY };
|
||||
let scale = fit(b.width(), room_w).min(fit(b.height(), room_h));
|
||||
if !(scale.is_finite() && scale > 0.0 && room_w > 0.0 && room_h > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let c = rect.center();
|
||||
let to_screen = vectorcraft_geom::Affine::translate((f64::from(c.x), f64::from(c.y)))
|
||||
* vectorcraft_geom::Affine::scale(scale)
|
||||
* vectorcraft_geom::Affine::translate(-b.center().to_vec2());
|
||||
let pos = |p: Point| egui::pos2(p.x as f32, p.y as f32);
|
||||
let mut outline = Vec::new();
|
||||
vectorcraft_geom::flatten(path.transformed(to_screen).to_bezpath(), 0.25, |el| match el {
|
||||
vectorcraft_geom::PathEl::MoveTo(p) | vectorcraft_geom::PathEl::LineTo(p) => outline.push(pos(p)),
|
||||
_ => {}
|
||||
});
|
||||
// A closed arc's last segment ends where it starts; the outline keeps its corner as the last point.
|
||||
let closed = path.is_closed();
|
||||
if closed && outline.len() > 2 && outline.first() == outline.last() {
|
||||
outline.pop();
|
||||
}
|
||||
let reference = pos(to_screen * Point::ZERO);
|
||||
let finite = |p: &egui::Pos2| p.x.is_finite() && p.y.is_finite();
|
||||
(outline.len() >= 2 && outline.iter().all(finite) && finite(&reference)).then_some(ArcPreview { outline, closed, reference })
|
||||
}
|
||||
|
||||
/// A paint as one color for the arc picture: a solid color as it is, a gradient or pattern gray.
|
||||
fn arc_preview_color(paint: &vectorcraft_color::Paint) -> Option<egui::Color32> {
|
||||
match paint {
|
||||
vectorcraft_color::Paint::None => None,
|
||||
vectorcraft_color::Paint::Solid { color, tint, .. } => Some(crate::panels::c32(&color.tinted(*tint))),
|
||||
_ => Some(egui::Color32::from_gray(160)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The arc Arc Segment Tool Options sets, drawn below its fields on white and redrawn on every
|
||||
/// frame from the fields as they are then: in the current stroke (black when there is none, as
|
||||
/// `shape.arc` draws it), filled with the current fill when Fill Arc is on, turned by General ›
|
||||
/// Constrain Angle, with a mark on its reference point.
|
||||
fn arc_preview(ui: &mut egui::Ui, d: &Dialog, session: &vectorcraft_engine::Session) {
|
||||
let t = crate::theme::Tokens::get(ui.ctx());
|
||||
let (rect, resp) = ui.allocate_exact_size(ARC_PREVIEW, egui::Sense::hover());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Preview")));
|
||||
let painter = ui.painter_at(rect);
|
||||
painter.rect_filled(rect, 0.0, egui::Color32::WHITE);
|
||||
painter.rect_stroke(rect, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside);
|
||||
let Some(arc) = arc_preview_shape(d, session.prefs.constrain_angle, rect) else { return };
|
||||
let fill = if d.bool("fillArc") { arc_preview_color(&session.paint.fill) } else { None };
|
||||
if let Some(fill) = fill {
|
||||
// A closed arc is seen whole from its corner (its last point), and an open arc closed by
|
||||
// its chord from its end: each fills as a fan of triangles from there.
|
||||
let mut mesh = egui::Mesh::default();
|
||||
for p in &arc.outline {
|
||||
mesh.colored_vertex(*p, fill);
|
||||
}
|
||||
let last = arc.outline.len() as u32 - 1;
|
||||
for i in 0..last.saturating_sub(1) {
|
||||
mesh.add_triangle(last, i, i + 1);
|
||||
}
|
||||
painter.add(egui::Shape::mesh(mesh));
|
||||
}
|
||||
let stroke = arc_preview_color(&session.paint.stroke).unwrap_or(egui::Color32::BLACK);
|
||||
let stroke = egui::Stroke::new(1.5, stroke);
|
||||
painter.add(if arc.closed { egui::Shape::closed_line(arc.outline, stroke) } else { egui::Shape::line(arc.outline, stroke) });
|
||||
painter.circle(arc.reference, 3.0, egui::Color32::WHITE, egui::Stroke::new(1.5, t.accent));
|
||||
}
|
||||
|
||||
/// The click dialogs whose Width and Height share a Constrain Width and Height Proportions link
|
||||
/// (<https://krankykids.com/cheatsheets/illustrator_cs6/shape_tool_rectangle.html>,
|
||||
/// <https://www.krankykids.com/cheatsheets/illustrator_cs6/shape_tool_ellipse.html>): the same
|
||||
@@ -543,6 +651,167 @@ mod tests {
|
||||
assert_eq!(box_origin(&fields(true)), (80.0, 40.0));
|
||||
}
|
||||
|
||||
fn arc_dialog(fields: Value) -> Dialog {
|
||||
let mut d =
|
||||
Dialog::new("arc", json!({"lengthX": 100.0, "lengthY": 60.0, "reference": 0, "baseAlong": "x", "slope": 50.0, "arcType": "open"}));
|
||||
for (k, v) in fields.as_object().into_iter().flatten() {
|
||||
d.fields.insert(k.clone(), v.clone());
|
||||
}
|
||||
d.fields.insert(TOOL_OPTIONS.into(), json!(true));
|
||||
d
|
||||
}
|
||||
|
||||
fn anchor_points(p: &vectorcraft_geom::path::PathData) -> Vec<(f64, f64, f64, f64, f64, f64)> {
|
||||
p.anchors().map(|(_, _, a)| (a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y)).collect()
|
||||
}
|
||||
|
||||
/// The preview is the arc `shape.arc` draws from the same values at a click on the origin, for
|
||||
/// each Type, Base Along, reference point and slope, and turned by General › Constrain Angle.
|
||||
#[test]
|
||||
fn the_arc_preview_is_the_arc_shape_arc_draws() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
for constrain in [0.0, 30.0] {
|
||||
app.run("prefs.set", json!({"key": "constrainAngle", "value": constrain})).unwrap();
|
||||
for (closed, base, reference, slope) in
|
||||
[(false, "x", 0, 50.0), (true, "x", 4, 100.0), (false, "y", 8, -100.0), (true, "y", 2, 0.0), (false, "x", 6, -40.0)]
|
||||
{
|
||||
let d =
|
||||
arc_dialog(json!({"arcType": if closed { "closed" } else { "open" }, "baseAlong": base, "reference": reference, "slope": slope}));
|
||||
let preview = arc_preview_path(&d, app.session.prefs.constrain_angle).expect("an arc");
|
||||
let params = json!({"x": 0.0, "y": 0.0, "lengthX": 100.0, "lengthY": 60.0, "reference": reference, "baseAlong": base, "slope": slope, "closed": closed});
|
||||
let params = vectorcraft_engine::constrain_click(&app.session, "shape.arc", params, Point::ZERO);
|
||||
app.run("shape.arc", params).unwrap();
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
let drawn = doc.layers[0].children().unwrap().last().unwrap().path_data().unwrap().clone();
|
||||
let (a, b) = (anchor_points(&preview), anchor_points(&drawn));
|
||||
assert_eq!(a.len(), b.len(), "{constrain} {closed} {base} {reference} {slope}");
|
||||
for (p, q) in a.iter().zip(&b) {
|
||||
let close = [(p.0, q.0), (p.1, q.1), (p.2, q.2), (p.3, q.3), (p.4, q.4), (p.5, q.5)].iter().all(|(u, v)| (u - v).abs() < 1e-6);
|
||||
assert!(close, "{constrain} {closed} {base} {reference} {slope}: {a:?} {b:?}");
|
||||
}
|
||||
assert_eq!(preview.is_closed(), closed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture follows Slope, Type, Base Along and the reference point, keeps the arc inside
|
||||
/// the frame, and stays finite for a length of 0 or a huge one.
|
||||
#[test]
|
||||
fn the_arc_preview_follows_the_fields_and_fits_its_frame() {
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(10.0, 20.0), ARC_PREVIEW);
|
||||
let shape = |fields: Value| arc_preview_shape(&arc_dialog(fields), 0.0, rect).expect("an arc");
|
||||
let inside = |s: &ArcPreview| {
|
||||
let room = rect.shrink(ARC_PREVIEW_MARGIN - 0.01);
|
||||
s.outline.iter().chain([&s.reference]).all(|p| room.contains(*p))
|
||||
};
|
||||
let base = shape(json!({}));
|
||||
assert!(inside(&base), "{:?}", base.outline);
|
||||
// Slope 0 is a straight line: two points.
|
||||
assert_eq!(shape(json!({"slope": 0.0})).outline.len(), 2);
|
||||
for changed in [json!({"slope": -50.0}), json!({"arcType": "closed"}), json!({"baseAlong": "y"}), json!({"lengthY": "30 pt"})] {
|
||||
let s = shape(changed.clone());
|
||||
assert!(inside(&s), "{changed}");
|
||||
assert_ne!(s.outline, base.outline, "{changed}");
|
||||
}
|
||||
assert!(shape(json!({"arcType": "closed"})).closed && !base.closed);
|
||||
// The reference mark sits on each of the nine points of the arc's box.
|
||||
let marks: Vec<egui::Pos2> = (0..9).map(|i| shape(json!({"reference": i})).reference).collect();
|
||||
assert!((marks[4] - rect.center()).length() < 1e-3, "{marks:?}");
|
||||
for row in 0..3 {
|
||||
assert!(marks[row * 3].x < marks[row * 3 + 1].x && marks[row * 3 + 1].x < marks[row * 3 + 2].x, "{marks:?}");
|
||||
assert!(marks[row].y < marks[row + 3].y && marks[row + 3].y < marks[row + 6].y, "{marks:?}");
|
||||
}
|
||||
for lengths in [json!({"lengthX": 0.0}), json!({"lengthY": 0.0}), json!({"lengthX": 1e300, "lengthY": 1e-300}), json!({"lengthX": -80.0})] {
|
||||
assert!(inside(&shape(lengths.clone())), "{lengths}");
|
||||
}
|
||||
}
|
||||
|
||||
/// For values the Arc tool does not keep as typed, the picture shows the arc of the options OK
|
||||
/// sets: the same picture as a dialog holding those options.
|
||||
#[test]
|
||||
fn the_arc_preview_shows_the_options_ok_sets() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
for typed in [
|
||||
json!({"slope": 140.0}),
|
||||
json!({"slope": -250.0}),
|
||||
json!({"slope": "steep"}),
|
||||
json!({"lengthX": "wide"}),
|
||||
json!({"lengthY": null}),
|
||||
json!({"baseAlong": "z"}),
|
||||
json!({"reference": 12}),
|
||||
] {
|
||||
let d = arc_dialog(typed.clone());
|
||||
let shown = arc_preview_path(&d, 0.0).expect("an arc");
|
||||
app.ui.dialog = Some(d);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let kept = app.session.tool_options_of("arc");
|
||||
let arc_type = if kept["closed"].as_bool() == Some(true) { "closed" } else { "open" };
|
||||
let keys = ["lengthX", "lengthY", "slope", "baseAlong", "reference"];
|
||||
let mut fields: serde_json::Map<String, Value> = keys.iter().map(|k| (k.to_string(), kept[*k].clone())).collect();
|
||||
fields.insert("arcType".into(), json!(arc_type));
|
||||
let want = arc_preview_path(&arc_dialog(Value::Object(fields)), 0.0).expect("an arc");
|
||||
assert_eq!(anchor_points(&shown), anchor_points(&want), "{typed}: kept {kept}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Double-clicking the Arc tool shows the picture in Arc Segment Tool Options; a click on the
|
||||
/// canvas does not. Changing the options and pressing OK draws nothing and adds no undo step.
|
||||
#[test]
|
||||
fn arc_tool_options_show_a_preview_and_ok_draws_nothing() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
app.run("tool.select", json!({"tool": "arc"})).unwrap();
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
open_options(&mut app, "arc").unwrap();
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state(
|
||||
move |ui, app: &mut VectorcraftApp| {
|
||||
if !std::mem::replace(&mut fonts, true) {
|
||||
crate::theme::install_fonts(ui.ctx());
|
||||
return;
|
||||
}
|
||||
super::super::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h.check_accessibility();
|
||||
let picture = h.get_by_role_and_label(Role::Image, "Preview").rect();
|
||||
let fill_arc = h.get_by_label("Fill Arc").rect();
|
||||
assert!(picture.top() > fill_arc.center().y, "the picture is below Fill Arc: {picture:?} {fill_arc:?}");
|
||||
h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("slope".into(), json!(-30.0));
|
||||
h.run_steps(2);
|
||||
super::super::confirm(h.state_mut()).unwrap();
|
||||
h.run_steps(2);
|
||||
let app = h.state();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert!(app.session.doc().unwrap().doc.layers[0].children().unwrap().is_empty());
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(app.session.tool_options_of("arc")["slope"], json!(-30.0));
|
||||
drop(h);
|
||||
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
super::super::open_tool_dialog(&mut app, "arc", json!({"x": 40.0, "y": 60.0}));
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state(
|
||||
move |ui, app: &mut VectorcraftApp| {
|
||||
if !std::mem::replace(&mut fonts, true) {
|
||||
crate::theme::install_fonts(ui.ctx());
|
||||
return;
|
||||
}
|
||||
super::super::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
assert!(h.query_by_role_and_label(Role::Image, "Preview").is_none());
|
||||
}
|
||||
|
||||
/// The Rounded Rectangle click dialog opens on General › Corner Radius, and OK makes the radius
|
||||
/// typed (in any unit) that preference: the next dialog and the tool's next drag use it.
|
||||
#[test]
|
||||
|
||||
@@ -2524,6 +2524,34 @@ fn flare_options_alt_turns_cancel_into_reset() {
|
||||
);
|
||||
}
|
||||
|
||||
/// While Alt is held, Save for Web's Cancel button reads Reset; Reset puts the remembered settings
|
||||
/// back without remembering anything and leaves the dialog open, and letting Alt go shows Cancel again.
|
||||
#[test]
|
||||
fn save_for_web_alt_turns_cancel_into_reset() {
|
||||
let mut app = app();
|
||||
app.run("webExport.settings", json!({"format": "jpg", "quality": 70})).unwrap();
|
||||
let remembered = app.session.last_web_settings().to_json();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
for (k, v) in [("format", json!("png8")), ("quality", json!(20)), ("colors", json!(16)), ("__view", json!("optimized"))] {
|
||||
d.fields.insert(k.into(), v);
|
||||
}
|
||||
let mut f = Frames::new();
|
||||
f.button(&mut app, "Cancel");
|
||||
f.run(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::ALT)]);
|
||||
let reset = f.button(&mut app, "Reset");
|
||||
let texts = f.texts(&mut app);
|
||||
assert!(!texts.iter().any(|(t, _)| t == "Cancel"), "Reset takes Cancel's place: {texts:?}");
|
||||
f.press(&mut app, reset, true);
|
||||
f.press(&mut app, reset, false);
|
||||
let d = app.ui.dialog.as_ref().expect("Reset leaves the dialog open");
|
||||
assert_eq!((d.str("format"), d.f64("quality", 0.0), d.f64("colors", 0.0)), ("jpg".into(), 70.0, 128.0));
|
||||
assert_eq!(d.str("__view"), "optimized", "the view stays");
|
||||
assert_eq!(app.session.last_web_settings().to_json(), remembered, "Reset remembers nothing");
|
||||
f.run(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
|
||||
f.button(&mut app, "Cancel");
|
||||
}
|
||||
|
||||
/// Reset Actions' question: OK replaces the action sets with the built-in set, Append adds the
|
||||
/// built-in set after them, and Cancel or Escape (`cancel`) leaves them as they are.
|
||||
#[test]
|
||||
|
||||
@@ -286,3 +286,157 @@ fn the_control_channel_fills_and_confirms_the_dialog() {
|
||||
assert_eq!(app.session.active().unwrap().doc.print_setup.as_ref().unwrap()["copies"], 5);
|
||||
assert_eq!(jobs.borrow().len(), 1);
|
||||
}
|
||||
|
||||
/// Frames of the dialog layer with the accessibility tree on.
|
||||
struct Screen {
|
||||
ctx: egui::Context,
|
||||
time: f64,
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
fn new() -> Self {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.enable_accesskit();
|
||||
theme::install_fonts(&ctx);
|
||||
Self { ctx, time: 0.0 }
|
||||
}
|
||||
|
||||
fn run(&mut self, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> egui::FullOutput {
|
||||
self.time += 0.1;
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0));
|
||||
let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() };
|
||||
let mut out = self.ctx.run_ui(input, |ui| super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
out
|
||||
}
|
||||
|
||||
/// The Scale link as screen readers find it: its node, whether it is on, and whether it is dimmed.
|
||||
fn link(&mut self, app: &mut VectorcraftApp) -> (egui::accesskit::NodeId, Option<egui::accesskit::Toggled>, bool) {
|
||||
self.run(app, vec![]);
|
||||
let out = self.run(app, vec![]);
|
||||
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
|
||||
let link =
|
||||
nodes.iter().find(|(_, n)| n.label() == Some("Constrain Width and Height Proportions") && n.role() == egui::accesskit::Role::Button);
|
||||
let (id, node) = link.expect("the Scale link");
|
||||
(*id, node.toggled(), node.is_disabled())
|
||||
}
|
||||
}
|
||||
|
||||
/// Scale W and H of the open dialog, and its link.
|
||||
fn scale(app: &mut VectorcraftApp) -> (f64, f64, bool) {
|
||||
let s = &dialog(app).fields["scale"];
|
||||
(s["width"].as_f64().unwrap_or(f64::NAN), s["height"].as_f64().unwrap_or(f64::NAN), s["linked"] == true)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scale_link_keeps_scale_width_and_height_equal() {
|
||||
use egui::accesskit::{Action, ActionRequest, Toggled, TreeId};
|
||||
let (mut app, _) = app();
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
let mut screen = Screen::new();
|
||||
// On for a new job, and dimmed with the fields until a scaling uses them.
|
||||
let (link, on, dimmed) = screen.link(&mut app);
|
||||
assert_eq!((on, dimmed), (Some(Toggled::True), true));
|
||||
set(&mut app, "scaling", json!("custom"));
|
||||
assert!(!screen.link(&mut app).2, "Custom scales by W and H");
|
||||
// Linked, a new W sets H, and a new H sets W.
|
||||
dialog(&mut app).fields["scale"]["width"] = json!(40);
|
||||
screen.run(&mut app, vec![]);
|
||||
assert_eq!(scale(&mut app), (40.0, 40.0, true));
|
||||
dialog(&mut app).fields["scale"]["height"] = json!(250);
|
||||
screen.run(&mut app, vec![]);
|
||||
assert_eq!(scale(&mut app), (250.0, 250.0, true));
|
||||
// A click turns it off: screen readers hear it off, and each field changes alone.
|
||||
let request = |action| egui::Event::AccessKitActionRequest(ActionRequest { action, target_node: link, target_tree: TreeId::ROOT, data: None });
|
||||
screen.run(&mut app, vec![request(Action::Click)]);
|
||||
assert_eq!(screen.link(&mut app).1, Some(Toggled::False));
|
||||
dialog(&mut app).fields["scale"]["width"] = json!(50);
|
||||
screen.run(&mut app, vec![]);
|
||||
assert_eq!(scale(&mut app), (50.0, 250.0, false));
|
||||
// Space on the focused link turns it on and sets H to W; Enter turns it off again.
|
||||
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
screen.run(&mut app, vec![request(Action::Focus)]);
|
||||
screen.run(&mut app, vec![key(egui::Key::Space)]);
|
||||
assert_eq!(scale(&mut app), (50.0, 50.0, true));
|
||||
assert_eq!(screen.link(&mut app).1, Some(Toggled::True));
|
||||
screen.run(&mut app, vec![request(Action::Focus)]);
|
||||
screen.run(&mut app, vec![key(egui::Key::Enter)]);
|
||||
assert_eq!(scale(&mut app), (50.0, 50.0, false));
|
||||
// Done keeps the link with the document's settings, and the next Print opens with it.
|
||||
dialog(&mut app).fields["scale"]["height"] = json!(75);
|
||||
set(&mut app, "discard", json!(true));
|
||||
super::confirm(&mut app).unwrap();
|
||||
let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap();
|
||||
assert_eq!(saved["scale"], json!({"width": 50.0, "height": 75.0, "linked": false}));
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
assert_eq!(scale(&mut app), (50.0, 75.0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_print_preset_keeps_the_scale_link() {
|
||||
let (mut app, _) = app();
|
||||
app.run("print.presets.save", json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap();
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
assert_eq!(scale(&mut app), (100.0, 100.0, true));
|
||||
// Choosing the preset loads its unlinked W and H as they are.
|
||||
set(&mut app, "preset", json!("Apart"));
|
||||
frame(&mut app);
|
||||
assert_eq!(scale(&mut app), (30.0, 90.0, false));
|
||||
// A scale set without the link and with W and H apart turns it off, as print.setup reads it.
|
||||
set(&mut app, "preset", json!("[Default]"));
|
||||
frame(&mut app);
|
||||
assert_eq!(scale(&mut app), (100.0, 100.0, true));
|
||||
set(&mut app, "scale", json!({"width": 20, "height": 60}));
|
||||
frame(&mut app);
|
||||
assert_eq!(scale(&mut app), (20.0, 60.0, false));
|
||||
// `linked: null` keeps the link as it was, off here.
|
||||
set(&mut app, "scale", json!({"width": 30, "height": 70, "linked": null}));
|
||||
frame(&mut app);
|
||||
assert_eq!(dialog(&mut app).fields["scale"], json!({"width": 30, "height": 70, "linked": false}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_set_through_the_dialog_keeps_the_percentage_it_changes() {
|
||||
let (mut app, _) = app();
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
// A new H with the link on, set before any frame: W follows it, and Done saves both.
|
||||
set(&mut app, "scale", json!({"width": 100, "height": 250, "linked": true}));
|
||||
set(&mut app, "discard", json!(true));
|
||||
super::confirm(&mut app).unwrap();
|
||||
let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap();
|
||||
assert_eq!(saved["scale"], json!({"width": 250.0, "height": 250.0, "linked": true}));
|
||||
// A scale that gives only W keeps the link and H as they were, so H follows W.
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
set(&mut app, "scale", json!({"width": 40}));
|
||||
frame(&mut app);
|
||||
assert_eq!(scale(&mut app), (40.0, 40.0, true));
|
||||
// A new W and H apart with `linked: null` keep the link on: they stay as set, and confirming
|
||||
// refuses them, as print.setup does, and saves nothing.
|
||||
set(&mut app, "scale", json!({"width": 50, "height": 200, "linked": null}));
|
||||
frame(&mut app);
|
||||
frame(&mut app);
|
||||
assert_eq!(scale(&mut app), (50.0, 200.0, true));
|
||||
set(&mut app, "discard", json!(true));
|
||||
assert!(super::confirm(&mut app).is_err());
|
||||
let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap();
|
||||
assert_eq!(saved["scale"], json!({"width": 250.0, "height": 250.0, "linked": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dimmed_scale_link_ignores_the_keyboard() {
|
||||
use egui::accesskit::{Action, ActionRequest, TreeId};
|
||||
let (mut app, _) = app();
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
let mut screen = Screen::new();
|
||||
set(&mut app, "scaling", json!("custom"));
|
||||
let (link, _, _) = screen.link(&mut app);
|
||||
let focus =
|
||||
egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Focus, target_node: link, target_tree: TreeId::ROOT, data: None });
|
||||
let space = egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
screen.run(&mut app, vec![focus]);
|
||||
// Scaling None dims the link while it has the keyboard: Space leaves it as it was.
|
||||
set(&mut app, "scaling", json!("none"));
|
||||
screen.run(&mut app, vec![space]);
|
||||
screen.run(&mut app, vec![]);
|
||||
assert_eq!(scale(&mut app), (100.0, 100.0, true));
|
||||
}
|
||||
@@ -289,6 +289,76 @@ fn save_remembers_and_writes_and_done_only_remembers() {
|
||||
assert!(!dir.join("Untitled-1.png").exists());
|
||||
}
|
||||
|
||||
/// `ui.dialogReset` puts the remembered settings back (the defaults when none are remembered) on
|
||||
/// the document's active artboard, drops a pending preset, the preset name being typed and the
|
||||
/// selected color, keeps the view, zoom, speed and path, writes and remembers nothing, and leaves
|
||||
/// the dialog open; settings changed after it are remembered as usual.
|
||||
#[test]
|
||||
fn reset_puts_the_remembered_settings_back() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-reset");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
let defaults = vectorcraft_engine::cmd::webexport::WebSettings::default().to_json();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
for (k, v) in [
|
||||
("format", json!("jpg")),
|
||||
("quality", json!(20)),
|
||||
("colorTable", json!({"locked": ["nope"]})),
|
||||
("preset", json!("PNG-24")),
|
||||
("__presetName", json!("Mine")),
|
||||
("__color", json!("#cc3300")),
|
||||
("__zoom", json!("200")),
|
||||
("__kbps", json!(1024)),
|
||||
("path", json!("elsewhere.png")),
|
||||
] {
|
||||
set(&mut app, k, v);
|
||||
}
|
||||
app.run("ui.dialogReset", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().expect("Reset leaves the dialog open");
|
||||
for (k, v) in defaults.as_object().unwrap() {
|
||||
let want = if k == "artboard" { &json!(0) } else { v };
|
||||
assert_eq!(d.fields.get(k), Some(want), "{k}");
|
||||
}
|
||||
for k in ["preset", "__presetName", "__color"] {
|
||||
assert!(!d.fields.contains_key(k), "{k}");
|
||||
}
|
||||
assert_eq!((d.str("__zoom"), d.f64("__kbps", 0.0), d.str("path")), ("200".into(), 1024.0, "elsewhere.png".into()));
|
||||
assert_eq!(app.session.last_web_settings().to_json(), defaults, "Reset remembers nothing");
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "Reset writes nothing");
|
||||
set(&mut app, "quality", json!(55));
|
||||
set(&mut app, "discard", json!(true));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(app.session.last_web_settings().quality, 55);
|
||||
|
||||
// Remembered on another document's second artboard: Reset keeps this document's active one.
|
||||
let mut app = two_artboards(&vectorcraft_testkit::temp_dir("sfw-reset-artboard"));
|
||||
app.run("view.goToArtboard", json!({"index": 1})).unwrap();
|
||||
app.run("webExport.settings", json!({"artboard": 1, "quality": 40})).unwrap();
|
||||
app.run("file.new", json!({"width": 50, "height": 50})).unwrap();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
set(&mut app, "quality", json!(90));
|
||||
set(&mut app, "artboard", json!(3));
|
||||
app.run("ui.dialogReset", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.fields["artboard"].clone(), d.f64("quality", 0.0)), (json!(0), 40.0));
|
||||
}
|
||||
|
||||
/// A Done that failed on a bad setting leaves `discard` in the dialog; Reset drops it, so Save…
|
||||
/// after Reset writes the file instead of only remembering the settings.
|
||||
#[test]
|
||||
fn reset_drops_a_done_that_failed() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-reset-done");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
set(&mut app, "colorTable", json!({"locked": ["nope"]}));
|
||||
set(&mut app, "discard", json!(true));
|
||||
assert!(confirm(&mut app).is_err());
|
||||
app.run("ui.dialogReset", json!({})).unwrap();
|
||||
assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("discard"));
|
||||
let r = confirm(&mut app).unwrap();
|
||||
let path = r["path"].as_str().expect("Save… writes a file");
|
||||
assert!(std::path::Path::new(path).exists(), "{path}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn html_output_with_slices_saves_the_page_and_images() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-html");
|
||||
|
||||
+305
-29
@@ -4,13 +4,17 @@
|
||||
//! or reached with ↑/↓ previews its font on the selected text (one live interaction, nothing in
|
||||
//! the history); a click or Enter applies it as one step, Escape or closing the menu puts the text
|
||||
//! back. The Glyphs panel and Find Font only pick a font ([`picked`]): nothing is previewed on the
|
||||
//! document. A star marks a favourite family, and the ★ filter lists only those. The ≈ button
|
||||
//! before a family's star (Show Similar Fonts) orders the listed families by how alike they look to
|
||||
//! it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent
|
||||
//! document. A star marks a favourite family, and the ★ filter lists only those. The Document
|
||||
//! filter lists only the families that type in the current document is set in
|
||||
//! ([`document_families`]), and is unavailable while no document is open. The Recently Added
|
||||
//! filter lists only the installed families with a font file created in the last 30 days, the
|
||||
//! newest first and without the Recent Fonts section ([`vectorcraft_text::FontDb::recently_added`]).
|
||||
//! The ≈ button before a family's star (Show Similar Fonts) orders the listed families by how alike
|
||||
//! they look to it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent
|
||||
//! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font
|
||||
//! Technology filter's Variable lists only variable font families. Preferences › Type › Enable
|
||||
//! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays
|
||||
//! out its filters on the same four rows wherever it opens. However narrow its field, it opens at
|
||||
//! out its filters on the same five rows wherever it opens. However narrow its field, it opens at
|
||||
//! least wide enough for those rows and for a family name up to 220 points wide with its sample
|
||||
//! beside it, up to 60% of the window; each sample fills its row's height. Recently used families
|
||||
//! appear first, in the order they were last applied, within the same search and filters as the
|
||||
@@ -119,10 +123,49 @@ pub struct MenuLook<'a> {
|
||||
pub wheel_owner: Option<WheelOwner>,
|
||||
/// The name screen readers give the closed field when no label stands beside it.
|
||||
pub name: Option<&'a str>,
|
||||
/// The current document, which the Document filter lists the families of. `None`: no document
|
||||
/// is open, and the filter is unavailable.
|
||||
pub document: Option<MenuDocument<'a>>,
|
||||
/// The time the Recently Added filter counts back from. `None`: the system clock.
|
||||
pub clock: Option<std::time::SystemTime>,
|
||||
}
|
||||
|
||||
/// The current document as the Document filter reads it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct MenuDocument<'a> {
|
||||
/// The document's identity.
|
||||
pub uid: u64,
|
||||
/// Its content: while an interaction is open (a font previewed from the menu), the content it
|
||||
/// started from, so a preview does not change the families listed. Its families are listed
|
||||
/// again when this is another version of the document.
|
||||
pub doc: &'a Arc<vectorcraft_doc::Document>,
|
||||
}
|
||||
|
||||
impl MenuDocument<'_> {
|
||||
/// Which document and which version of it the families were read from.
|
||||
fn key(&self) -> DocumentKey {
|
||||
DocumentKey { uid: self.uid, doc: Arc::downgrade(self.doc) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A document and a version of its content, compared by identity. The weak reference keeps the
|
||||
/// version's allocation, so a later version is never placed at the same address while the key is
|
||||
/// kept.
|
||||
#[derive(Clone, Debug)]
|
||||
struct DocumentKey {
|
||||
uid: u64,
|
||||
doc: std::sync::Weak<vectorcraft_doc::Document>,
|
||||
}
|
||||
|
||||
impl PartialEq for DocumentKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.uid == other.uid && std::sync::Weak::ptr_eq(&self.doc, &other.doc)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for MenuLook<'static> {
|
||||
/// Samples on in the theme's colors, English names, medium rows, no favorites, no wheel.
|
||||
/// Samples on in the theme's colors, English names, medium rows, no favorites, no wheel, no
|
||||
/// document, the system clock.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
samples: true,
|
||||
@@ -134,6 +177,8 @@ impl Default for MenuLook<'static> {
|
||||
wheel: false,
|
||||
wheel_owner: None,
|
||||
name: None,
|
||||
document: None,
|
||||
clock: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,6 +200,11 @@ impl<'a> MenuLook<'a> {
|
||||
wheel: false,
|
||||
wheel_owner: None,
|
||||
name: None,
|
||||
document: app
|
||||
.session
|
||||
.active()
|
||||
.map(|state| MenuDocument { uid: state.uid, doc: state.interaction.as_ref().map_or(&state.doc, |interaction| &interaction.doc) }),
|
||||
clock: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -310,8 +360,52 @@ fn remap_highlight(before: &[Row], selected: Option<usize>, after: &[Row]) -> Op
|
||||
|
||||
/// What the rows were listed for: the query, the script, kind, font technology (variable only) and
|
||||
/// favourites filters, Show Font Names in English, the expanded families, favourites, recent
|
||||
/// history, font list generation and the family Show Similar Fonts orders by.
|
||||
type RowsKey = (String, usize, Option<FontClass>, bool, bool, bool, Vec<String>, Vec<String>, Vec<String>, u64, Option<String>);
|
||||
/// history, font list generation, the family Show Similar Fonts orders by, the document version
|
||||
/// while the Document filter lists its families, and the recently added families while the
|
||||
/// Recently Added filter lists them.
|
||||
type RowsKey = (
|
||||
String,
|
||||
usize,
|
||||
Option<FontClass>,
|
||||
bool,
|
||||
bool,
|
||||
bool,
|
||||
Vec<String>,
|
||||
Vec<String>,
|
||||
Vec<String>,
|
||||
u64,
|
||||
Option<String>,
|
||||
(Option<DocumentKey>, Option<Arc<AddedFonts>>),
|
||||
);
|
||||
|
||||
/// The installed families the Recently Added filter lists: each one's place in the list
|
||||
/// (lowercase name to place, newest first), and the instant from which they are to be found again
|
||||
/// ([`vectorcraft_text::RecentlyAdded::recheck_at`]).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
struct AddedFonts {
|
||||
place: HashMap<String, usize>,
|
||||
recheck_at: Option<std::time::SystemTime>,
|
||||
}
|
||||
|
||||
impl AddedFonts {
|
||||
fn of(list: &vectorcraft_text::RecentlyAdded) -> Self {
|
||||
Self { place: list.families.iter().enumerate().map(|(i, f)| (f.to_lowercase(), i)).collect(), recheck_at: list.recheck_at }
|
||||
}
|
||||
|
||||
/// Orders `families` (the listed ones) newest first.
|
||||
fn order(&self, families: &mut [String]) {
|
||||
families.sort_by_cached_key(|f| self.place.get(&f.to_lowercase()).copied().unwrap_or(usize::MAX));
|
||||
}
|
||||
}
|
||||
|
||||
/// The recently added families a [`MenuState`] found, the database and font list generation they
|
||||
/// were found in ([`vectorcraft_text::FontDb::id`], [`vectorcraft_text::FontDb::generation`]), and
|
||||
/// the time they were found for.
|
||||
type RecentlyAddedFonts = ((u64, u64), std::time::SystemTime, Arc<AddedFonts>);
|
||||
|
||||
/// The families a [`MenuState`] found in a document (lowercase), and the document version and font
|
||||
/// list generation they were found for.
|
||||
type DocumentFonts = ((DocumentKey, u64), Arc<HashSet<String>>);
|
||||
|
||||
/// The menu's state between frames.
|
||||
#[derive(Clone, Default)]
|
||||
@@ -327,12 +421,21 @@ struct MenuState {
|
||||
highlight: Option<usize>,
|
||||
query: String,
|
||||
/// The filters (kept from one opening to the next, and the same in every font menu:
|
||||
/// [`Filters`]): script (0..[`SCRIPTS`]), kind, font technology (variable fonts only) and
|
||||
/// favorites only.
|
||||
/// [`Filters`]): script (0..[`SCRIPTS`]), kind, font technology (variable fonts only),
|
||||
/// favorites only, the current document's families only and recently added families only.
|
||||
script: usize,
|
||||
class: Option<FontClass>,
|
||||
variable_only: bool,
|
||||
favorites_only: bool,
|
||||
document_only: bool,
|
||||
added_only: bool,
|
||||
/// The recently added families the Recently Added filter last listed.
|
||||
added: Option<RecentlyAddedFonts>,
|
||||
/// The families of the current document the Document filter last listed.
|
||||
document_fonts: Option<DocumentFonts>,
|
||||
/// The Document filter lists nothing because the document's type uses none of the menu's
|
||||
/// families (none at all, or only missing ones), whatever the other filters.
|
||||
none_used: bool,
|
||||
/// Families whose styles are listed (lowercase).
|
||||
expanded: Vec<String>,
|
||||
/// Show Similar Fonts: the family the list is ordered by likeness to, until it is cleared or
|
||||
@@ -352,7 +455,10 @@ struct MenuState {
|
||||
filters: f32,
|
||||
/// The families the wheel steps through, listed at its first notch over the closed field and
|
||||
/// kept for that text selection while the pointer stays on it: each step makes its family a recent one, which would
|
||||
/// otherwise move it in the order.
|
||||
/// otherwise move it in the order. The Document filter's families are kept the same way: a
|
||||
/// step that leaves a family unused keeps it in the order, so turning the wheel back returns
|
||||
/// to it. They are listed again at the first notch after the pointer leaves the field or the
|
||||
/// selection changes.
|
||||
wheel_order: Option<Arc<[String]>>,
|
||||
wheel_target: Option<WheelTarget>,
|
||||
}
|
||||
@@ -366,11 +472,20 @@ struct Filters {
|
||||
class: Option<FontClass>,
|
||||
variable_only: bool,
|
||||
favorites_only: bool,
|
||||
document_only: bool,
|
||||
added_only: bool,
|
||||
}
|
||||
|
||||
impl Filters {
|
||||
fn of(st: &MenuState) -> Self {
|
||||
Self { script: st.script, class: st.class, variable_only: st.variable_only, favorites_only: st.favorites_only }
|
||||
Self {
|
||||
script: st.script,
|
||||
class: st.class,
|
||||
variable_only: st.variable_only,
|
||||
favorites_only: st.favorites_only,
|
||||
document_only: st.document_only,
|
||||
added_only: st.added_only,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(self, st: &mut MenuState) {
|
||||
@@ -378,9 +493,99 @@ impl Filters {
|
||||
st.class = self.class;
|
||||
st.variable_only = self.variable_only;
|
||||
st.favorites_only = self.favorites_only;
|
||||
st.document_only = self.document_only;
|
||||
st.added_only = self.added_only;
|
||||
}
|
||||
}
|
||||
|
||||
/// The families the type in `doc` is set in, lowercase and by the name the menu lists them under
|
||||
/// ([`vectorcraft_text::FontDb::canonical`]): the runs of every text object in the layers, symbols,
|
||||
/// patterns and graph designs, hidden, locked and masked ones included, with a composite font named
|
||||
/// as such. A pattern being edited is read from its editing layer only. Each run's family is looked
|
||||
/// up with its style, so a family and style split from a PostScript name (`Honoka`, `Mincho`) find
|
||||
/// the installed font of that name. Styles no type uses are left out.
|
||||
fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Document) -> HashSet<String> {
|
||||
// Each family and style once, so a document with many runs in a few fonts looks each one up
|
||||
// once.
|
||||
let mut named: HashMap<String, HashSet<String>> = HashMap::new();
|
||||
let mut add = |n: &vectorcraft_doc::Node| {
|
||||
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
|
||||
for r in &t.runs {
|
||||
let (family, style) = (&r.style.font_family, &r.style.font_style);
|
||||
match named.get_mut(family) {
|
||||
Some(styles) => {
|
||||
if !styles.contains(style) {
|
||||
styles.insert(style.clone());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
named.insert(family.clone(), HashSet::from([style.clone()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let editing = doc.pattern_edit.as_ref().map(|e| e.pattern.as_str());
|
||||
let patterns = doc.patterns.iter().filter(|p| Some(p.name.as_str()) != editing).flat_map(|p| p.art.iter().map(|a| &**a));
|
||||
let designs = doc.graph_designs.iter().map(|g| &*g.art);
|
||||
for n in doc.layers.iter().map(|l| &**l).chain(doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(designs) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut add);
|
||||
}
|
||||
named.iter().flat_map(|(f, styles)| styles.iter().map(move |s| db.canonical(f, s).0.to_lowercase())).collect()
|
||||
}
|
||||
|
||||
/// The families the Document filter lists, when it is on and a document is open: those of
|
||||
/// `look`'s document, found again only when the document, its version or the font list changed.
|
||||
fn used_families(db: &vectorcraft_text::FontDb, st: &mut MenuState, look: MenuLook) -> Option<Arc<HashSet<String>>> {
|
||||
let document = look.document.filter(|_| st.document_only)?;
|
||||
let key = (document.key(), db.generation());
|
||||
if let Some((k, families)) = &st.document_fonts
|
||||
&& *k == key
|
||||
{
|
||||
return Some(families.clone());
|
||||
}
|
||||
let families = Arc::new(document_families(db, document.doc));
|
||||
st.document_fonts = Some((key, families.clone()));
|
||||
Some(families)
|
||||
}
|
||||
|
||||
/// The time the Recently Added filter counts back from: `look`'s clock, else the system clock. On
|
||||
/// wasm, which has no installed fonts to date, the Unix epoch.
|
||||
fn added_clock(look: MenuLook) -> std::time::SystemTime {
|
||||
look.clock.unwrap_or_else(|| {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
std::time::SystemTime::now()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
std::time::SystemTime::UNIX_EPOCH
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The families the Recently Added filter lists, when it is on: those `db` dates within
|
||||
/// [`vectorcraft_text::RECENTLY_ADDED_WITHIN`] before `look`'s clock, found again only when the
|
||||
/// font list changed, the clock reached the instant the list may change at, or the clock went back
|
||||
/// before the time the list was found for.
|
||||
fn added_families(db: &vectorcraft_text::FontDb, st: &mut MenuState, look: MenuLook) -> Option<Arc<AddedFonts>> {
|
||||
if !st.added_only {
|
||||
return None;
|
||||
}
|
||||
let now = added_clock(look);
|
||||
let key = (db.id(), db.generation());
|
||||
if let Some((k, asked, added)) = &st.added
|
||||
&& *k == key
|
||||
&& *asked <= now
|
||||
&& added.recheck_at.is_none_or(|t| now < t)
|
||||
{
|
||||
return Some(added.clone());
|
||||
}
|
||||
let added = Arc::new(AddedFonts::of(&db.recently_added(now)));
|
||||
st.added = Some((key, now, added.clone()));
|
||||
Some(added)
|
||||
}
|
||||
|
||||
/// Where the filters every font menu shares are kept ([`Filters`]).
|
||||
fn filters_id() -> egui::Id {
|
||||
egui::Id::unique("font-menu-filters")
|
||||
@@ -448,7 +653,7 @@ pub fn font_menu(
|
||||
WheelInput::Leave => st.wheel_order = None,
|
||||
WheelInput::Notches(notches) => {
|
||||
if st.wheel_order.is_none() {
|
||||
st.wheel_order = Some(wheel_order(&st, look).into());
|
||||
st.wheel_order = Some(wheel_order(&mut st, look).into());
|
||||
}
|
||||
if let Some(order) = st.wheel_order.as_deref() {
|
||||
let next = wheel_steps(order, &own, notches);
|
||||
@@ -488,8 +693,24 @@ pub fn font_menu(
|
||||
out
|
||||
}
|
||||
|
||||
/// Does the menu list family `f` for search `query` (lowercase) under the filters of `st`?
|
||||
fn listed(db: &vectorcraft_text::FontDb, f: &str, query: &str, st: &MenuState, look: MenuLook) -> bool {
|
||||
/// Does the menu list family `f` for search `query` (lowercase) under the filters of `st`, among
|
||||
/// `used` (lowercase) while the Document filter lists the document's families, and among `added`
|
||||
/// while the Recently Added filter lists the recently added ones?
|
||||
fn listed(
|
||||
db: &vectorcraft_text::FontDb,
|
||||
f: &str,
|
||||
query: &str,
|
||||
st: &MenuState,
|
||||
look: MenuLook,
|
||||
used: Option<&HashSet<String>>,
|
||||
added: Option<&AddedFonts>,
|
||||
) -> bool {
|
||||
if used.is_some_and(|used| !used.contains(&f.to_lowercase())) {
|
||||
return false;
|
||||
}
|
||||
if added.is_some_and(|added| !added.place.contains_key(&f.to_lowercase())) {
|
||||
return false;
|
||||
}
|
||||
let label = db.family_display_name(f, look.english_names);
|
||||
if !(query.is_empty() || f.to_lowercase().contains(query) || label.to_lowercase().contains(query)) {
|
||||
return false;
|
||||
@@ -505,11 +726,22 @@ fn listed(db: &vectorcraft_text::FontDb, f: &str, query: &str, st: &MenuState, l
|
||||
}
|
||||
|
||||
/// The families the closed field's wheel steps through, in the open menu's order with no search:
|
||||
/// the recent families first, then the others, under the menu's filters.
|
||||
fn wheel_order(st: &MenuState, look: MenuLook) -> Vec<String> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, "", st, look)).cloned().collect();
|
||||
grouped_rows(&families, look.recent, &[], |_| vec![])
|
||||
/// the recent families first, then the others, under the menu's filters; with Recently Added, the
|
||||
/// newest first. Listed once per wheel gesture ([`MenuState`]'s `wheel_order`).
|
||||
fn wheel_order(st: &mut MenuState, look: MenuLook) -> Vec<String> {
|
||||
wheel_order_in(vectorcraft_text::FontDb::global(), st, look)
|
||||
}
|
||||
|
||||
/// [`wheel_order`] of the families in `db`.
|
||||
fn wheel_order_in(db: &vectorcraft_text::FontDb, st: &mut MenuState, look: MenuLook) -> Vec<String> {
|
||||
let used = used_families(db, st, look);
|
||||
let added = added_families(db, st, look);
|
||||
let mut families: Vec<_> =
|
||||
db.menu_family_list().iter().filter(|f| listed(db, f, "", st, look, used.as_deref(), added.as_deref())).cloned().collect();
|
||||
if let Some(added) = &added {
|
||||
added.order(&mut families);
|
||||
}
|
||||
grouped_rows(&families, if added.is_some() { &[] } else { look.recent }, &[], |_| vec![])
|
||||
.into_iter()
|
||||
.filter_map(|r| match r {
|
||||
Row::Family(f) => Some(f),
|
||||
@@ -1075,7 +1307,14 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
|
||||
ui.memory_mut(|m| m.request_focus(field.with("edit")));
|
||||
}
|
||||
let query = widgets::search_field(ui, field, tl!("Search")).to_lowercase();
|
||||
let refilter = filters(ui, st, &t);
|
||||
let refilter = filters(ui, st, &t, look.document.is_some());
|
||||
let added = added_families(db, st, look);
|
||||
// On the system clock, the list is drawn again when a family's 30 days end.
|
||||
if let (Some(at), None) = (added.as_ref().and_then(|a| a.recheck_at), look.clock)
|
||||
&& let Ok(wait) = at.duration_since(added_clock(look))
|
||||
{
|
||||
ui.ctx().request_repaint_after(wait);
|
||||
}
|
||||
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
// The current family by its own name (a document may name it in Japanese: ヒラギノ角ゴシック),
|
||||
// as it was before any preview.
|
||||
@@ -1094,13 +1333,26 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
|
||||
look.recent.to_vec(),
|
||||
db.generation(),
|
||||
st.similar.clone(),
|
||||
(look.document.filter(|_| st.document_only).map(|d| d.key()), added.clone()),
|
||||
);
|
||||
if st.rows_key.as_ref() != Some(&key) {
|
||||
let families: Vec<_> = db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look)).cloned().collect();
|
||||
let used = used_families(db, st, look);
|
||||
let mut families: Vec<_> =
|
||||
db.menu_family_list().iter().filter(|f| listed(db, f, &query, st, look, used.as_deref(), added.as_deref())).cloned().collect();
|
||||
st.none_used = families.is_empty() && used.is_some_and(|used| !db.menu_family_list().iter().any(|f| used.contains(&f.to_lowercase())));
|
||||
// Recently Added lists every family it finds once, newest first: the recent ones among
|
||||
// them, without the Recent Fonts section.
|
||||
let recent = match &added {
|
||||
Some(added) => {
|
||||
added.order(&mut families);
|
||||
&[]
|
||||
}
|
||||
None => look.recent,
|
||||
};
|
||||
// Show Similar Fonts orders every listed family by likeness, the recent ones among them.
|
||||
let rows = match &st.similar {
|
||||
Some(base) => grouped_rows(&db.similar_families(base, &families), &[], &st.expanded, |f| db.styles(f)),
|
||||
None => grouped_rows(&families, look.recent, &st.expanded, |f| db.styles(f)),
|
||||
None => grouped_rows(&families, recent, &st.expanded, |f| db.styles(f)),
|
||||
};
|
||||
// Filter changes (including un-starring a favourite) may remove rows; expanding
|
||||
// another family or a background font scan can insert rows before the highlight.
|
||||
@@ -1145,7 +1397,9 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id,
|
||||
}
|
||||
st.header = ui.min_rect().height();
|
||||
if rows.is_empty() {
|
||||
widgets::dim_label(ui, tl!("No matching fonts"));
|
||||
// The Document filter on a document whose type uses none of the listed families (none at
|
||||
// all, or only missing ones) says so, whatever the other filters.
|
||||
widgets::dim_label(ui, if st.none_used { tl!("This document uses no available fonts") } else { tl!("No matching fonts") });
|
||||
}
|
||||
ui.spacing_mut().item_spacing.y = 0.0;
|
||||
// The scroll bar beside the rows, not over them: a floating one covered the stars at their
|
||||
@@ -1160,6 +1414,10 @@ enum Chip {
|
||||
/// A script ([`SCRIPTS`]).
|
||||
Script(usize),
|
||||
Favorites,
|
||||
/// The families the current document's type uses.
|
||||
Document,
|
||||
/// The families installed in the last 30 days.
|
||||
Added,
|
||||
AnyKind,
|
||||
Class(FontClass),
|
||||
/// The Font Technology label, which filters nothing.
|
||||
@@ -1167,21 +1425,24 @@ enum Chip {
|
||||
Variable,
|
||||
}
|
||||
|
||||
/// The filters, row by row, the same wherever the menu opens: the scripts; favorites, any kind
|
||||
/// and the first three kinds; the other kinds; font technology.
|
||||
fn filter_rows() -> [Vec<Chip>; 4] {
|
||||
/// The filters, row by row, the same wherever the menu opens: the scripts; favorites, the
|
||||
/// document's fonts, any kind and the first three kinds; the other kinds; font technology; the
|
||||
/// recently added fonts.
|
||||
fn filter_rows() -> [Vec<Chip>; 5] {
|
||||
let (first, rest) = FontClass::ALL.split_at(3);
|
||||
[
|
||||
(0..SCRIPTS).map(Chip::Script).collect(),
|
||||
[Chip::Favorites, Chip::AnyKind].into_iter().chain(first.iter().copied().map(Chip::Class)).collect(),
|
||||
[Chip::Favorites, Chip::Document, Chip::AnyKind].into_iter().chain(first.iter().copied().map(Chip::Class)).collect(),
|
||||
rest.iter().copied().map(Chip::Class).collect(),
|
||||
vec![Chip::Technology, Chip::Variable],
|
||||
vec![Chip::Added],
|
||||
]
|
||||
}
|
||||
|
||||
/// The filters on their rows ([`filter_rows`]): a row wraps only where the menu is narrower than
|
||||
/// it. Records in `st` the width of the widest row unwrapped; whether a filter changed.
|
||||
fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool {
|
||||
/// it. The Document filter is unavailable without a `document`. Records in `st` the width of the
|
||||
/// widest row unwrapped; whether a filter changed.
|
||||
fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool) -> bool {
|
||||
let mut refilter = false;
|
||||
let mut widest = 0.0_f32;
|
||||
for row in filter_rows() {
|
||||
@@ -1194,6 +1455,19 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool {
|
||||
let resp = match chip {
|
||||
Chip::Script(i) => ui.selectable_label(st.script == i, text(script_label(i))),
|
||||
Chip::Favorites => ui.selectable_label(st.favorites_only, text("★")).on_hover_text(tl!("Favorites")),
|
||||
Chip::Document => {
|
||||
let on = st.document_only && document;
|
||||
let tip = tl!("Fonts used in this document");
|
||||
let resp = ui
|
||||
.add_enabled(document, egui::Button::selectable(on, text(tl!("Document"))))
|
||||
.on_hover_text(tip)
|
||||
.on_disabled_hover_text(tip);
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, document, on, tip));
|
||||
resp
|
||||
}
|
||||
Chip::Added => {
|
||||
ui.selectable_label(st.added_only, text(tl!("Recently Added"))).on_hover_text(tl!("Fonts added in the last 30 days"))
|
||||
}
|
||||
Chip::AnyKind => ui.selectable_label(st.class.is_none(), text(tl!("Any Kind"))),
|
||||
Chip::Class(c) => ui.selectable_label(st.class == Some(c), text(class_label(c))),
|
||||
Chip::Technology => ui.label(text(tl!("Font Technology")).color(t.text_dim)),
|
||||
@@ -1206,6 +1480,8 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens) -> bool {
|
||||
match chip {
|
||||
Chip::Script(i) => st.script = i,
|
||||
Chip::Favorites => st.favorites_only = !st.favorites_only,
|
||||
Chip::Document => st.document_only = !st.document_only,
|
||||
Chip::Added => st.added_only = !st.added_only,
|
||||
Chip::AnyKind => st.class = None,
|
||||
Chip::Class(c) => st.class = if st.class == Some(c) { None } else { Some(c) },
|
||||
Chip::Technology => continue,
|
||||
|
||||
@@ -380,15 +380,15 @@ fn the_wheel_follows_the_menus_order_and_filters() {
|
||||
}
|
||||
let recent = vec![names[2].clone()];
|
||||
let look = super::MenuLook { samples: false, recent: &recent, ..Default::default() };
|
||||
let order = super::wheel_order(&super::MenuState::default(), look);
|
||||
let order = super::wheel_order(&mut super::MenuState::default(), look);
|
||||
assert_eq!(order.first(), Some(&names[2]), "the recent family first");
|
||||
// Other tests add fonts to the process-wide database meanwhile: compare places, not neighbours.
|
||||
let at = |f: &String| order.iter().position(|x| x == f);
|
||||
assert!(matches!((at(&names[0]), at(&names[1])), (Some(a), Some(b)) if 0 < a && a < b), "then the others in the menu's order");
|
||||
assert_eq!(order.iter().filter(|f| **f == names[2]).count(), 1, "once each");
|
||||
let favorites = vec![names[0].clone(), names[1].clone()];
|
||||
let st = super::MenuState { favorites_only: true, ..Default::default() };
|
||||
let order = super::wheel_order(&st, super::MenuLook { favorites: &favorites, ..look });
|
||||
let mut st = super::MenuState { favorites_only: true, ..Default::default() };
|
||||
let order = super::wheel_order(&mut st, super::MenuLook { favorites: &favorites, ..look });
|
||||
assert_eq!(order, favorites, "the favourites filter");
|
||||
}
|
||||
|
||||
@@ -1131,3 +1131,340 @@ fn show_similar_fonts_orders_the_list_by_likeness() {
|
||||
frame(vec![], &mut st);
|
||||
assert_eq!((st.similar.as_deref(), families(&st)), (None, menu_order));
|
||||
}
|
||||
|
||||
/// An app with a new document holding type set in each of `fonts`, one text object each.
|
||||
fn app_with_type(fonts: &[&str]) -> crate::VectorcraftApp {
|
||||
let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({})).unwrap();
|
||||
for (i, font) in fonts.iter().enumerate() {
|
||||
app.run("text.create", serde_json::json!({"x": 20, "y": 40 + 30 * i, "text": "Type", "font": font})).unwrap();
|
||||
}
|
||||
app
|
||||
}
|
||||
|
||||
/// Draws the open menu (its header and rows) for `look` under the filters of `st`, with `events`;
|
||||
/// returns the shapes drawn.
|
||||
fn menu_frame(ctx: &egui::Context, st: &mut super::MenuState, look: super::MenuLook, events: Vec<egui::Event>) -> Vec<egui::epaint::ClippedShape> {
|
||||
let input =
|
||||
egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 900.0))), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
super::list(ui, egui::Id::unique("document-filter"), st, "Inter", None, look);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
out.shapes
|
||||
}
|
||||
|
||||
/// The families `st`'s rows list, in their order.
|
||||
fn listed_families(st: &super::MenuState) -> Vec<String> {
|
||||
st.rows
|
||||
.iter()
|
||||
.filter_map(|r| match r {
|
||||
Row::Family(f) => Some(f.clone()),
|
||||
Row::Heading(_) | Row::Style(..) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The Document filter's chip lists only the families the document's type uses (hidden and locked
|
||||
/// type included, a missing family left out), in the menu's order, and lists every family again
|
||||
/// when it is clicked off.
|
||||
#[test]
|
||||
fn the_document_filter_lists_the_families_the_documents_type_uses() {
|
||||
let mut app = app_with_type(&["Source Serif 4", "Inter"]);
|
||||
app.run("object.hide", serde_json::json!({})).unwrap();
|
||||
app.run("text.create", serde_json::json!({"x": 20, "y": 120, "text": "Locked", "font": "Source Sans 3"})).unwrap();
|
||||
app.run("object.lock", serde_json::json!({})).unwrap();
|
||||
app.run("text.create", serde_json::json!({"x": 20, "y": 150, "text": "Missing", "font": "Missing Family 7059"})).unwrap();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let used = super::document_families(db, &app.session.active().unwrap().doc);
|
||||
let mut names: Vec<_> = used.iter().cloned().collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["inter", "missing family 7059", "source sans 3", "source serif 4"], "each run's family, as named");
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut st = super::MenuState::default();
|
||||
let look = super::MenuLook { samples: false, ..super::MenuLook::of(&app) };
|
||||
for _ in 0..3 {
|
||||
menu_frame(&ctx, &mut st, look, vec![]);
|
||||
}
|
||||
let every = listed_families(&st);
|
||||
assert!(every.len() > 3, "every family: {every:?}");
|
||||
let click = |st: &mut super::MenuState, at: egui::Pos2| {
|
||||
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
menu_frame(&ctx, st, look, vec![egui::Event::PointerMoved(at), button(true)]);
|
||||
menu_frame(&ctx, st, look, vec![button(false)]);
|
||||
menu_frame(&ctx, st, look, vec![])
|
||||
};
|
||||
let chip = text_at(&menu_frame(&ctx, &mut st, look, vec![]), |t| t == "Document").expect("the Document chip is drawn");
|
||||
click(&mut st, chip);
|
||||
assert!(st.document_only);
|
||||
let in_menu: Vec<String> = every.iter().filter(|f| ["Inter", "Source Sans 3", "Source Serif 4"].contains(&f.as_str())).cloned().collect();
|
||||
assert_eq!(listed_families(&st), in_menu, "the document's available families, in the menu's order");
|
||||
click(&mut st, chip);
|
||||
assert!(!st.document_only);
|
||||
assert_eq!(listed_families(&st), every, "every family again");
|
||||
}
|
||||
|
||||
/// Type kept in a graph design counts as the document's type, as type in a symbol does.
|
||||
#[test]
|
||||
fn the_document_filter_counts_type_in_graph_designs() {
|
||||
let mut app = app_with_type(&["Inter"]);
|
||||
let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Bar", "font": "JetBrains Mono"})).unwrap()["id"].as_u64().unwrap();
|
||||
let art = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type");
|
||||
app.run("edit.undo", serde_json::json!({})).unwrap();
|
||||
let mut doc = (*app.session.active().unwrap().doc).clone();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
assert!(!super::document_families(db, &doc).contains("jetbrains mono"));
|
||||
doc.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bars".into(), art: std::sync::Arc::new(art) });
|
||||
let mut names: Vec<_> = super::document_families(db, &doc).into_iter().collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["inter", "jetbrains mono"]);
|
||||
}
|
||||
|
||||
/// A run whose family and style were split from a PostScript name (as an importer without the font
|
||||
/// splits one) counts under the family of the installed font of that name, found with its style.
|
||||
#[test]
|
||||
fn the_document_filter_finds_a_postscript_name_split_into_family_and_style() {
|
||||
let mut app = app_with_type(&[]);
|
||||
let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Split", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
|
||||
let mut art = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type");
|
||||
app.run("edit.undo", serde_json::json!({})).unwrap();
|
||||
let vectorcraft_doc::NodeKind::Text(t) = &mut art.kind else { panic!("type") };
|
||||
for r in &mut t.runs {
|
||||
// SourceSans3-Semibold, split after "Semi".
|
||||
r.style.font_family = "SourceSans3Semi".into();
|
||||
r.style.font_style = "bold".into();
|
||||
}
|
||||
let mut doc = (*app.session.active().unwrap().doc).clone();
|
||||
doc.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Split".into(), art: std::sync::Arc::new(art) });
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let names: Vec<_> = super::document_families(db, &doc).into_iter().collect();
|
||||
assert_eq!(names, ["source sans 3"]);
|
||||
}
|
||||
|
||||
/// The Document filter combines with the others and with Recent Fonts, follows edits and undo
|
||||
/// without the menu reopening, and steers the closed field's wheel.
|
||||
#[test]
|
||||
fn the_document_filter_combines_with_the_others_and_follows_edits() {
|
||||
let mut app = app_with_type(&["Inter", "Source Serif 4"]);
|
||||
let ctx = egui::Context::default();
|
||||
let mut st = super::MenuState { document_only: true, favorites_only: true, ..Default::default() };
|
||||
let favorites = vec!["Inter".to_string(), "Source Sans 3".to_string()];
|
||||
let recent = vec!["Source Sans 3".to_string(), "Source Serif 4".to_string()];
|
||||
let frames = |app: &crate::VectorcraftApp, st: &mut super::MenuState| {
|
||||
let look = super::MenuLook { samples: false, favorites: &favorites, recent: &recent, ..super::MenuLook::of(app) };
|
||||
for _ in 0..2 {
|
||||
menu_frame(&ctx, st, look, vec![]);
|
||||
}
|
||||
};
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(listed_families(&st), ["Inter"], "favorites the document uses");
|
||||
st.favorites_only = false;
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(st.rows.first(), Some(&Row::Heading("Recent Fonts")));
|
||||
assert_eq!(listed_families(&st), ["Source Serif 4", "Inter"], "only the recent family the document uses comes first");
|
||||
app.run("text.create", serde_json::json!({"x": 20, "y": 120, "text": "New", "font": "Source Sans 3"})).unwrap();
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(listed_families(&st), ["Source Sans 3", "Source Serif 4", "Inter"], "an edit lists the new family");
|
||||
app.run("edit.undo", serde_json::json!({})).unwrap();
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(listed_families(&st), ["Source Serif 4", "Inter"], "undo takes it out again");
|
||||
let look = super::MenuLook { samples: false, recent: &recent, ..super::MenuLook::of(&app) };
|
||||
assert_eq!(super::wheel_order(&mut st, look), ["Source Serif 4", "Inter"], "the wheel steps through the same families");
|
||||
}
|
||||
|
||||
/// A font previewed from the menu does not change what the Document filter lists: the family the
|
||||
/// previewed text had stays listed, though no other type uses it. A pick lists the families again.
|
||||
#[test]
|
||||
fn a_preview_keeps_the_document_filters_families() {
|
||||
let mut app = app_with_type(&["Source Serif 4", "Inter"]);
|
||||
let ctx = egui::Context::default();
|
||||
let mut st = super::MenuState { document_only: true, ..Default::default() };
|
||||
let frames = |app: &crate::VectorcraftApp, st: &mut super::MenuState| {
|
||||
let look = super::MenuLook { samples: false, recent: &[], ..super::MenuLook::of(app) };
|
||||
for _ in 0..2 {
|
||||
menu_frame(&ctx, st, look, vec![]);
|
||||
}
|
||||
};
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(listed_families(&st), ["Inter", "Source Serif 4"]);
|
||||
// The selected text, the only type in Inter, previewed in Source Serif 4.
|
||||
super::apply(&mut app, &ctx, super::FontPick::Preview("Source Serif 4".into(), None));
|
||||
assert!(app.session.active().unwrap().interaction.is_some(), "the preview is open");
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(listed_families(&st), ["Inter", "Source Serif 4"], "the preview leaves the list as it was");
|
||||
super::apply(&mut app, &ctx, super::FontPick::Preview("Inter".into(), None));
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(listed_families(&st), ["Inter", "Source Serif 4"], "previewing back changes nothing");
|
||||
super::apply(&mut app, &ctx, super::FontPick::Chosen("Source Serif 4".into(), None));
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(listed_families(&st), ["Source Serif 4"], "the pick is an edit: Inter is no longer used");
|
||||
app.run("edit.undo", serde_json::json!({})).unwrap();
|
||||
frames(&app, &mut st);
|
||||
assert_eq!(listed_families(&st), ["Inter", "Source Serif 4"], "undo lists it again");
|
||||
}
|
||||
|
||||
/// The Document filter on a document without type lists nothing and says why; without a document
|
||||
/// it is unavailable and lists every family; the filter is shared like the others.
|
||||
#[test]
|
||||
fn the_document_filter_on_an_empty_document_or_none() {
|
||||
let app = app_with_type(&[]);
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut st = super::MenuState { document_only: true, ..Default::default() };
|
||||
let look = super::MenuLook { samples: false, ..super::MenuLook::of(&app) };
|
||||
let mut shapes = vec![];
|
||||
for _ in 0..3 {
|
||||
shapes = menu_frame(&ctx, &mut st, look, vec![]);
|
||||
}
|
||||
assert!(st.rows.is_empty(), "{:?}", st.rows);
|
||||
assert!(text_at(&shapes, |t| t == "This document uses no available fonts").is_some(), "the filter says the list is empty because of it");
|
||||
// A search that matches nothing still says so in its own words.
|
||||
st.document_only = false;
|
||||
shapes = menu_frame(&ctx, &mut st, look, vec![egui::Event::Text("NoSuchFontFor7059".into())]);
|
||||
shapes = if st.rows.is_empty() { menu_frame(&ctx, &mut st, look, vec![]) } else { shapes };
|
||||
assert!(text_at(&shapes, |t| t == "No matching fonts").is_some());
|
||||
// No document: the filter, kept on, lists every family.
|
||||
let mut st = super::MenuState { document_only: true, ..Default::default() };
|
||||
let none = egui::Context::default();
|
||||
for _ in 0..3 {
|
||||
menu_frame(&none, &mut st, super::MenuLook { samples: false, ..Default::default() }, vec![]);
|
||||
}
|
||||
assert!(st.document_only && !listed_families(&st).is_empty(), "no document: every family");
|
||||
let mut other = super::MenuState::default();
|
||||
super::Filters::of(&st).apply(&mut other);
|
||||
assert!(other.document_only, "every font menu shares the filter");
|
||||
}
|
||||
|
||||
/// A fixed time the Recently Added tests count from.
|
||||
fn clock() -> std::time::SystemTime {
|
||||
std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000)
|
||||
}
|
||||
|
||||
const DAY: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
|
||||
|
||||
/// The Recently Added filter's list of `families` (newest first), as found in `db` at [`clock`],
|
||||
/// to be found again from `recheck_at` on.
|
||||
fn added_in(db: &vectorcraft_text::FontDb, families: &[&str], recheck_at: Option<std::time::SystemTime>) -> Option<super::RecentlyAddedFonts> {
|
||||
let list = vectorcraft_text::RecentlyAdded { families: families.iter().map(|f| f.to_string()).collect(), recheck_at };
|
||||
// The font folders' first scan changes the generation: it runs before the generation is read.
|
||||
db.family_list();
|
||||
Some(((db.id(), db.generation()), clock(), std::sync::Arc::new(super::AddedFonts::of(&list))))
|
||||
}
|
||||
|
||||
/// Draws the open menu of the families in `db` twice for `look` under the filters of `st`, with
|
||||
/// `events` in the first pass; returns the shapes of the second.
|
||||
fn settle_menu_of(
|
||||
ctx: &egui::Context,
|
||||
db: &vectorcraft_text::FontDb,
|
||||
st: &mut super::MenuState,
|
||||
look: super::MenuLook,
|
||||
events: Vec<egui::Event>,
|
||||
) -> Vec<egui::epaint::ClippedShape> {
|
||||
let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 900.0));
|
||||
let mut shapes = vec![];
|
||||
for events in [events, vec![]] {
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| {
|
||||
let _ = super::list_of(ui, db, egui::Id::unique("recently-added"), st, "Inter", None, look);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
shapes = out.shapes;
|
||||
}
|
||||
shapes
|
||||
}
|
||||
|
||||
/// The Recently Added filter lists only the families added recently, the newest first and without
|
||||
/// the Recent Fonts section, the recent family among them; it combines with the ★ filter and the
|
||||
/// search, Show Similar Fonts orders what it lists, and the closed field's wheel follows its order.
|
||||
#[test]
|
||||
fn the_recently_added_filter_lists_new_families_newest_first() {
|
||||
// The bundled fonts alone: fonts that tests running alongside add stay out of the rows.
|
||||
let db = vectorcraft_text::FontDb::with_font_dirs(vec![]);
|
||||
let ctx = egui::Context::default();
|
||||
let recent = vec!["Inter".to_string()];
|
||||
let favorites = vec!["Inter".to_string(), "Source Serif 4".to_string()];
|
||||
let look = super::MenuLook { samples: false, recent: &recent, clock: Some(clock()), ..Default::default() };
|
||||
let newest_first = ["Source Serif 4", "JetBrains Mono", "Inter"];
|
||||
let mut st = super::MenuState { added_only: true, added: added_in(&db, &newest_first, None), ..Default::default() };
|
||||
settle_menu_of(&ctx, &db, &mut st, look, vec![]);
|
||||
assert_eq!(listed_families(&st), newest_first, "newest first, the recent family among them");
|
||||
assert!(!st.rows.iter().any(|r| matches!(r, Row::Heading(_))), "no Recent Fonts section: {:?}", st.rows);
|
||||
assert_eq!(super::wheel_order_in(&db, &mut st, look), newest_first, "the wheel steps through the same families");
|
||||
st.favorites_only = true;
|
||||
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { favorites: &favorites, ..look }, vec![]);
|
||||
assert_eq!(listed_families(&st), ["Source Serif 4", "Inter"], "only the favorites among them");
|
||||
st.favorites_only = false;
|
||||
st.similar = Some("Inter".into());
|
||||
settle_menu_of(&ctx, &db, &mut st, look, vec![]);
|
||||
let listed: Vec<String> = newest_first.iter().map(|f| f.to_string()).collect();
|
||||
assert_eq!(listed_families(&st), db.similar_families("Inter", &listed), "Show Similar Fonts orders only these");
|
||||
st.similar = None;
|
||||
settle_menu_of(&ctx, &db, &mut st, look, vec![]);
|
||||
assert_eq!(listed_families(&st), newest_first, "newest first again once it is cleared");
|
||||
settle_menu_of(&ctx, &db, &mut st, look, vec![egui::Event::Text("mono".into())]);
|
||||
assert_eq!(listed_families(&st), ["JetBrains Mono"], "the search narrows the list");
|
||||
}
|
||||
|
||||
/// A family leaves the list when its 30 days end, while the menu is open; with none left the
|
||||
/// filter stays on and the menu says nothing matches. Its chip turns it off, and every font menu
|
||||
/// shares it.
|
||||
#[test]
|
||||
fn the_recently_added_filter_drops_families_as_their_30_days_end() {
|
||||
let db = vectorcraft_text::FontDb::with_font_dirs(vec![]);
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let look = super::MenuLook { samples: false, clock: Some(clock()), ..Default::default() };
|
||||
let mut st = super::MenuState { added_only: true, added: added_in(&db, &["Inter"], Some(clock() + DAY)), ..Default::default() };
|
||||
settle_menu_of(&ctx, &db, &mut st, look, vec![]);
|
||||
assert_eq!(listed_families(&st), ["Inter"]);
|
||||
let mut other = super::MenuState::default();
|
||||
super::Filters::of(&st).apply(&mut other);
|
||||
assert!(other.added_only, "every font menu shares the filter");
|
||||
let later = super::MenuLook { clock: Some(clock() + DAY), ..look };
|
||||
let shapes = settle_menu_of(&ctx, &db, &mut st, later, vec![]);
|
||||
assert!(st.rows.is_empty(), "{:?}", st.rows);
|
||||
assert!(st.added_only, "the filter stays on");
|
||||
assert!(text_at(&shapes, |t| t == "No matching fonts").is_some(), "the menu says nothing matches");
|
||||
let chip = text_at(&shapes, |t| t == "Recently Added").expect("the Recently Added chip is drawn");
|
||||
let button = |pressed| egui::Event::PointerButton { pos: chip, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
settle_menu_of(&ctx, &db, &mut st, later, vec![egui::Event::PointerMoved(chip), button(true)]);
|
||||
settle_menu_of(&ctx, &db, &mut st, later, vec![button(false)]);
|
||||
assert!(!st.added_only, "the chip turns the filter off");
|
||||
assert!(listed_families(&st).len() > 1, "every family: {:?}", st.rows);
|
||||
}
|
||||
|
||||
/// When the clock goes back before the time the list was found for (the system clock is set back),
|
||||
/// the filter finds its families again rather than keep the list it found.
|
||||
#[test]
|
||||
fn the_recently_added_filter_finds_its_families_again_when_the_clock_goes_back() {
|
||||
// The bundled fonts alone, which are never recently added.
|
||||
let db = vectorcraft_text::FontDb::with_font_dirs(vec![]);
|
||||
let ctx = egui::Context::default();
|
||||
let mut st = super::MenuState { added_only: true, added: added_in(&db, &["Inter"], None), ..Default::default() };
|
||||
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, clock: Some(clock()), ..Default::default() }, vec![]);
|
||||
assert_eq!(listed_families(&st), ["Inter"]);
|
||||
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, clock: Some(clock() - DAY), ..Default::default() }, vec![]);
|
||||
assert!(st.rows.is_empty(), "found again a day earlier: {:?}", st.rows);
|
||||
}
|
||||
|
||||
/// A font file installed just now is recently added by its creation time, and no longer 31 days
|
||||
/// later. Where the file system keeps no creation time, the filter lists nothing.
|
||||
#[test]
|
||||
fn the_recently_added_filter_lists_a_font_installed_just_now() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-font-menu-recently-added-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("SourceSerif4-Regular.ttf");
|
||||
std::fs::copy(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap();
|
||||
let dated = std::fs::metadata(&file).and_then(|m| m.created()).is_ok();
|
||||
let db = vectorcraft_text::FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
let ctx = egui::Context::default();
|
||||
let now = std::time::SystemTime::now();
|
||||
let mut st = super::MenuState { added_only: true, ..Default::default() };
|
||||
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, clock: Some(now), ..Default::default() }, vec![]);
|
||||
let expected: &[&str] = if dated { &["Source Serif 4"] } else { &[] };
|
||||
assert_eq!(listed_families(&st), expected);
|
||||
settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, clock: Some(now + DAY * 31), ..Default::default() }, vec![]);
|
||||
assert!(st.rows.is_empty(), "31 days later: {:?}", st.rows);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -1290,6 +1290,10 @@ font-technology Variable Променливи
|
||||
Font List Списък с шрифтове
|
||||
Show Similar Fonts Показване на подобни шрифтове
|
||||
Clear Similar Fonts Изчистване на подобните шрифтове
|
||||
Fonts used in this document Шрифтове, използвани в този документ
|
||||
This document uses no available fonts Този документ не използва налични шрифтове
|
||||
Recently Added Наскоро добавени
|
||||
Fonts added in the last 30 days Шрифтове, добавени през последните 30 дни
|
||||
Font Preview Size Размер за преглед на шрифта
|
||||
Font Size Размер на шрифта
|
||||
Variable Font Променлив шрифт
|
||||
@@ -6445,6 +6449,7 @@ anchor Points: Точки:
|
||||
Open a document to check it for issues. Отворете документ, за да го проверите за проблеми.
|
||||
Empty Text Празен текст
|
||||
Unpainted Objects Обекти без цвят
|
||||
Empty Text Paths Празни текстови пътища
|
||||
Zero-Opacity Objects Обекти с нулева непрозрачност
|
||||
Duplicate Objects Дублирани обекти
|
||||
Off-Artboard Art Графика извън работните области
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2839,6 +2839,7 @@ digits Malayalam Malajalam
|
||||
Collate Složi po kopijama
|
||||
Composite colours are converted to it; separations separate with it when it is a CMYK profile. Kompozitne boje se pretvaraju u njega; separacije se razdvajaju njime kad je CMYK profil.
|
||||
Convert All Spot Colors to Process Pretvori sve spot boje u procesne
|
||||
Overprint Black Pretisak crne
|
||||
Default Printer Zadani štampač
|
||||
Document Ink Options Opcije tinti dokumenta
|
||||
Download: Preuzimanje:
|
||||
@@ -3612,6 +3613,10 @@ theme Appearance Izgled
|
||||
Font List Lista fontova
|
||||
Show Similar Fonts Prikaži slične fontove
|
||||
Clear Similar Fonts Očisti slične fontove
|
||||
Fonts used in this document Fontovi korišteni u ovom dokumentu
|
||||
This document uses no available fonts Ovaj dokument ne koristi dostupne fontove
|
||||
Recently Added Nedavno dodani
|
||||
Fonts added in the last 30 days Fontovi dodani u posljednjih 30 dana
|
||||
Fonts in Document Fontovi u dokumentu
|
||||
Refresh Font List Osvježi listu fontova
|
||||
Replace Font Zamijeni font
|
||||
@@ -6499,6 +6504,7 @@ anchor Points: Tačke:
|
||||
Open a document to check it for issues. Otvorite dokument da ga provjerite na probleme.
|
||||
Empty Text Prazan tekst
|
||||
Unpainted Objects Neobojeni objekti
|
||||
Empty Text Paths Prazne tekstualne putanje
|
||||
Zero-Opacity Objects Objekti s nultom neprozirnošću
|
||||
Duplicate Objects Duplirani objekti
|
||||
Off-Artboard Art Grafika izvan radne ploče
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1807,6 +1807,10 @@ digits Malayalam Malaiàlam
|
||||
Font List Llista de tipus de lletra
|
||||
Show Similar Fonts Mostra tipus de lletra semblants
|
||||
Clear Similar Fonts Esborra els tipus de lletra semblants
|
||||
Fonts used in this document Tipus de lletra utilitzats en aquest document
|
||||
This document uses no available fonts Aquest document no utilitza cap tipus de lletra disponible
|
||||
Recently Added Afegits recentment
|
||||
Fonts added in the last 30 days Tipus de lletra afegits en els darrers 30 dies
|
||||
Font Preview Size Mida de previsualització del tipus de lletra
|
||||
Font Size Mida del tipus de lletra
|
||||
Font Style: Estil de tipus de lletra:
|
||||
@@ -6053,6 +6057,9 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg no active document no hi ha cap document actiu
|
||||
@msg no active perspective plane no hi ha cap pla de perspectiva actiu
|
||||
@msg no anchor points selected no hi ha cap punt d’ancoratge seleccionat
|
||||
@msg `points` must be three [x, y] pairs of numbers `points` han de ser tres parells de nombres [x, y]
|
||||
@msg direct-select three anchor points, or give `points` seleccioneu directament tres punts d’ancoratge o indiqueu `points`
|
||||
@msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta
|
||||
@msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers
|
||||
@msg no artboard no hi ha tauler
|
||||
@msg no artboard {i} (0-based; the document has {_1}) no hi ha el tauler {i} (basat en 0; el document en té {_1})
|
||||
@@ -7133,6 +7140,7 @@ anchor Points: Punts:
|
||||
Open a document to check it for issues. Obriu un document per revisar-ne els problemes.
|
||||
Empty Text Text buit
|
||||
Unpainted Objects Objectes sense pintura
|
||||
Empty Text Paths Traçats de text buits
|
||||
Zero-Opacity Objects Objectes amb opacitat zero
|
||||
Duplicate Objects Objectes duplicats
|
||||
Off-Artboard Art Art fora dels taulers
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3715,6 +3715,10 @@ theme Appearance Motiv
|
||||
Font List Seznam písem
|
||||
Show Similar Fonts Zobrazit podobná písma
|
||||
Clear Similar Fonts Zrušit podobná písma
|
||||
Fonts used in this document Písma použitá v tomto dokumentu
|
||||
This document uses no available fonts Tento dokument nepoužívá žádná dostupná písma
|
||||
Recently Added Nedávno přidané
|
||||
Fonts added in the last 30 days Písma přidaná za posledních 30 dní
|
||||
Fonts in Document Písma v dokumentu
|
||||
Refresh Font List Obnovit seznam písem
|
||||
Replace Font Nahradit písmo
|
||||
@@ -5213,6 +5217,9 @@ liquify-list-end {0}, {1} {0} a {1}
|
||||
@msg no active document žádný aktivní dokument
|
||||
@msg no active perspective plane žádná aktivní perspektivní rovina
|
||||
@msg no anchor points selected nejsou vybrány žádné kotevní body
|
||||
@msg `points` must be three [x, y] pairs of numbers `points` musí být tři dvojice čísel [x, y]
|
||||
@msg direct-select three anchor points, or give `points` vyberte přímým výběrem tři kotevní body, nebo zadejte `points`
|
||||
@msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce
|
||||
@msg no app to open files here zde chybí aplikace pro otevírání souborů
|
||||
@msg no artboard žádná pracovní plocha
|
||||
@msg no artboard {i} (0-based; the document has {_1}) pracovní plocha {i} neexistuje (číslováno od 0; dokument jich má {_1})
|
||||
@@ -7135,6 +7142,7 @@ anchor Points: Body:
|
||||
Open a document to check it for issues. Otevřete dokument a zkontrolujte jeho problémy.
|
||||
Empty Text Prázdný text
|
||||
Unpainted Objects Objekty bez barvy
|
||||
Empty Text Paths Prázdné textové cesty
|
||||
Zero-Opacity Objects Objekty s nulovým krytím
|
||||
Duplicate Objects Duplicitní objekty
|
||||
Off-Artboard Art Kresba mimo pracovní plochy
|
||||
|
||||
|
Can't render this file because it is too large.
|
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user