mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
Merge main into fix/drop-gradient-hand-workarounds-home-tests
This commit is contained in:
@@ -124,6 +124,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-12-04: Raster Settings OK edits the objects selected when the dialog opened. It keeps the dialog open with the reason if its document is not active, was reverted or had an Undo, a Redo or a canceled edit that put back an earlier state, if a target was changed, deleted, locked or hidden, if another edit is in progress, or if the change is refused. Headline numbers unchanged.
|
||||
- 2026-12-04: Paste from CAD apps: on Windows, Paste reads the enhanced metafile CAD and office apps copy as vector art, and a `.dxf`, `.dwg` or HP-GL plot file copied in a file manager pastes as its drawing through the new command `clipboard.importCad` (#10819). Headline numbers unchanged.
|
||||
|
||||
- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged.
|
||||
|
||||
@@ -196,8 +196,8 @@ USAGE:
|
||||
|
||||
/// The usage text plus the formats `document.open` reads and `document.export` writes.
|
||||
fn usage() -> String {
|
||||
use vectorcraft_engine::cmd::fileio::{OPEN_EXTS, export_extensions};
|
||||
format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", OPEN_EXTS.join(", ."), export_extensions().join(", ."))
|
||||
use vectorcraft_engine::cmd::fileio::{export_extensions, open_exts};
|
||||
format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", open_exts().join(", ."), export_extensions().join(", ."))
|
||||
}
|
||||
|
||||
/// Does a subcommand's `args` ask for the usage? `--help` or `-h` counts where an option goes, not as
|
||||
|
||||
@@ -799,6 +799,10 @@ fn main() -> std::process::ExitCode {
|
||||
// window, so eframe's windows are recorded as it makes and drops them (`quit_windows`).
|
||||
#[cfg(target_os = "linux")]
|
||||
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options };
|
||||
// Floating panels and dialogs that draw their own title bar stay borderless on Windows, as the
|
||||
// main window does (`window_frame`, #10797).
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(window_frame::Hooks)), ..options };
|
||||
#[cfg(feature = "wgpu")]
|
||||
let options = {
|
||||
let mut options = options;
|
||||
|
||||
@@ -22,10 +22,20 @@
|
||||
//! monitor. In PhotoCraft the taskbar then did not show when the pointer reached its edge
|
||||
//! (storytold/photocraft#4845). On each edge with an auto-hidden taskbar the guard stops the window
|
||||
//! one pixel short of the monitor instead, as PhotoCraft does (storytold/photocraft#6878).
|
||||
//!
|
||||
//! Floating panels and dialogs that draw their own title bar (Preferences, a floating Color panel)
|
||||
//! are undecorated winit windows as well, and on the same systems their content was drawn offset
|
||||
//! by the caption and border too (#10797). `Hooks` records those windows as eframe makes them and
|
||||
//! runs the same guard on each one in each of its frames.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
|
||||
/// Run once per frame; a no-op once the window is borderless.
|
||||
pub type WindowFrameFn = Box<dyn FnMut()>;
|
||||
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
pub use platform::Hooks;
|
||||
pub use platform::service;
|
||||
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
@@ -49,6 +59,33 @@ mod platform {
|
||||
Some(Box::new(move || reapply(&hwnd)))
|
||||
}
|
||||
|
||||
/// The undecorated windows of floating panels and dialogs, which [`Hooks`] records.
|
||||
static SECONDARY: std::sync::LazyLock<super::Viewports<HWND>> = std::sync::LazyLock::new(super::Viewports::default);
|
||||
|
||||
/// Keeps the undecorated windows of floating panels and dialogs borderless, as [`service`]
|
||||
/// keeps the main window: the guard runs when eframe makes such a window and before each of its
|
||||
/// frames. Set as [`eframe::NativeOptions::viewport_hooks`].
|
||||
pub struct Hooks;
|
||||
|
||||
impl eframe::ViewportHooks for Hooks {
|
||||
fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) {
|
||||
let hwnd = match window.window_handle().map(|h| h.as_raw()) {
|
||||
Ok(RawWindowHandle::Win32(h)) => find_window(h.hwnd.get()),
|
||||
_ => None,
|
||||
};
|
||||
SECONDARY.created(viewport, window.is_decorated(), hwnd);
|
||||
SECONDARY.with(viewport, reapply);
|
||||
}
|
||||
|
||||
fn window_destroyed(&self, viewport: egui::ViewportId) {
|
||||
SECONDARY.destroyed(viewport);
|
||||
}
|
||||
|
||||
fn raw_input(&self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
SECONDARY.with(raw_input.viewport_id, reapply);
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass of the per-frame guard: the styles winit put back come off again, and a parked
|
||||
/// maximize stays clear of the taskbar.
|
||||
fn reapply(hwnd: &HWND) {
|
||||
@@ -152,6 +189,55 @@ mod platform {
|
||||
}
|
||||
}
|
||||
|
||||
/// The windows of the undecorated floating panels and dialogs, by viewport, while eframe holds
|
||||
/// them. A record holds `None` while [`Viewports::with`] has its window out. Platform-neutral so
|
||||
/// it is tested everywhere.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
struct Viewports<H>(Mutex<HashMap<egui::ViewportId, Option<H>>>);
|
||||
|
||||
impl<H> Default for Viewports<H> {
|
||||
fn default() -> Self {
|
||||
Self(Mutex::new(HashMap::new()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
impl<H> Viewports<H> {
|
||||
/// eframe made `viewport`'s window, with `handle`. It is recorded when it is an undecorated
|
||||
/// window other than the main one, which [`service`] keeps; otherwise any earlier record of the
|
||||
/// viewport is removed, so a window made again with the system title bar is left alone.
|
||||
fn created(&self, viewport: egui::ViewportId, decorated: bool, handle: Option<H>) {
|
||||
let mut windows = self.lock();
|
||||
match handle {
|
||||
Some(handle) if viewport != egui::ViewportId::ROOT && !decorated => windows.insert(viewport, Some(handle)),
|
||||
_ => windows.remove(&viewport),
|
||||
};
|
||||
}
|
||||
|
||||
/// eframe dropped `viewport`'s window.
|
||||
fn destroyed(&self, viewport: egui::ViewportId) {
|
||||
self.lock().remove(&viewport);
|
||||
}
|
||||
|
||||
/// Runs `f` on `viewport`'s recorded window, if any. The window is taken out of its record
|
||||
/// while `f` runs, so window messages that `f` sends and that reach the hooks again do not wait
|
||||
/// on the lock. It goes back only if the record is still there and empty: a window dropped or
|
||||
/// made again for the viewport in the meantime wins.
|
||||
fn with(&self, viewport: egui::ViewportId, f: impl FnOnce(&H)) {
|
||||
let Some(handle) = self.lock().get_mut(&viewport).and_then(Option::take) else {
|
||||
return;
|
||||
};
|
||||
f(&handle);
|
||||
if let Some(slot @ None) = self.lock().get_mut(&viewport) {
|
||||
*slot = Some(handle);
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, HashMap<egui::ViewportId, Option<H>>> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about
|
||||
/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being
|
||||
/// dragged or snapped, and is left alone.
|
||||
@@ -260,7 +346,64 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
|
||||
use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
|
||||
|
||||
fn viewport(name: &str) -> egui::ViewportId {
|
||||
egui::ViewportId::from_hash_of(name)
|
||||
}
|
||||
|
||||
/// The windows `with` reaches for each viewport, in order.
|
||||
fn reached(windows: &Viewports<u32>, viewports: &[egui::ViewportId]) -> Vec<Option<u32>> {
|
||||
viewports
|
||||
.iter()
|
||||
.map(|&id| {
|
||||
let mut seen = None;
|
||||
windows.with(id, |&h| seen = Some(h));
|
||||
seen
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Floating panels and dialogs with their own title bar are kept borderless (#10797); the main
|
||||
/// window, which `service` keeps, and windows with the system title bar are not recorded.
|
||||
#[test]
|
||||
fn undecorated_floating_windows_are_recorded_until_dropped() {
|
||||
let windows = Viewports::default();
|
||||
let (prefs, color, hang) = (viewport("Preferences"), viewport("Color"), viewport("Not responding"));
|
||||
windows.created(egui::ViewportId::ROOT, false, Some(1));
|
||||
windows.created(prefs, false, Some(7));
|
||||
windows.created(color, false, Some(9));
|
||||
windows.created(hang, true, Some(11));
|
||||
assert_eq!(reached(&windows, &[egui::ViewportId::ROOT, prefs, color, hang]), [None, Some(7), Some(9), None]);
|
||||
// Each frame reaches the window again.
|
||||
assert_eq!(reached(&windows, &[prefs]), [Some(7)]);
|
||||
windows.destroyed(prefs);
|
||||
assert_eq!(reached(&windows, &[prefs, color]), [None, Some(9)]);
|
||||
// A window made again with the system title bar, or without a handle, is left alone.
|
||||
windows.created(color, true, Some(13));
|
||||
assert_eq!(reached(&windows, &[color]), [None]);
|
||||
windows.created(color, false, Some(15));
|
||||
windows.created(color, false, None);
|
||||
assert_eq!(reached(&windows, &[color]), [None]);
|
||||
}
|
||||
|
||||
/// A window dropped or made again while the guard runs on the old one is not brought back.
|
||||
#[test]
|
||||
fn a_window_dropped_or_made_again_during_the_guard_wins() {
|
||||
let windows = Viewports::default();
|
||||
let prefs = viewport("Preferences");
|
||||
windows.created(prefs, false, Some(7));
|
||||
windows.with(prefs, |_| windows.destroyed(prefs));
|
||||
assert_eq!(reached(&windows, &[prefs]), [None]);
|
||||
windows.created(prefs, false, Some(7));
|
||||
windows.with(prefs, |_| windows.created(prefs, false, Some(8)));
|
||||
assert_eq!(reached(&windows, &[prefs]), [Some(8)]);
|
||||
// The guard can reach the hooks again for the same viewport without waiting on itself.
|
||||
let mut inner = None;
|
||||
windows.with(prefs, |_| windows.with(prefs, |&h| inner = Some(h)));
|
||||
assert_eq!(inner, None);
|
||||
assert_eq!(reached(&windows, &[prefs]), [Some(8)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() {
|
||||
|
||||
@@ -13,6 +13,9 @@ use web_time::Instant;
|
||||
|
||||
pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker};
|
||||
|
||||
/// Whether this build decodes DWG drawings. Web builds and FreeBSD on 64-bit ARM have no DWG decoder.
|
||||
pub const DECODES: bool = !cfg!(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")));
|
||||
|
||||
/// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch
|
||||
/// ([`use_own_worker_for`]).
|
||||
const WORKER_UNTIL_ARG: &str = "--dwg-worker-until";
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! or with the drawing's origin on the artboard's bottom-left corner. Each DXF layer holding art
|
||||
//! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on
|
||||
//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid
|
||||
//! hatches and solids become paths; text and multiline text point type; named blocks symbols
|
||||
//! hatches, solids and regions become paths; text and multiline text point type; named blocks symbols
|
||||
//! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour),
|
||||
//! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve
|
||||
//! them. What can't come in is listed in the warnings.
|
||||
@@ -16,8 +16,10 @@
|
||||
//! - `entity`: entities to items (geometry and properties).
|
||||
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
|
||||
//! - `text`: text values to plain text.
|
||||
//! - `acis`: a region's solid-modeler data as its outline.
|
||||
//! - `build`: items to the document.
|
||||
|
||||
mod acis;
|
||||
mod build;
|
||||
mod curve;
|
||||
mod entity;
|
||||
@@ -237,3 +239,5 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_dwg;
|
||||
#[cfg(test)]
|
||||
mod tests_region;
|
||||
|
||||
@@ -0,0 +1,779 @@
|
||||
//! The solid-modeler data of a REGION as a filled outline: each face's loops of edges, in world x
|
||||
//! and y (drawing units). The data comes as text (DXF before 2013, ciphered or not) or binary
|
||||
//! (DXF 2013 and later keep it in the ACDSDATA section).
|
||||
//!
|
||||
//! The model is a list of records pointing at each other: a body holds lumps, a lump shells, a
|
||||
//! shell faces, a face loops, a loop a ring of coedges. Each coedge uses an edge (forward or
|
||||
//! reversed), and each edge runs between two vertices along a line, an ellipse or a spline. A
|
||||
//! curve of any other kind comes in as a straight line between its vertices.
|
||||
//!
|
||||
//! The REGION groups are in the DXF Reference
|
||||
//! (<https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4>); which
|
||||
//! DXF versions hold text and which binary data is in <https://ezdxf.mozman.at/docs/acis.html>.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use kurbo::{BezPath, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg};
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
|
||||
use super::curve;
|
||||
|
||||
/// The most bytes of one region's data read.
|
||||
pub(crate) const MAX_BYTES: usize = 16 << 20;
|
||||
/// The most records one region's outline may visit: bodies, lumps, shells, faces and coedges
|
||||
/// (a loop counts as one at least).
|
||||
const MAX_VISITS: usize = 1_000_000;
|
||||
/// The first bytes of binary data: ACIS's, or ASM's (DXF 2018 writes either).
|
||||
const BINARY_MAGIC: [&[u8]; 2] = [b"ACIS BinaryFile", b"ASM BinaryFile4"];
|
||||
/// From this version on, every record starts with its attribute, a history number and one more
|
||||
/// pointer; before it, with its attribute alone.
|
||||
const LONG_HEADER_VERSION: u32 = 700;
|
||||
|
||||
type P3 = [f64; 3];
|
||||
/// A B-spline: degree, knots, control points, weights (none: all 1).
|
||||
type Spline = (usize, Vec<f64>, Vec<P3>, Option<Vec<f64>>);
|
||||
|
||||
/// One value of a record.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Tok {
|
||||
Ptr(i64),
|
||||
Num(f64),
|
||||
Word(String),
|
||||
/// `forward` (false) or `reversed` (true).
|
||||
Sense(bool),
|
||||
Open,
|
||||
Close,
|
||||
}
|
||||
|
||||
/// A record: its type (`body`, `plane-surface`…) and its values after the ones every record
|
||||
/// starts with.
|
||||
#[derive(Debug)]
|
||||
struct Rec {
|
||||
kind: String,
|
||||
toks: Vec<Tok>,
|
||||
}
|
||||
|
||||
impl Rec {
|
||||
/// The type `base` or one derived from it (`tedge-edge` is an edge).
|
||||
fn is(&self, base: &str) -> bool {
|
||||
self.kind == base || self.kind.strip_suffix(base).is_some_and(|k| k.ends_with('-'))
|
||||
}
|
||||
|
||||
/// The `n`th pointer (-1: none).
|
||||
fn ptr(&self, n: usize) -> i64 {
|
||||
self.toks.iter().filter_map(|t| if let Tok::Ptr(p) = t { Some(*p) } else { None }).nth(n).unwrap_or(-1)
|
||||
}
|
||||
|
||||
/// The sense right after the `n`th pointer: true when reversed (old files write 1).
|
||||
fn sense_after(&self, n: usize) -> Option<bool> {
|
||||
let mut ptrs = 0;
|
||||
for t in &self.toks {
|
||||
if ptrs > n {
|
||||
return match t {
|
||||
Tok::Sense(r) => Some(*r),
|
||||
Tok::Num(v) if v.is_finite() => Some(*v != 0.0),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if matches!(t, Tok::Ptr(_)) {
|
||||
ptrs += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The numbers, in order.
|
||||
fn nums(&self) -> Vec<f64> {
|
||||
self.toks.iter().filter_map(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The records of one body, and how pointers find them.
|
||||
struct Model {
|
||||
recs: Vec<Rec>,
|
||||
/// Record number by index, when the records carry their own.
|
||||
at: HashMap<i64, usize>,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
fn get(&self, p: i64) -> Option<&Rec> {
|
||||
if p < 0 {
|
||||
return None;
|
||||
}
|
||||
if self.at.is_empty() { self.recs.get(usize::try_from(p).ok()?) } else { self.recs.get(*self.at.get(&p)?) }
|
||||
}
|
||||
|
||||
/// The record `p` points at when it is of type `base`.
|
||||
fn get_is(&self, p: i64, base: &str) -> Option<&Rec> {
|
||||
self.get(p).filter(|r| r.is(base))
|
||||
}
|
||||
|
||||
/// The records of type `base` from `first` along their `next` pointer (pointer `next`), each
|
||||
/// once. Missing records, wrong types and cycles outside coedge rings set `broken`.
|
||||
fn chain(&self, first: i64, base: &str, next: usize, broken: &mut bool) -> Vec<&Rec> {
|
||||
let mut out = vec![];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut p = first;
|
||||
while p >= 0 {
|
||||
if !seen.insert(p) {
|
||||
*broken |= base != "coedge";
|
||||
break;
|
||||
}
|
||||
let Some(r) = self.get_is(p, base) else {
|
||||
*broken = true;
|
||||
break;
|
||||
};
|
||||
out.push(r);
|
||||
p = r.ptr(next);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A region's outline: its faces' loops, closed; `approximated` when an edge of a curve type
|
||||
/// this reader doesn't draw came in as a straight line; `broken` when a topology chain breaks
|
||||
/// off or a loop's ring of coedges doesn't come back to its first; `ambiguous` when an edge's
|
||||
/// endpoint lies on separate parts of its curve.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Outline {
|
||||
pub path: BezPath,
|
||||
pub approximated: bool,
|
||||
pub broken: bool,
|
||||
pub ambiguous: bool,
|
||||
}
|
||||
|
||||
/// Text data, ciphered as DXF writes it or not.
|
||||
pub(crate) fn from_text(text: &str) -> Option<Outline> {
|
||||
if text.len() > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let plain;
|
||||
let text = if text.trim_start().starts_with(|c: char| c.is_ascii_digit()) {
|
||||
text
|
||||
} else {
|
||||
plain = decipher(text);
|
||||
&plain
|
||||
};
|
||||
outline(&sat_model(text)?)
|
||||
}
|
||||
|
||||
/// Binary data.
|
||||
pub(crate) fn from_binary(bytes: &[u8]) -> Option<Outline> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
outline(&sab_model(bytes)?)
|
||||
}
|
||||
|
||||
/// DXF's cipher of text data undone: each printable character is mapped back, and the space
|
||||
/// written after a mapped `A` (a caret, which DXF reads as a control code) is dropped.
|
||||
fn decipher(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut chars = s.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
out.push(match c {
|
||||
' ' | '\n' | '\r' | '\t' => c,
|
||||
'@'..='_' => char::from(159 - c as u8),
|
||||
c if c.is_ascii() && !c.is_ascii_control() => char::from(c as u8 ^ 0x5F),
|
||||
c => c,
|
||||
});
|
||||
if c == '^' && chars.peek() == Some(&' ') {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many values every record starts with in data of `version`.
|
||||
fn header_len(version: u32) -> usize {
|
||||
if version >= LONG_HEADER_VERSION { 3 } else { 1 }
|
||||
}
|
||||
|
||||
/// A text value as a value.
|
||||
fn sat_tok(w: &str) -> Tok {
|
||||
match w {
|
||||
"{" => Tok::Open,
|
||||
"}" => Tok::Close,
|
||||
"forward" | "forward_v" => Tok::Sense(false),
|
||||
"reversed" | "reversed_v" => Tok::Sense(true),
|
||||
_ => {
|
||||
if let Some(p) = w.strip_prefix('$').and_then(|p| p.parse::<i64>().ok()) {
|
||||
return Tok::Ptr(p);
|
||||
}
|
||||
match w.parse::<f64>() {
|
||||
Ok(v) if v.is_finite() => Tok::Num(v),
|
||||
_ => Tok::Word(w.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does this line start a record (`[-<index>] <type> $<attribute> …`)?
|
||||
fn starts_record(line: &str) -> bool {
|
||||
let mut words = line.split_whitespace();
|
||||
let first = words.next().unwrap_or_default();
|
||||
let (kind, next) = if first.starts_with('-') && first[1..].parse::<u64>().is_ok() {
|
||||
(words.next().unwrap_or_default(), words.next().unwrap_or_default())
|
||||
} else {
|
||||
(first, words.next().unwrap_or_default())
|
||||
};
|
||||
kind.starts_with(|c: char| c.is_ascii_alphabetic()) && next.starts_with('$')
|
||||
}
|
||||
|
||||
/// Text data's records: a version line, product and tolerance lines, then records ending in `#`.
|
||||
fn sat_model(text: &str) -> Option<Model> {
|
||||
let version = text.split_whitespace().next()?.parse::<f64>().ok().filter(|v| v.is_finite() && *v >= 0.0)? as u32;
|
||||
let skip = header_len(version);
|
||||
let mut offset = text.find('\n')? + 1;
|
||||
let start = loop {
|
||||
let rest = text.get(offset..)?;
|
||||
let line = rest.split('\n').next().unwrap_or_default();
|
||||
if starts_record(line) {
|
||||
break offset;
|
||||
}
|
||||
offset += line.len() + 1;
|
||||
};
|
||||
let body = text.get(start..)?;
|
||||
let (mut recs, mut at) = (Vec::new(), HashMap::new());
|
||||
let mut cur: Vec<Tok> = vec![];
|
||||
let (mut kind, mut index): (Option<String>, Option<i64>) = (None, None);
|
||||
let mut i = 0;
|
||||
let b = body.as_bytes();
|
||||
while i < b.len() {
|
||||
if b[i].is_ascii_whitespace() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let end = b[i..].iter().position(u8::is_ascii_whitespace).map_or(b.len(), |n| i + n);
|
||||
let word = body.get(i..end)?;
|
||||
i = end;
|
||||
// A counted string: `@<n>`, a space, then n bytes.
|
||||
if let Some(n) = word.strip_prefix('@').and_then(|n| n.parse::<usize>().ok()) {
|
||||
let from = (i + 1).min(b.len());
|
||||
let to = from.checked_add(n)?.min(b.len());
|
||||
cur.push(Tok::Word(body.get(from..to)?.to_string()));
|
||||
i = to;
|
||||
continue;
|
||||
}
|
||||
let (word, ends) = match word.strip_suffix('#') {
|
||||
Some(w) => (w, true),
|
||||
None => (word, false),
|
||||
};
|
||||
if !word.is_empty() {
|
||||
match &kind {
|
||||
None if index.is_none() && word.starts_with('-') && word[1..].parse::<i64>().is_ok() => {
|
||||
index = word[1..].parse().ok();
|
||||
}
|
||||
None => {
|
||||
if word.starts_with("End-of-") || word.starts_with("Begin-of-") {
|
||||
break;
|
||||
}
|
||||
kind = Some(word.to_string());
|
||||
}
|
||||
Some(_) => cur.push(sat_tok(word)),
|
||||
}
|
||||
}
|
||||
if ends {
|
||||
let toks = cur.split_off(skip.min(cur.len()));
|
||||
cur.clear();
|
||||
if let Some(n) = index.take() {
|
||||
at.insert(n, recs.len());
|
||||
}
|
||||
recs.push(Rec { kind: kind.take().unwrap_or_default(), toks });
|
||||
}
|
||||
}
|
||||
Some(Model { recs, at })
|
||||
}
|
||||
|
||||
/// Reads binary data's little-endian values.
|
||||
struct Bytes<'b> {
|
||||
b: &'b [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Bytes<'_> {
|
||||
fn take(&mut self, n: usize) -> Option<&[u8]> {
|
||||
let s = self.b.get(self.i..self.i.checked_add(n)?)?;
|
||||
self.i += n;
|
||||
Some(s)
|
||||
}
|
||||
fn u8(&mut self) -> Option<u8> {
|
||||
self.take(1).map(|s| s[0])
|
||||
}
|
||||
fn i16(&mut self) -> Option<f64> {
|
||||
self.take(2).map(|s| f64::from(i16::from_le_bytes([s[0], s[1]])))
|
||||
}
|
||||
fn u16(&mut self) -> Option<usize> {
|
||||
self.take(2).map(|s| usize::from(u16::from_le_bytes([s[0], s[1]])))
|
||||
}
|
||||
fn i32(&mut self) -> Option<i32> {
|
||||
self.take(4).map(|s| i32::from_le_bytes([s[0], s[1], s[2], s[3]]))
|
||||
}
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
self.take(4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
|
||||
}
|
||||
fn f64(&mut self) -> Option<f64> {
|
||||
let s = self.take(8)?;
|
||||
Some(f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]))
|
||||
}
|
||||
fn text(&mut self, n: usize) -> Option<String> {
|
||||
self.take(n).map(|s| String::from_utf8_lossy(s).into_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Binary data's records: the magic, four numbers (version first), product and tolerance values,
|
||||
/// then records of tagged values, each type name made of its parts.
|
||||
fn sab_model(b: &[u8]) -> Option<Model> {
|
||||
let mut r = Bytes { b: BINARY_MAGIC.iter().find_map(|m| b.strip_prefix(*m))?, i: 0 };
|
||||
let version = r.u32()?;
|
||||
r.take(12)?;
|
||||
let skip = header_len(version);
|
||||
let mut recs = vec![];
|
||||
let (mut parts, mut kind, mut cur): (Vec<String>, Option<String>, Vec<Tok>) = (vec![], None, vec![]);
|
||||
while r.i < r.b.len() {
|
||||
let tag = r.u8()?;
|
||||
let tok = match tag {
|
||||
0x02 => Tok::Num(f64::from(i8::from_le_bytes([r.u8()?]))),
|
||||
0x03 => Tok::Num(r.i16()?),
|
||||
0x04 | 0x15 => Tok::Num(f64::from(r.i32()?)),
|
||||
0x05 => Tok::Num(f64::from(f32::from_le_bytes(r.take(4)?.try_into().ok()?))),
|
||||
0x06 | 0x17 => Tok::Num(r.f64()?),
|
||||
0x07 => {
|
||||
let n = usize::from(r.u8()?);
|
||||
Tok::Word(r.text(n)?)
|
||||
}
|
||||
0x08 => {
|
||||
let n = r.u16()?;
|
||||
Tok::Word(r.text(n)?)
|
||||
}
|
||||
0x09 | 0x12 => {
|
||||
let n = usize::try_from(r.u32()?).ok()?;
|
||||
Tok::Word(r.text(n)?)
|
||||
}
|
||||
0x0A => Tok::Sense(true),
|
||||
0x0B => Tok::Sense(false),
|
||||
0x0C => Tok::Ptr(i64::from(r.i32()?)),
|
||||
0x0D | 0x0E => {
|
||||
let n = usize::from(r.u8()?);
|
||||
let name = r.text(n)?;
|
||||
if kind.is_some() {
|
||||
Tok::Word(name)
|
||||
} else {
|
||||
parts.push(name);
|
||||
if tag == 0x0D {
|
||||
let k = parts.join("-");
|
||||
parts.clear();
|
||||
if k.starts_with("End-of-") || k.starts_with("Begin-of-") {
|
||||
break;
|
||||
}
|
||||
kind = Some(k);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
0x0F => Tok::Open,
|
||||
0x10 => Tok::Close,
|
||||
0x11 => {
|
||||
if let Some(k) = kind.take() {
|
||||
let toks = cur.split_off(skip.min(cur.len()));
|
||||
recs.push(Rec { kind: k, toks });
|
||||
}
|
||||
cur.clear();
|
||||
continue;
|
||||
}
|
||||
0x13 | 0x14 => {
|
||||
for _ in 0..3 {
|
||||
cur.push(Tok::Num(r.f64()?));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
0x16 => {
|
||||
for _ in 0..2 {
|
||||
cur.push(Tok::Num(r.f64()?));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
// Values before the first record are the header's.
|
||||
if kind.is_some() {
|
||||
cur.push(tok);
|
||||
}
|
||||
}
|
||||
Some(Model { recs, at: HashMap::new() })
|
||||
}
|
||||
|
||||
/// A body's placement: `p · m · scale + t`.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Xf {
|
||||
m: [P3; 3],
|
||||
scale: f64,
|
||||
t: P3,
|
||||
}
|
||||
|
||||
impl Xf {
|
||||
const IDENTITY: Xf = Xf { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], scale: 1.0, t: [0.0; 3] };
|
||||
|
||||
/// A `transform` record's: nine matrix numbers row by row, the translation, the scale.
|
||||
fn read(r: &Rec) -> Option<Xf> {
|
||||
let n: Vec<f64> = r.toks.iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect();
|
||||
if n.iter().any(|v| !v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let v = |i: usize| n.get(i).copied();
|
||||
let row = |i: usize| Some([v(i)?, v(i + 1)?, v(i + 2)?]);
|
||||
let scale = v(12)?;
|
||||
Some(Xf { m: [row(0)?, row(3)?, row(6)?], t: row(9)?, scale })
|
||||
}
|
||||
|
||||
fn vector(&self, p: P3) -> P3 {
|
||||
let [a, b, c] = self.m;
|
||||
std::array::from_fn(|i| (p[0] * a[i] + p[1] * b[i] + p[2] * c[i]) * self.scale)
|
||||
}
|
||||
|
||||
fn point(&self, p: P3) -> P3 {
|
||||
let v = self.vector(p);
|
||||
std::array::from_fn(|i| v[i] + self.t[i])
|
||||
}
|
||||
}
|
||||
|
||||
/// Seen from above: x and y.
|
||||
fn flat(p: P3) -> Point {
|
||||
Point::new(p[0], p[1])
|
||||
}
|
||||
|
||||
fn sub(a: P3, b: P3) -> P3 {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
|
||||
fn dot(a: P3, b: P3) -> f64 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
|
||||
fn cross(a: P3, b: P3) -> P3 {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
|
||||
fn p3(n: &[f64], i: usize) -> Option<P3> {
|
||||
Some([*n.get(i)?, *n.get(i + 1)?, *n.get(i + 2)?])
|
||||
}
|
||||
|
||||
/// Endpoints farther apart than rounding at their coordinate size allows.
|
||||
fn endpoints_apart(a: Point, b: Point) -> bool {
|
||||
a.distance(b) > 1e-6 * (1.0 + a.x.hypot(a.y).max(b.x.hypot(b.y)))
|
||||
}
|
||||
|
||||
/// Every face's loops of every body, as one path (filled even-odd).
|
||||
fn outline(m: &Model) -> Option<Outline> {
|
||||
let mut o = Outline { path: BezPath::new(), approximated: false, broken: false, ambiguous: false };
|
||||
// Records visited at every level together: chains shared between records are walked again
|
||||
// each time.
|
||||
let mut visits = 0usize;
|
||||
let mut spend = |n: usize| {
|
||||
visits = visits.saturating_add(n.max(1));
|
||||
(visits <= MAX_VISITS).then_some(())
|
||||
};
|
||||
for body in m.recs.iter().filter(|r| r.is("body")) {
|
||||
spend(1)?;
|
||||
let xf = if body.ptr(2) == -1 { Xf::IDENTITY } else { Xf::read(m.get_is(body.ptr(2), "transform")?)? };
|
||||
for lump in m.chain(body.ptr(0), "lump", 0, &mut o.broken) {
|
||||
spend(1)?;
|
||||
for shell in m.chain(lump.ptr(1), "shell", 0, &mut o.broken) {
|
||||
spend(1)?;
|
||||
for face in m.chain(shell.ptr(2), "face", 0, &mut o.broken) {
|
||||
spend(1)?;
|
||||
for lp in m.chain(face.ptr(1), "loop", 0, &mut o.broken) {
|
||||
let ring = m.chain(lp.ptr(1), "coedge", 0, &mut o.broken);
|
||||
spend(ring.len())?;
|
||||
let complete = ring.last().is_some_and(|c| c.ptr(0) == lp.ptr(1));
|
||||
o.broken |= !complete;
|
||||
let mut bp = BezPath::new();
|
||||
for c in ring {
|
||||
let edge = m.get_is(c.ptr(3), "edge")?;
|
||||
let (seg, ambiguous) = edge_path(m, edge, c.sense_after(3)?, &xf, &mut o.approximated)?;
|
||||
o.ambiguous |= ambiguous;
|
||||
if let (Some(end), Some(start)) =
|
||||
(bp.elements().last().and_then(|e| e.end_point()), seg.elements().first().and_then(|e| e.end_point()))
|
||||
{
|
||||
o.broken |= endpoints_apart(end, start);
|
||||
}
|
||||
super::entity::append(&mut bp, &seg);
|
||||
if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if !bp.elements().is_empty() {
|
||||
if complete
|
||||
&& let (Some(end), Some(start)) =
|
||||
(bp.elements().last().and_then(|e| e.end_point()), bp.elements().first().and_then(|e| e.end_point()))
|
||||
{
|
||||
o.broken |= endpoints_apart(end, start);
|
||||
}
|
||||
// A loop of one curve ending where it starts is split in two: as one
|
||||
// segment, its start and end would become one anchor.
|
||||
if let [seg] = bp.segments().collect::<Vec<_>>()[..]
|
||||
&& !matches!(seg, PathSeg::Line(_))
|
||||
{
|
||||
let (a, b) = seg.subdivide();
|
||||
bp = BezPath::from_path_segments([a, b].into_iter());
|
||||
}
|
||||
bp.close_path();
|
||||
if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS {
|
||||
return None;
|
||||
}
|
||||
o.path.extend(bp);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = !o.path.elements().is_empty() && curve::bounds(&o.path).is_some();
|
||||
ok.then_some(o)
|
||||
}
|
||||
|
||||
/// A vertex's position.
|
||||
fn vertex(m: &Model, p: i64) -> Option<P3> {
|
||||
let v = m.get_is(p, "vertex")?;
|
||||
let n = m.get_is(v.ptr(1), "point")?.nums();
|
||||
p3(&n, 0).filter(|p| p.iter().all(|c| c.is_finite()))
|
||||
}
|
||||
|
||||
/// The edge as a coedge runs it (`reversed`: from its end vertex to its start), from the first
|
||||
/// point.
|
||||
fn edge_path(m: &Model, edge: &Rec, reversed: bool, xf: &Xf, approximated: &mut bool) -> Option<(BezPath, bool)> {
|
||||
let (sv, ev) = (vertex(m, edge.ptr(0))?, vertex(m, edge.ptr(1))?);
|
||||
let closed = edge.ptr(0) == edge.ptr(1);
|
||||
let (from, to) = if reversed { (ev, sv) } else { (sv, ev) };
|
||||
// Against the curve's own direction?
|
||||
let back = edge.sense_after(3)? != reversed;
|
||||
let drawn = match m.get(edge.ptr(3)) {
|
||||
// Only -1 means the edge has no curve.
|
||||
None => {
|
||||
*approximated |= edge.ptr(3) != -1;
|
||||
None
|
||||
}
|
||||
Some(c) if c.is("straight-curve") => None,
|
||||
Some(c) => {
|
||||
let bp = if c.is("ellipse-curve") {
|
||||
ellipse(c, from, to, closed, back, xf).map(|bp| (bp, false))
|
||||
} else if c.is("intcurve-curve") {
|
||||
spline(c, from, to, closed, back, xf)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
*approximated |= bp.is_none();
|
||||
bp
|
||||
}
|
||||
};
|
||||
if let Some(bp) = drawn {
|
||||
return Some(bp);
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(flat(xf.point(from)));
|
||||
bp.line_to(flat(xf.point(to)));
|
||||
Some((bp, false))
|
||||
}
|
||||
|
||||
/// An `ellipse-curve` (centre, normal, major axis, ratio) from `from` to `to`; the whole curve
|
||||
/// when the edge starts and ends at one vertex. It runs counter-clockwise about its normal,
|
||||
/// clockwise when `back`.
|
||||
fn ellipse(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<BezPath> {
|
||||
let n = c.nums();
|
||||
let (centre, normal, major, ratio) = (p3(&n, 0)?, p3(&n, 3)?, p3(&n, 6)?, *n.get(9)?);
|
||||
let len = dot(normal, normal).sqrt();
|
||||
if !(len > 1e-12 && ratio > 0.0 && ratio.is_finite() && dot(major, major) > 1e-24) {
|
||||
return None;
|
||||
}
|
||||
let minor = cross(normal, major).map(|v| v / len * ratio);
|
||||
let angle = |p: P3| {
|
||||
let d = sub(p, centre);
|
||||
(dot(d, minor) / dot(minor, minor)).atan2(dot(d, major) / dot(major, major))
|
||||
};
|
||||
let (a, b) = (angle(from), angle(to));
|
||||
let tau = std::f64::consts::TAU;
|
||||
let sweep = match (closed, back) {
|
||||
(true, false) => tau,
|
||||
(true, true) => -tau,
|
||||
(false, false) => (b - a).rem_euclid(tau),
|
||||
(false, true) => -(a - b).rem_euclid(tau),
|
||||
};
|
||||
let (o, u, v) = (flat(xf.point(centre)), flat(xf.vector(major)), flat(xf.vector(minor)));
|
||||
curve::ellipse(Affine::new([u.x, u.y, v.x, v.y, o.x, o.y]), a, sweep)
|
||||
}
|
||||
|
||||
/// An `intcurve-curve`'s B-spline (`nubs`, or `nurbs` with weights): degree, form, the knots
|
||||
/// with their multiplicities (without the end knots, or with them), the control points.
|
||||
fn bspline(toks: &[Tok]) -> Option<Spline> {
|
||||
let at = toks.iter().position(|t| matches!(t, Tok::Word(w) if matches!(w.as_str(), "nubs" | "nurbs" | "nullbs")))?;
|
||||
let rational = match &toks[at] {
|
||||
Tok::Word(w) if w == "nurbs" => true,
|
||||
Tok::Word(w) if w == "nubs" => false,
|
||||
_ => return None,
|
||||
};
|
||||
let num = |i: usize| if let Some(Tok::Num(v)) = toks.get(i) { Some(*v) } else { None };
|
||||
let degree = num(at + 1).filter(|d| (1.0..=32.0).contains(d))? as usize;
|
||||
let count = num(at + 3).filter(|n| *n >= 1.0 && *n <= toks.len() as f64)? as usize;
|
||||
let mut knots = vec![];
|
||||
let mut i = at + 4;
|
||||
for _ in 0..count {
|
||||
let (k, mult) = (num(i)?, num(i + 1)?);
|
||||
if !(mult >= 1.0 && mult <= (degree + 1) as f64) {
|
||||
return None;
|
||||
}
|
||||
knots.extend(std::iter::repeat_n(k, mult as usize));
|
||||
i += 2;
|
||||
}
|
||||
let stride = if rational { 4 } else { 3 };
|
||||
let values: Vec<f64> = toks[i.min(toks.len())..].iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect();
|
||||
let available = values.len() / stride;
|
||||
// The data leaves out the first and last knots; data that keeps them has two points fewer.
|
||||
let short = (knots.len() + 1).checked_sub(degree)?;
|
||||
let n = if available >= short {
|
||||
let (first, last) = (*knots.first()?, *knots.last()?);
|
||||
knots.insert(0, first);
|
||||
knots.push(last);
|
||||
short
|
||||
} else {
|
||||
knots.len().checked_sub(degree + 1)?
|
||||
};
|
||||
if n == 0 || n > available {
|
||||
return None;
|
||||
}
|
||||
let pts = values.chunks(stride).take(n).map(|c| [c[0], c[1], c[2]]).collect();
|
||||
let weights = rational.then(|| values.chunks(stride).take(n).map(|c| c[3]).collect());
|
||||
Some((degree, knots, pts, weights))
|
||||
}
|
||||
|
||||
/// The distinct parameters of a cubic's self-intersection, when both lie on the curve.
|
||||
fn cubic_crossing(cubic: kurbo::CubicBez) -> Option<(f64, f64)> {
|
||||
let b = (cubic.p1 - cubic.p0) * 3.0;
|
||||
let c = (cubic.p2 - cubic.p1) * 3.0 - b;
|
||||
let d = (cubic.p3 - cubic.p0) - b - c;
|
||||
let det = c.cross(d);
|
||||
if det == 0.0 {
|
||||
return None;
|
||||
}
|
||||
// Dividing P(s) - P(t) by s - t gives b + c*u + d*(u*u - v) = 0,
|
||||
// where u = s + t and v = s*t.
|
||||
let u = -b.cross(d) / det;
|
||||
let v = u * u - b.cross(c) / det;
|
||||
let discriminant = u * u - 4.0 * v;
|
||||
if !discriminant.is_finite() || discriminant <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let root = discriminant.sqrt();
|
||||
let (s, t) = ((u - root) * 0.5, (u + root) * 0.5);
|
||||
(0.0 <= s && s < t && t <= 1.0).then_some((s, t))
|
||||
}
|
||||
|
||||
/// An `intcurve-curve` from `from` to `to` (the part of its spline between them), the whole
|
||||
/// ring when the edge starts and ends at one vertex; also whether trimming is ambiguous.
|
||||
fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<(BezPath, bool)> {
|
||||
// The curve's own sense comes before its data.
|
||||
let open = c.toks.iter().position(|t| *t == Tok::Open)?;
|
||||
let curve_back = c.toks[..open].contains(&Tok::Sense(true));
|
||||
let (degree, knots, pts, weights) = bspline(&c.toks[open..])?;
|
||||
let ctrl: Vec<Point> = pts.into_iter().map(|p| flat(xf.point(p))).collect();
|
||||
let full = curve::nurbs(degree, &knots, &ctrl, weights.as_deref())?;
|
||||
let back = back != curve_back;
|
||||
let segs: Vec<PathSeg> = full.segments().collect();
|
||||
let (first, last) = (segs.first()?.start(), segs.last()?.end());
|
||||
let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot());
|
||||
let mut lengths = vec![0.0];
|
||||
for s in &segs {
|
||||
lengths.push(lengths.last()? + s.arclen(1e-9));
|
||||
}
|
||||
let total = *lengths.last()?;
|
||||
let at = |p: P3| {
|
||||
let p = flat(xf.point(p));
|
||||
let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect();
|
||||
let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?;
|
||||
let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9);
|
||||
let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y));
|
||||
let mut locations: Vec<_> =
|
||||
near.iter().filter(|(n, i)| !endpoints_apart(p, segs[*i].eval(n.t))).map(|(n, i)| (*i as f64 + n.t, along(*i, n.t))).collect();
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
if let PathSeg::Cubic(cubic) = s
|
||||
&& let Some((a, b)) = cubic_crossing(*cubic)
|
||||
&& !endpoints_apart(p, cubic.eval(a))
|
||||
{
|
||||
locations.extend([a, b].map(|t| (i as f64 + t, along(i, t))));
|
||||
}
|
||||
}
|
||||
// Nearby ends at a segment joint, or at a closed curve's seam, are one location.
|
||||
locations.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
locations.dedup_by(|a, b| (a.1 - b.1).abs() <= 4.0 * tolerance);
|
||||
if ring && locations.len() > 1 && (total - (locations.last()?.1 - locations.first()?.1)).abs() <= 4.0 * tolerance {
|
||||
locations.pop();
|
||||
}
|
||||
Some((*i as f64 + n.t, locations))
|
||||
};
|
||||
let mut ambiguous = false;
|
||||
let part = if closed && ring {
|
||||
let (_, locations) = at(from)?;
|
||||
ambiguous = locations.len() > 1;
|
||||
full
|
||||
} else {
|
||||
let bounds = if closed {
|
||||
let (_, locations) = at(from)?;
|
||||
if let [a, b] = locations.as_slice() {
|
||||
Some((a.0, b.0))
|
||||
} else {
|
||||
ambiguous = true;
|
||||
None
|
||||
}
|
||||
} else {
|
||||
let ((ga, a), (gb, b)) = (at(from)?, at(to)?);
|
||||
ambiguous = a.len() > 1 || b.len() > 1;
|
||||
Some((ga, gb))
|
||||
};
|
||||
if let Some((ga, gb)) = bounds {
|
||||
let (lo, hi) = if back { (gb, ga) } else { (ga, gb) };
|
||||
let pieces = if lo <= hi || !ring {
|
||||
piece(&segs, lo.min(hi), hi.max(lo))
|
||||
} else {
|
||||
[piece(&segs, lo, segs.len() as f64), piece(&segs, 0.0, hi)].concat()
|
||||
};
|
||||
if pieces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
BezPath::from_path_segments(pieces.into_iter())
|
||||
} else {
|
||||
full
|
||||
}
|
||||
};
|
||||
Some((if back { part.reverse_subpaths() } else { part }, ambiguous))
|
||||
}
|
||||
|
||||
/// The parts of `segs` from `lo` to `hi`, counted in segments (2.5: halfway along the third).
|
||||
fn piece(segs: &[PathSeg], lo: f64, hi: f64) -> Vec<PathSeg> {
|
||||
let mut out = vec![];
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
let (t0, t1) = ((lo - i as f64).max(0.0), (hi - i as f64).min(1.0));
|
||||
if t1 > t0 {
|
||||
out.push(s.subsegment(t0..t1));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cubic_crossings_have_two_distinct_parameters() {
|
||||
let cubic = kurbo::CubicBez::new((36.0, -18.0), (-28.0, 26.0), (-28.0, -26.0), (36.0, 18.0));
|
||||
let (s, t) = cubic_crossing(cubic).unwrap();
|
||||
assert!((s - 0.25).abs() < 1e-12 && (t - 0.75).abs() < 1e-12, "{s}, {t}");
|
||||
let plain = kurbo::CubicBez::new((0.0, 0.0), (30.0, 50.0), (70.0, -50.0), (100.0, 0.0));
|
||||
assert!(cubic_crossing(plain).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deciphering_maps_each_character_back_and_drops_the_caret_space() {
|
||||
// "Ab@_ 7#" ciphered: A→^ (and a space), b→=, @→_, _→@, 7→h, #→|.
|
||||
assert_eq!(decipher("^ =_@ h|"), "Ab@_ 7#");
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ const MAX_NODES: usize = 2_000_000;
|
||||
/// per item of the block looked at for it (art on hidden layers too).
|
||||
const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 };
|
||||
/// The most path elements an import makes (blocks drawn as art are copied for every placement).
|
||||
const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 };
|
||||
pub(crate) const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 };
|
||||
/// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern).
|
||||
const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 };
|
||||
/// The most bytes of text, font names and symbol names an import copies into objects (a block's
|
||||
@@ -128,7 +128,7 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
Self {
|
||||
d,
|
||||
o,
|
||||
conv: Converter::default(),
|
||||
conv: Converter::new(d.regions.clone()),
|
||||
doc: Document::new(1.0, 1.0),
|
||||
blocks: HashMap::new(),
|
||||
bounds: HashMap::new(),
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Entities to drawing items: their geometry in world coordinates (drawing units, y up) and the
|
||||
//! properties they take from their layer or block (resolved when the items become art).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::rc::Rc;
|
||||
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use vectorcraft_doc::Justify;
|
||||
@@ -9,6 +10,7 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
|
||||
|
||||
use super::acis;
|
||||
use super::curve::{self, Vertex};
|
||||
use super::reader::{aci_paper, point};
|
||||
|
||||
@@ -174,6 +176,8 @@ pub(crate) struct Converter {
|
||||
pub warnings: Vec<String>,
|
||||
/// Array insert copies made so far, against [`MAX_TOTAL_CELLS`].
|
||||
cells: i64,
|
||||
/// The binary solid-modeler data of regions, by handle (DXF 2013 and later).
|
||||
regions: Rc<HashMap<u64, Vec<u8>>>,
|
||||
}
|
||||
|
||||
const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries";
|
||||
@@ -182,8 +186,16 @@ const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertic
|
||||
const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each";
|
||||
const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all";
|
||||
const FAR_AWAY: &str = "entities with coordinates out of range are left out";
|
||||
const REGION_CURVES: &str = "region edges of some curve types come in as straight lines";
|
||||
const REGION_BROKEN: &str = "regions whose outlines break off are closed with straight lines";
|
||||
const REGION_AMBIGUOUS: &str = "region edges on curves that cross themselves may come in along the wrong part of the curve";
|
||||
|
||||
impl Converter {
|
||||
/// A converter reading regions' binary data from `regions`.
|
||||
pub fn new(regions: Rc<HashMap<u64, Vec<u8>>>) -> Self {
|
||||
Self { regions, ..Self::default() }
|
||||
}
|
||||
|
||||
fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) {
|
||||
self.warnings.push(w.to_string());
|
||||
@@ -255,6 +267,7 @@ impl Converter {
|
||||
model::EntityKind::Dimension(d) => {
|
||||
Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] }))
|
||||
}
|
||||
_ if e.kind == "REGION" => self.region(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -378,6 +391,41 @@ impl Converter {
|
||||
out
|
||||
}
|
||||
|
||||
/// A region as a filled path: its solid-modeler data as text in groups 1 (a line each) and 3
|
||||
/// (the rest of a long line), or, from DXF 2013 on, binary data kept by handle.
|
||||
fn region(&mut self, e: &EntityRecord<'_>) -> Option<Geom> {
|
||||
let g = e.groups();
|
||||
let own = g.subclass("AcDbModelerGeometry");
|
||||
let tags = if own.0.is_empty() { g.0 } else { own.0 };
|
||||
let mut text = String::new();
|
||||
for t in tags {
|
||||
match t.code {
|
||||
1 => {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(t.str_ref().unwrap_or_default());
|
||||
}
|
||||
3 => text.push_str(t.str_ref().unwrap_or_default()),
|
||||
_ => {}
|
||||
}
|
||||
if text.len() > acis::MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let outline = if text.trim().is_empty() { acis::from_binary(self.regions.get(&e.record().handle()?)?) } else { acis::from_text(&text) }?;
|
||||
if outline.approximated {
|
||||
self.warn(REGION_CURVES);
|
||||
}
|
||||
if outline.broken {
|
||||
self.warn(REGION_BROKEN);
|
||||
}
|
||||
if outline.ambiguous {
|
||||
self.warn(REGION_AMBIGUOUS);
|
||||
}
|
||||
Some(Geom::Path { bp: outline.path, fill: true, width: 0.0 })
|
||||
}
|
||||
|
||||
fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option<Geom> {
|
||||
let mut bp = BezPath::new();
|
||||
for l in &h.loops {
|
||||
@@ -601,7 +649,7 @@ fn boundary(path: &HatchPath) -> Option<BezPath> {
|
||||
}
|
||||
|
||||
/// `seg` continuing `bp`: joined by a line when it starts elsewhere.
|
||||
fn append(bp: &mut BezPath, seg: &BezPath) {
|
||||
pub(super) fn append(bp: &mut BezPath, seg: &BezPath) {
|
||||
for el in seg.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer,
|
||||
//! linetype and text style tables; the blocks; the entities; the layouts.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_dxf::model::{self, EntityRecord};
|
||||
use vectorcraft_geom::Point;
|
||||
@@ -81,6 +82,9 @@ pub(crate) struct Drawing<'a> {
|
||||
pub layouts: Vec<LayoutDef>,
|
||||
/// How many sections the file has (none: not a drawing).
|
||||
pub sections: usize,
|
||||
/// The binary solid-modeler data of the regions, by handle (DXF 2013 and later keep it in
|
||||
/// the ACDSDATA section).
|
||||
pub regions: Rc<HashMap<u64, Vec<u8>>>,
|
||||
}
|
||||
|
||||
/// The colour of index `i` on paper: index 7 (white on a CAD screen) is black.
|
||||
@@ -112,6 +116,7 @@ impl<'a> Drawing<'a> {
|
||||
}
|
||||
let block_names = doc.block_names();
|
||||
d.layouts = layouts(&doc, &block_names);
|
||||
d.regions = Rc::new(region_data(&doc));
|
||||
for b in doc.blocks {
|
||||
if b.name.is_empty() {
|
||||
continue;
|
||||
@@ -148,6 +153,69 @@ impl<'a> Drawing<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The binary data of each region in the ACDSDATA section: an `ACDSRECORD` names its entity's
|
||||
/// handle (320), then holds the bytes (310 chunks) after `2 ASM_Data`, their count in 94.
|
||||
fn region_data(doc: &model::Document<'_>) -> HashMap<u64, Vec<u8>> {
|
||||
let records = doc.entities.iter().chain(doc.blocks.iter().flat_map(|b| &b.entities));
|
||||
let wanted: HashSet<u64> = records.filter(|e| e.kind == "REGION").filter_map(|e| e.record().handle()).collect();
|
||||
let mut out = HashMap::new();
|
||||
if wanted.is_empty() {
|
||||
return out;
|
||||
}
|
||||
for section in doc.other_sections.iter().filter(|s| s.name.eq_ignore_ascii_case("ACDSDATA")) {
|
||||
for r in model::records(section.tags).into_iter().filter(|r| r.kind == "ACDSRECORD") {
|
||||
let Some(handle) = r.tags.iter().find(|t| t.code == 320).and_then(|t| model::parse_handle(&t.str())) else { continue };
|
||||
if !wanted.contains(&handle) || out.contains_key(&handle) {
|
||||
continue;
|
||||
}
|
||||
let Some(at) = r.tags.iter().position(|t| t.code == 2 && t.str_ref().is_some_and(|s| s.trim() == "ASM_Data")) else { continue };
|
||||
let data = r.tags.get(at + 1..).unwrap_or_default();
|
||||
let size = data.iter().find(|t| t.code == 94).and_then(|t| usize::try_from(t.i64()).ok());
|
||||
let mut bytes = Vec::new();
|
||||
let mut whole = true;
|
||||
for t in data.iter().filter(|t| t.code == 310) {
|
||||
whole = hex_bytes(t.str_ref().unwrap_or_default().trim(), &mut bytes);
|
||||
if !whole || bytes.len() > super::acis::MAX_BYTES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !whole {
|
||||
continue;
|
||||
}
|
||||
if let Some(bytes) = sized_region(bytes, size, super::acis::MAX_BYTES) {
|
||||
out.insert(handle, bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A region's `bytes` cut to its declared `size`, or `None` when the record declares more bytes
|
||||
/// than it holds (the data was cut short or damaged) or the data is longer than `limit`.
|
||||
pub(super) fn sized_region(mut bytes: Vec<u8>, size: Option<usize>, limit: usize) -> Option<Vec<u8>> {
|
||||
match size {
|
||||
Some(n) if n <= bytes.len() => bytes.truncate(n),
|
||||
Some(_) => return None,
|
||||
None => {}
|
||||
}
|
||||
(bytes.len() <= limit).then_some(bytes)
|
||||
}
|
||||
|
||||
/// Hex digits' bytes, two digits each, onto `out`. False when `hex` has a character that is not
|
||||
/// a hex digit or an odd number of digits.
|
||||
pub(super) fn hex_bytes(hex: &str, out: &mut Vec<u8>) -> bool {
|
||||
let digit = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok());
|
||||
let (pairs, rest) = hex.as_bytes().as_chunks::<2>();
|
||||
if !rest.is_empty() {
|
||||
return false;
|
||||
}
|
||||
for pair in pairs {
|
||||
let (Some(hi), Some(lo)) = (digit(pair[0]), digit(pair[1])) else { return false };
|
||||
out.push(hi << 4 | lo);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn point(p: model::Point) -> Point {
|
||||
Point::new(p[0], p[1])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,686 @@
|
||||
//! Regions: solid-modeler data in text (ciphered or not, lines split over groups 1 and 3) and in
|
||||
//! binary form (the ACDSDATA section) comes in as one filled path of the region's loops; lines,
|
||||
//! circles, ellipses and spline edges keep their shape, coedge and edge senses are followed, a
|
||||
//! body's transform is applied, and damaged data is left out without hanging.
|
||||
|
||||
use kurbo::{BezPath, Shape};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, Unit};
|
||||
use vectorcraft_geom::{FillRule, Point, Rect};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A curve an edge runs along.
|
||||
#[derive(Clone)]
|
||||
enum Curve {
|
||||
Line,
|
||||
/// A circle about the z axis (`-z`: clockwise) of this centre and radius.
|
||||
Circle {
|
||||
c: [f64; 2],
|
||||
r: f64,
|
||||
down: bool,
|
||||
},
|
||||
/// A curve record's text after its first three values.
|
||||
Raw(String),
|
||||
}
|
||||
|
||||
/// An edge of a loop, from `a` to `b` as the loop runs it. `flip`: the edge is stored from `b`
|
||||
/// to `a` and the coedge runs it reversed; `against`: the edge also runs against its curve.
|
||||
#[derive(Clone)]
|
||||
struct E {
|
||||
a: [f64; 2],
|
||||
b: [f64; 2],
|
||||
curve: Curve,
|
||||
flip: bool,
|
||||
against: bool,
|
||||
}
|
||||
|
||||
fn line(a: [f64; 2], b: [f64; 2]) -> E {
|
||||
E { a, b, curve: Curve::Line, flip: false, against: false }
|
||||
}
|
||||
|
||||
fn circle(c: [f64; 2], r: f64, down: bool) -> E {
|
||||
let p = [c[0] + r, c[1]];
|
||||
E { a: p, b: p, curve: Curve::Circle { c, r, down }, flip: false, against: false }
|
||||
}
|
||||
|
||||
fn square(lo: f64, hi: f64) -> Vec<E> {
|
||||
vec![line([lo, lo], [hi, lo]), line([hi, lo], [hi, hi]), line([hi, hi], [lo, hi]), line([lo, hi], [lo, lo])]
|
||||
}
|
||||
|
||||
/// Text data (version 700) of one face with `loops`, placed by `transform` (12 numbers and a
|
||||
/// scale) when given.
|
||||
fn sat(loops: &[Vec<E>], transform: Option<&str>) -> String {
|
||||
let mut recs: Vec<String> = vec![];
|
||||
let xf = if transform.is_some() { "$5" } else { "$-1" };
|
||||
recs.push(format!("body $-1 -1 $-1 $1 $-1 {xf}"));
|
||||
recs.push("lump $-1 -1 $-1 $-1 $2 $0".into());
|
||||
recs.push("shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1".into());
|
||||
recs.push("face $-1 -1 $-1 $-1 $6 $2 $-1 $4 forward single".into());
|
||||
recs.push("plane-surface $-1 -1 $-1 0 0 0 0 0 1 1 0 0 forward_v I I I I".into());
|
||||
recs.push(format!("transform $-1 -1 $-1 {} no_rotate no_reflect no_shear", transform.unwrap_or("1 0 0 0 1 0 0 0 1 0 0 0 1")));
|
||||
let mut base = 6;
|
||||
for (l, edges) in loops.iter().enumerate() {
|
||||
let next_loop = if l + 1 < loops.len() { format!("${}", base + 1 + 7 * edges.len()) } else { "$-1".into() };
|
||||
recs.push(format!("loop $-1 -1 $-1 {next_loop} ${} $3", base + 1));
|
||||
let n = edges.len();
|
||||
for (j, e) in edges.iter().enumerate() {
|
||||
let at = |k: usize| base + 1 + 7 * k;
|
||||
let i = at(j);
|
||||
let (coedge, edge, sv, ev, sp, ep, cv) = (i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6);
|
||||
let (start, end) = if e.flip { (e.b, e.a) } else { (e.a, e.b) };
|
||||
let ev = if start == end { sv } else { ev };
|
||||
let sense = |r: bool| if r { "reversed" } else { "forward" };
|
||||
recs.push(format!("coedge $-1 -1 $-1 ${} ${} $-1 ${edge} {} ${base} $-1", at((j + 1) % n), at((j + n - 1) % n), sense(e.flip)));
|
||||
recs.push(format!("edge $-1 -1 $-1 ${sv} 0 ${ev} 1 ${coedge} ${cv} {} @7 unknown", sense(e.against)));
|
||||
recs.push(format!("vertex $-1 -1 $-1 ${edge} ${sp}"));
|
||||
recs.push(format!("vertex $-1 -1 $-1 ${edge} ${ep}"));
|
||||
recs.push(format!("point $-1 -1 $-1 {} {} 0", start[0], start[1]));
|
||||
recs.push(format!("point $-1 -1 $-1 {} {} 0", end[0], end[1]));
|
||||
recs.push(match &e.curve {
|
||||
Curve::Line => format!("straight-curve $-1 -1 $-1 {} {} 0 {} {} 0 I I", start[0], start[1], end[0] - start[0], end[1] - start[1]),
|
||||
Curve::Circle { c, r, down } => {
|
||||
format!("ellipse-curve $-1 -1 $-1 {} {} 0 0 0 {} {r} 0 0 1 I I", c[0], c[1], if *down { -1 } else { 1 })
|
||||
}
|
||||
Curve::Raw(s) => s.clone(),
|
||||
});
|
||||
}
|
||||
base += 1 + 7 * n;
|
||||
}
|
||||
let mut s = String::from("700 0 1 0\n9 Synthetic 3 ASM 4 none\n1 9.9999999999999995e-07 1e-10\n");
|
||||
for r in recs {
|
||||
s.push_str(&r);
|
||||
s.push_str(" #\n");
|
||||
}
|
||||
s.push_str("End-of-ACIS-data\n");
|
||||
s
|
||||
}
|
||||
|
||||
/// DXF's cipher of text data: each printable character mapped, a space after each caret.
|
||||
fn encipher(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for c in s.chars() {
|
||||
let m = match c {
|
||||
' ' | '\n' => c,
|
||||
'@'..='_' => char::from(159 - c as u8),
|
||||
c => char::from(c as u8 ^ 0x5F),
|
||||
};
|
||||
out.push(m);
|
||||
if m == '^' {
|
||||
out.push(' ');
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A drawing of `version` with `entities` and, when given, an ACDSDATA section.
|
||||
fn drawing(version: &str, entities: &[(i32, String)], acds: &[(i32, String)]) -> Vec<u8> {
|
||||
let mut s = format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\n{version}\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n");
|
||||
let put = |pairs: &[(i32, String)], s: &mut String| {
|
||||
for (c, v) in pairs {
|
||||
s.push_str(&format!("{c:>3}\n{v}\n"));
|
||||
}
|
||||
};
|
||||
put(entities, &mut s);
|
||||
s.push_str(" 0\nENDSEC\n");
|
||||
if !acds.is_empty() {
|
||||
s.push_str(" 0\nSECTION\n 2\nACDSDATA\n");
|
||||
put(acds, &mut s);
|
||||
s.push_str(" 0\nENDSEC\n");
|
||||
}
|
||||
s.push_str(" 0\nEOF\n");
|
||||
s.into_bytes()
|
||||
}
|
||||
|
||||
/// A REGION entity holding `lines` of text data (`split`: each line over 40 characters goes on
|
||||
/// in group 3 from inside a word).
|
||||
fn region_text(lines: &str, split: bool) -> Vec<(i32, String)> {
|
||||
let mut e = vec![
|
||||
(0, "REGION".to_string()),
|
||||
(5, "2A".into()),
|
||||
(8, "0".into()),
|
||||
(100, "AcDbEntity".into()),
|
||||
(100, "AcDbModelerGeometry".into()),
|
||||
(70, "1".into()),
|
||||
];
|
||||
for l in lines.lines() {
|
||||
let b = l.as_bytes();
|
||||
let cut = (40..b.len()).find(|&i| !b[i - 1].is_ascii_whitespace() && !b[i].is_ascii_whitespace());
|
||||
if let Some(at) = cut.filter(|_| split) {
|
||||
e.push((1, l[..at].to_string()));
|
||||
e.push((3, l[at..].to_string()));
|
||||
} else {
|
||||
e.push((1, l.to_string()));
|
||||
}
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
fn points() -> ImportOptions {
|
||||
ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }
|
||||
}
|
||||
|
||||
/// Every leaf path of the document as one path, in document coordinates.
|
||||
fn outline(doc: &Document) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
doc.walk(|n: &Node| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
bp.extend(path.to_bezpath());
|
||||
}
|
||||
});
|
||||
bp
|
||||
}
|
||||
|
||||
/// Inside the path by the even-odd rule.
|
||||
fn filled(bp: &BezPath, p: Point) -> bool {
|
||||
bp.winding(p) % 2 != 0
|
||||
}
|
||||
|
||||
/// The region (drawing `x, y`) is filled at `inside` and not at `outside`.
|
||||
fn check(doc: &Document, inside: &[[f64; 2]], outside: &[[f64; 2]]) {
|
||||
let h = doc.artboards[0].rect.height();
|
||||
let (bp, at) = (outline(doc), |p: &[f64; 2]| Point::new(p[0], h - p[1]));
|
||||
for p in inside {
|
||||
assert!(filled(&bp, at(p)), "{p:?} should be filled");
|
||||
}
|
||||
for p in outside {
|
||||
assert!(!filled(&bp, at(p)), "{p:?} should be empty");
|
||||
}
|
||||
}
|
||||
|
||||
/// The only top-level object: filled, without a stroke.
|
||||
fn filled_object(doc: &Document) -> Node {
|
||||
let [n] = &doc.layers[0].children().unwrap()[..] else { panic!("{:?}", doc.layers[0].children()) };
|
||||
assert!(n.appearance.fill().is_some_and(|f| !f.paint.is_none()), "regions are filled");
|
||||
assert!(n.appearance.stroke().is_none_or(|s| s.paint.is_none()), "regions have no stroke");
|
||||
n.as_ref().clone()
|
||||
}
|
||||
|
||||
fn square_with_hole() -> Vec<Vec<E>> {
|
||||
vec![square(0.0, 100.0), vec![circle([50.0, 50.0], 20.0, true)]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ciphered_text_data_comes_in_as_a_filled_path_with_its_hole() {
|
||||
let text = encipher(&sat(&square_with_hole(), None));
|
||||
let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let n = filled_object(&r.document);
|
||||
let NodeKind::Compound { rule, .. } = &n.kind else { panic!("{:?}", n.kind) };
|
||||
assert_eq!(*rule, FillRule::EvenOdd);
|
||||
assert!((n.geometric_bounds().unwrap().area() - 10_000.0).abs() < 1e-6);
|
||||
check(&r.document, &[[10.0, 10.0], [50.0, 75.0], [90.0, 50.0]], &[[50.0, 50.0], [60.0, 55.0], [110.0, 50.0]]);
|
||||
// The hole is a circle.
|
||||
let h = r.document.artboards[0].rect.height();
|
||||
let bp = outline(&r.document);
|
||||
let centre = Point::new(50.0, h - 50.0);
|
||||
let on_hole: Vec<f64> = bp.segments().map(|s| kurbo::ParamCurve::eval(&s, 0.5).distance(centre)).filter(|d| *d < 30.0).collect();
|
||||
assert!(!on_hole.is_empty() && on_hole.iter().all(|d| (d - 20.0).abs() < 1e-3), "{on_hole:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_split_over_groups_one_and_three_reads_alike() {
|
||||
let text = sat(&square_with_hole(), None);
|
||||
let r = import(&drawing("AC1021", ®ion_text(&text, true), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
filled_object(&r.document);
|
||||
check(&r.document, &[[10.0, 10.0]], &[[50.0, 50.0]]);
|
||||
// Before version 700 a record starts with its attribute alone.
|
||||
let old: String = text.replacen("700 0 1 0", "400 0 1 0", 1).lines().map(|l| format!("{}\n", l.replacen(" $-1 -1 $-1 ", " $-1 ", 1))).collect();
|
||||
assert!(old.contains("body $-1 $1 $-1 $-1 #"), "{old}");
|
||||
let r = import(&drawing("AC1012", ®ion_text(&old, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
check(&r.document, &[[10.0, 10.0]], &[[50.0, 50.0]]);
|
||||
}
|
||||
|
||||
/// Binary data of the same records: tagged values, type names in parts.
|
||||
fn sab(text: &str) -> Vec<u8> {
|
||||
let mut b = b"ACIS BinaryFile".to_vec();
|
||||
for v in [700u32, 0, 1, 0] {
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
let string = |b: &mut Vec<u8>, tag: u8, s: &str| {
|
||||
b.push(tag);
|
||||
b.push(u8::try_from(s.len()).unwrap());
|
||||
b.extend(s.as_bytes());
|
||||
};
|
||||
string(&mut b, 0x07, "Synthetic");
|
||||
b.push(0x06);
|
||||
b.extend(1.0f64.to_le_bytes());
|
||||
for line in text.lines().skip(3) {
|
||||
if line.starts_with("End-of") {
|
||||
break;
|
||||
}
|
||||
let mut words = line.split_whitespace().peekable();
|
||||
let kind = words.next().unwrap();
|
||||
let parts: Vec<&str> = kind.split('-').collect();
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
string(&mut b, if i + 1 == parts.len() { 0x0D } else { 0x0E }, p);
|
||||
}
|
||||
while let Some(w) = words.next() {
|
||||
match w {
|
||||
"#" => {}
|
||||
"forward" | "forward_v" => b.push(0x0B),
|
||||
"reversed" | "reversed_v" => b.push(0x0A),
|
||||
"{" => b.push(0x0F),
|
||||
"}" => b.push(0x10),
|
||||
w if w.starts_with('$') => {
|
||||
b.push(0x0C);
|
||||
b.extend(w[1..].parse::<i32>().unwrap().to_le_bytes());
|
||||
}
|
||||
w if w.starts_with('@') => {
|
||||
let s = words.next().unwrap();
|
||||
string(&mut b, 0x07, s);
|
||||
}
|
||||
w => match w.parse::<f64>() {
|
||||
Ok(v) => {
|
||||
b.push(0x06);
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
Err(_) => string(&mut b, 0x07, w),
|
||||
},
|
||||
}
|
||||
}
|
||||
b.push(0x11);
|
||||
}
|
||||
for p in ["End", "of", "ASM"] {
|
||||
string(&mut b, 0x0E, p);
|
||||
}
|
||||
string(&mut b, 0x0D, "data");
|
||||
b
|
||||
}
|
||||
|
||||
/// An ACDSDATA record holding `bytes` for the entity with handle 2A, in 50-byte chunks.
|
||||
fn acds(bytes: &[u8]) -> Vec<(i32, String)> {
|
||||
let mut a = vec![
|
||||
(0, "ACDSRECORD".to_string()),
|
||||
(90, "1".into()),
|
||||
(2, "AcDbDs::ID".into()),
|
||||
(280, "10".into()),
|
||||
(320, "2A".into()),
|
||||
(2, "ASM_Data".into()),
|
||||
(280, "15".into()),
|
||||
(94, bytes.len().to_string()),
|
||||
];
|
||||
for c in bytes.chunks(50) {
|
||||
a.push((310, c.iter().map(|b| format!("{b:02X}")).collect()));
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_data_in_the_acdsdata_section_reads_alike() {
|
||||
let bytes = sab(&sat(&square_with_hole(), None));
|
||||
let e = vec![(0, "REGION".to_string()), (5, "2A".into()), (8, "0".into()), (100, "AcDbModelerGeometry".into()), (290, "0".into())];
|
||||
// ASM's signature in place of ACIS's, as DXF 2018 may write it.
|
||||
let asm = [b"ASM BinaryFile4".as_slice(), &bytes[b"ACIS BinaryFile".len()..]].concat();
|
||||
for data in [&bytes, &asm] {
|
||||
let r = import(&drawing("AC1032", &e, &acds(data)), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
filled_object(&r.document);
|
||||
check(&r.document, &[[10.0, 10.0], [50.0, 75.0]], &[[50.0, 50.0]]);
|
||||
}
|
||||
// Without its data the region is left out and listed.
|
||||
let r = import(&drawing("AC1027", &e, &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
|
||||
// Data shorter than its declared size is left out and listed too.
|
||||
let mut short = acds(&bytes);
|
||||
short[7].1 = (bytes.len() + 1).to_string();
|
||||
let r = import(&drawing("AC1032", &e, &short), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
|
||||
// A chunk with an odd number of digits or a character that is not a hex digit fails to read.
|
||||
let mut out = Vec::new();
|
||||
assert!(super::reader::hex_bytes("0aFf", &mut out));
|
||||
assert_eq!(out, [0x0A, 0xFF]);
|
||||
for hex in ["0aF", "0aZZ", "0 aF"] {
|
||||
assert!(!super::reader::hex_bytes(hex, &mut Vec::new()), "{hex}");
|
||||
}
|
||||
// Data longer than the limit is left out, unless its declared size cuts it within the limit.
|
||||
let sized = |len: usize, size: Option<usize>| super::reader::sized_region(vec![7; len], size, 8).map(|b| b.len());
|
||||
assert_eq!(sized(10, None), None);
|
||||
assert_eq!(sized(10, Some(9)), None);
|
||||
assert_eq!(sized(10, Some(11)), None);
|
||||
assert_eq!(sized(10, Some(5)), Some(5));
|
||||
assert_eq!(sized(8, None), Some(8));
|
||||
}
|
||||
|
||||
/// A drawing the export writes (R2000, millimetres) with a region added to its entities.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
fn exported_with_region() -> Vec<u8> {
|
||||
let d = Document::new(200.0, 200.0);
|
||||
let o =
|
||||
crate::DxfOptions { version: crate::DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..crate::DxfOptions::default() };
|
||||
let dxf = String::from_utf8(crate::export(&d, &o).unwrap().bytes).unwrap();
|
||||
let mut region = String::new();
|
||||
for (c, v) in region_text(&encipher(&sat(&square_with_hole(), None)), false) {
|
||||
let v = if c == 5 { "FFF0".to_string() } else { v };
|
||||
region.push_str(&format!("{c:>3}\n{v}\n"));
|
||||
}
|
||||
let at = dxf.find("ENTITIES\n").unwrap() + "ENTITIES\n".len();
|
||||
format!("{}{region}{}", &dxf[..at], &dxf[at..]).into_bytes()
|
||||
}
|
||||
|
||||
/// The converter writes a region's data as text in a 2004 drawing and as binary data in the
|
||||
/// ACDSDATA section of a 2013 one; both come in as the DXF does.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn regions_in_dwg_drawings_come_in_from_text_and_binary_data() {
|
||||
crate::dwg::allow_in_process();
|
||||
let dxf = exported_with_region();
|
||||
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), center: false, ..ImportOptions::default() };
|
||||
let want = import(&dxf, &o).unwrap();
|
||||
assert!(want.warnings.is_empty(), "{:?}", want.warnings);
|
||||
let want = filled_object(&want.document).geometric_bounds().unwrap();
|
||||
for version in ["AC1018", "AC1027"] {
|
||||
let dwg = craft_dwg::dxf_to_dwg_as(&dxf, version).unwrap();
|
||||
let back = craft_dwg::dwg_to_dxf(&dwg).unwrap();
|
||||
let binary = String::from_utf8_lossy(&back).contains("ACDSDATA");
|
||||
assert_eq!(binary, version == "AC1027", "{version}: the data's form");
|
||||
let r = import(&dwg, &o).unwrap();
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("REGION")), "{version}: {:?}", r.warnings);
|
||||
let got = filled_object(&r.document).geometric_bounds().unwrap();
|
||||
assert!((got.area() - want.area()).abs() < 1e-6 && got.origin().distance(want.origin()) < 1e-6, "{version}: {got:?} {want:?}");
|
||||
let mm = 72.0 / 25.4;
|
||||
check_at(&r.document, mm, &[[10.0, 10.0], [50.0, 75.0]], &[[50.0, 50.0]]);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`check`] for art at `k` points per drawing unit.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
fn check_at(doc: &Document, k: f64, inside: &[[f64; 2]], outside: &[[f64; 2]]) {
|
||||
let scale = |ps: &[[f64; 2]]| ps.iter().map(|p| [p[0] * k, p[1] * k]).collect::<Vec<_>>();
|
||||
check(doc, &scale(inside), &scale(outside));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reversed_coedges_and_edges_run_their_curves_backwards() {
|
||||
// A quarter of a circle from (100, 0) to (0, 100): on a counter-clockwise circle run along
|
||||
// it, or on a clockwise one run against it, with the edge stored either way round.
|
||||
for (down, flip, against) in [(false, true, true), (true, false, true), (true, true, false), (false, false, false)] {
|
||||
let quarter = E { a: [100.0, 0.0], b: [0.0, 100.0], curve: Curve::Circle { c: [0.0, 0.0], r: 100.0, down }, flip, against };
|
||||
let flipped_line = E { flip: true, against: true, ..line([0.0, 100.0], [0.0, 0.0]) };
|
||||
let quadrant = vec![line([0.0, 0.0], [100.0, 0.0]), quarter, flipped_line];
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[quadrant], None), false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
// A quarter disc, not the three quarters the other way round.
|
||||
check(&r.document, &[[20.0, 20.0], [10.0, 50.0], [65.0, 65.0]], &[[80.0, 80.0], [-50.0, 50.0], [50.0, -50.0]]);
|
||||
let b = filled_object(&r.document).geometric_bounds().unwrap();
|
||||
assert!((b.width() - 100.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{down} {flip} {against}: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spline_edge_keeps_only_its_part_of_the_curve() {
|
||||
// A parabola from (0, 0) through (100, -50) to (200, 0); the edge runs its first half,
|
||||
// stored from its end and run reversed.
|
||||
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 2 open 2 0 2 1 2 0 0 0 100 -100 0 200 0 0 0 } I I".to_string();
|
||||
let half = E { a: [0.0, 0.0], b: [100.0, -50.0], curve: Curve::Raw(curve), flip: true, against: true };
|
||||
let shape = vec![half, line([100.0, -50.0], [100.0, 50.0]), line([100.0, 50.0], [0.0, 0.0])];
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let b = filled_object(&r.document).geometric_bounds().unwrap();
|
||||
assert!((b.width() - 100.0).abs() < 1e-6, "only the first half of the curve: {b:?}");
|
||||
assert!((b.height() - 100.0).abs() < 1e-6, "down to the curve's midpoint: {b:?}");
|
||||
// Below the chord from (0, 0) to (100, -50), above the curve.
|
||||
check(&r.document, &[[50.0, -30.0], [90.0, 0.0]], &[[50.0, -45.0], [150.0, 0.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spline_edge_warns_when_an_endpoint_lies_on_separate_parts_of_its_curve() {
|
||||
// The first and last spans both pass through (0, 0), away from their ends.
|
||||
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 open 4 0 2 1 1 2 1 3 2 -100 -100 0 100 100 0 -100 100 0 100 -100 0 } I I";
|
||||
for back in [false, true] {
|
||||
let (a, b) = if back { ([100.0, 100.0], [0.0, 0.0]) } else { ([0.0, 0.0], [100.0, 100.0]) };
|
||||
let edge = E { a, b, curve: Curve::Raw(curve.into()), flip: false, against: back };
|
||||
let shape = vec![edge, line(b, [100.0, 0.0]), line([100.0, 0.0], a)];
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap();
|
||||
assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]);
|
||||
assert!(!outline(&r.document).elements().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spline_edge_warns_when_an_endpoint_is_at_one_cubic_spans_crossing() {
|
||||
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 3 open 2 0 3 1 3 36 -18 0 -28 26 0 -28 -26 0 36 18 0 } I I";
|
||||
let edge = E { a: [0.0, 0.0], b: [36.0, 18.0], curve: Curve::Raw(curve.into()), flip: false, against: false };
|
||||
let shape = vec![edge, line([36.0, 18.0], [36.0, 0.0]), line([36.0, 0.0], [0.0, 0.0])];
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap();
|
||||
assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]);
|
||||
assert!(!outline(&r.document).elements().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_spline_edge_keeps_the_loop_at_one_cubic_spans_crossing() {
|
||||
// The curve crosses (0, 0) at 0.25 and 0.75; the loop reaches (-12, 0) at 0.5.
|
||||
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 3 open 2 0 3 1 3 36 -18 0 -28 26 0 -28 -26 0 36 18 0 } I I";
|
||||
for back in [false, true] {
|
||||
let edge = E { a: [0.0, 0.0], b: [0.0, 0.0], curve: Curve::Raw(curve.into()), flip: false, against: back };
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[vec![edge]], None), false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
check(&r.document, &[[-6.0, 0.0]], &[[30.0, 0.0]]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_spline_ring_warns_only_when_its_vertex_is_at_the_crossing() {
|
||||
// The first and third spans cross (0, 0) halfway along each; the seam is (-100, -100).
|
||||
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 closed 5 0 2 1 1 2 1 3 1 4 2 -100 -100 0 100 100 0 -100 100 0 100 -100 0 -100 -100 0 } I I";
|
||||
for a in [[0.0, 0.0], [-100.0, -100.0]] {
|
||||
for back in [false, true] {
|
||||
let edge = E { a, b: a, curve: Curve::Raw(curve.into()), flip: false, against: back };
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[vec![edge]], None), false), &[]), &points()).unwrap();
|
||||
if a == [0.0, 0.0] {
|
||||
assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]);
|
||||
} else {
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
check(&r.document, &[[0.0, 50.0], [0.0, -50.0]], &[[75.0, 0.0], [-75.0, 0.0]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spline_joints_and_a_closed_curves_seam_do_not_warn() {
|
||||
for (curve, a) in [
|
||||
("intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 open 3 0 2 1 1 2 2 0 0 0 100 0 0 100 100 0 } I I", [100.0, 0.0]),
|
||||
(
|
||||
"intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 closed 5 0 2 1 1 2 1 3 1 4 2 0 0 0 100 0 0 100 100 0 0 100 0 0 0 0 } I I",
|
||||
[0.0, 0.0],
|
||||
),
|
||||
] {
|
||||
let edge = E { a, b: [100.0, 100.0], curve: Curve::Raw(curve.into()), flip: false, against: false };
|
||||
let shape = vec![edge, line([100.0, 100.0], [0.0, 100.0]), line([0.0, 100.0], a)];
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[shape], None), false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert!(!outline(&r.document).elements().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transform_places_the_body() {
|
||||
// Twice the size, moved 1000 along x.
|
||||
let text = sat(&[square(0.0, 10.0)], Some("1 0 0 0 1 0 0 0 1 1000 0 0 2"));
|
||||
let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap();
|
||||
let b = filled_object(&r.document).geometric_bounds().unwrap();
|
||||
assert!((b.width() - 20.0).abs() < 1e-9 && (b.height() - 20.0).abs() < 1e-9, "{b:?}");
|
||||
let h = r.document.artboards[0].rect.height();
|
||||
assert!(Rect::new(b.x0, h - b.y1, b.x1, h - b.y0).contains(Point::new(1010.0, 10.0)), "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_unreadable_body_transforms_leave_the_region_out() {
|
||||
let text = sat(&[square(0.0, 10.0)], Some("1 0 0 0 1 0 0 0 1 1000 0 0 2"));
|
||||
for damaged in [
|
||||
text.replacen("body $-1 -1 $-1 $1 $-1 $5", "body $-1 -1 $-1 $1 $-1 $99999", 1),
|
||||
text.replacen("body $-1 -1 $-1 $1 $-1 $5", "body $-1 -1 $-1 $1 $-1 $4", 1),
|
||||
text.replacen("1 0 0 0 1 0 0 0 1 1000 0 0 2 no_rotate", "1 0 0 0 1 0 0 0 1 1000 0 no_rotate", 1),
|
||||
text.replacen("1000 0 0 2 no_rotate", "1000 0 0 no_rotate", 1),
|
||||
text.replacen("1000 0 0 2 no_rotate", "1000 0 0 unreadable no_rotate", 1),
|
||||
text.replacen("1 0 0 0 1 0 0 0 1 1000", "1 unreadable 0 0 0 1 0 0 0 1 1000", 1),
|
||||
] {
|
||||
assert_ne!(damaged, text);
|
||||
let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
|
||||
assert!(outline(&r.document).elements().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_unreadable_edge_and_coedge_senses_leave_the_region_out() {
|
||||
let text = sat(&[square(0.0, 10.0)], None);
|
||||
for before in ["$8 forward $6", "$13 forward @7 unknown"] {
|
||||
assert!(text.contains(before), "{text}");
|
||||
for sense in ["", "unreadable"] {
|
||||
let damaged = text.replacen(before, &before.replace("forward", sense), 1);
|
||||
let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{before} {sense}: {:?}", r.warnings);
|
||||
assert!(outline(&r.document).elements().is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_curve_records_warn_when_edges_come_in_straight() {
|
||||
let text = sat(&square_with_hole(), None);
|
||||
let before = "$42 forward @7 unknown";
|
||||
assert!(text.contains(before), "{text}");
|
||||
let damaged = text.replacen(before, "$99999 forward @7 unknown", 1);
|
||||
let r = import(&drawing("AC1015", ®ion_text(&damaged, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("straight lines")), "{:?}", r.warnings);
|
||||
check(&r.document, &[[10.0, 10.0], [50.0, 50.0]], &[[110.0, 50.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnected_edges_warn_even_when_the_coedge_ring_is_complete() {
|
||||
let mut edges = square(0.0, 100.0);
|
||||
edges[1].a[0] += 5.0;
|
||||
edges[1].b[0] += 5.0;
|
||||
let mut closing = square(0.0, 100.0);
|
||||
closing[3].b[0] += 5.0;
|
||||
for edges in [edges, closing] {
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[edges], None), false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings);
|
||||
check(&r.document, &[[50.0, 50.0]], &[[110.0, 50.0]]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_curves_come_in_straight_and_damaged_data_is_left_out() {
|
||||
let mut edges = square(0.0, 100.0);
|
||||
edges[0].curve = Curve::Raw("helix-curve $-1 -1 $-1 0 0 0".into());
|
||||
let r = import(&drawing("AC1015", ®ion_text(&sat(&[edges], None), false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("straight lines")), "{:?}", r.warnings);
|
||||
check(&r.document, &[[50.0, 50.0]], &[]);
|
||||
// A ring of coedges whose second points at itself ends there; a body pointing out of range
|
||||
// and text that isn't data are listed as left out.
|
||||
let ring = sat(&[square(0.0, 10.0)], None);
|
||||
assert!(ring.contains("coedge $-1 -1 $-1 $21 $7 $-1"));
|
||||
let ring = ring.replace("coedge $-1 -1 $-1 $21 $7 $-1", "coedge $-1 -1 $-1 $14 $7 $-1");
|
||||
let wild = sat(&[square(0.0, 10.0)], None).replace("body $-1 -1 $-1 $1", "body $-1 -1 $-1 $99999");
|
||||
let mut e = region_text(&ring, false);
|
||||
for text in [wild.as_str(), "not data", "700 0 1 0\n"] {
|
||||
e.extend(region_text(text, false));
|
||||
}
|
||||
let r = import(&drawing("AC1015", &e, &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("3 REGION")), "{:?}", r.warnings);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings);
|
||||
// The ring's two edges and the line that closes them.
|
||||
check(&r.document, &[[8.0, 2.0]], &[[2.0, 8.0]]);
|
||||
// A hole whose ring of coedges is missing is listed, not dropped quietly.
|
||||
let holed = sat(&[square(0.0, 100.0), square(40.0, 60.0)], None);
|
||||
assert!(holed.contains("loop $-1 -1 $-1 $-1 $36 $3"), "{holed}");
|
||||
let holed = holed.replace("loop $-1 -1 $-1 $-1 $36 $3", "loop $-1 -1 $-1 $-1 $99999 $3");
|
||||
let r = import(&drawing("AC1015", ®ion_text(&holed, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_topology_chains_are_walked_within_a_limit() {
|
||||
// 100 lumps share one chain of 100 shells, each shell one chain of 100 faces: the first face
|
||||
// a square, the others without loops. That is 1,000,000 faces visited, over the limit of
|
||||
// records visited, though only 40,000 coedges.
|
||||
let one = sat(&[square(0.0, 10.0)], None);
|
||||
let mut recs: Vec<String> = one.lines().skip(3).take_while(|l| !l.starts_with("End-of")).map(str::to_string).collect();
|
||||
let (lumps, shells, faces) = (recs.len(), recs.len() + 100, recs.len() + 200);
|
||||
recs[0] = format!("body $-1 -1 $-1 ${lumps} $-1 $-1 #");
|
||||
let next = |i: usize, n: usize, at: usize| if i + 1 < n { format!("${}", at + i + 1) } else { "$-1".into() };
|
||||
for i in 0..100 {
|
||||
recs.push(format!("lump $-1 -1 $-1 {} ${shells} $0 #", next(i, 100, lumps)));
|
||||
}
|
||||
for i in 0..100 {
|
||||
recs.push(format!("shell $-1 -1 $-1 {} $-1 ${faces} $-1 ${lumps} #", next(i, 100, shells)));
|
||||
}
|
||||
for i in 0..100 {
|
||||
let lp = if i == 0 { "$6" } else { "$-1" };
|
||||
recs.push(format!("face $-1 -1 $-1 {} {lp} ${shells} $-1 $4 forward single #", next(i, 100, faces)));
|
||||
}
|
||||
let text = format!("{}\n{}\nEnd-of-ACIS-data\n", one.lines().take(3).collect::<Vec<_>>().join("\n"), recs.join("\n"));
|
||||
let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
|
||||
// One lump, shell and face of the same records come in.
|
||||
let small = text.replacen(&format!("lump $-1 -1 $-1 ${} ", lumps + 1), "lump $-1 -1 $-1 $-1 ", 1);
|
||||
let small = small.replacen(&format!("shell $-1 -1 $-1 ${} ", shells + 1), "shell $-1 -1 $-1 $-1 ", 1);
|
||||
let small = small.replacen(&format!("face $-1 -1 $-1 ${} ", faces + 1), "face $-1 -1 $-1 $-1 ", 1);
|
||||
let r = import(&drawing("AC1015", ®ion_text(&small, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
check(&r.document, &[[5.0, 5.0]], &[[15.0, 5.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_topology_chains_warn_when_the_next_record_is_missing_or_the_wrong_type() {
|
||||
let text = sat(&[square(0.0, 100.0), square(40.0, 60.0)], None);
|
||||
for (before, prefix) in [
|
||||
("lump $-1 -1 $-1 $-1", "lump $-1 -1 $-1"),
|
||||
("shell $-1 -1 $-1 $-1", "shell $-1 -1 $-1"),
|
||||
("face $-1 -1 $-1 $-1", "face $-1 -1 $-1"),
|
||||
("loop $-1 -1 $-1 $35", "loop $-1 -1 $-1"),
|
||||
] {
|
||||
for next in ["$99999", "$4"] {
|
||||
assert!(text.contains(before), "{before}");
|
||||
let broken = text.replacen(before, &format!("{prefix} {next}"), 1);
|
||||
let r = import(&drawing("AC1015", ®ion_text(&broken, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("break off")), "{before} {next}: {:?}", r.warnings);
|
||||
check(&r.document, &[[10.0, 10.0]], &[[110.0, 10.0]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_spline_loops_are_left_out_when_their_generated_outline_is_too_large() {
|
||||
// Many faces share one loop. Its degree-one spline follows a square with many knot spans,
|
||||
// so generated elements reach their limit well before topology visits do.
|
||||
let spans = 1024;
|
||||
let mut curve = format!("intcurve-curve $-1 -1 $-1 forward {{ exactcur 0 nubs 1 closed {} 0 2", spans + 1);
|
||||
for i in 1..spans {
|
||||
curve.push_str(&format!(" {i} 1"));
|
||||
}
|
||||
curve.push_str(&format!(" {spans} 2"));
|
||||
for i in 0..=spans {
|
||||
let t = (i % (spans / 4)) as f64 / (spans / 4) as f64;
|
||||
let (x, y) = match i / (spans / 4) {
|
||||
0 => (t, 0.0),
|
||||
1 => (1.0, t),
|
||||
2 => (1.0 - t, 1.0),
|
||||
_ => (0.0, 1.0 - t),
|
||||
};
|
||||
let (x, y) = if i == spans { (0.0, 0.0) } else { (x, y) };
|
||||
curve.push_str(&format!(" {x} {y} 0"));
|
||||
}
|
||||
curve.push_str(" } I I");
|
||||
let edge = E { a: [0.0, 0.0], b: [0.0, 0.0], curve: Curve::Raw(curve), flip: false, against: false };
|
||||
let one = sat(&[vec![edge]], None);
|
||||
let r = import(&drawing("AC1015", ®ion_text(&one, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
check(&r.document, &[[0.5, 0.5]], &[[1.5, 0.5]]);
|
||||
let mut recs: Vec<String> = one.lines().skip(3).take_while(|l| !l.starts_with("End-of")).map(str::to_string).collect();
|
||||
let faces = recs.len();
|
||||
let count = super::build::MAX_ELEMENTS / (spans + 2) + 1;
|
||||
recs[2] = format!("shell $-1 -1 $-1 $-1 $-1 ${faces} $-1 $1 #");
|
||||
for i in 0..count {
|
||||
let next = if i + 1 < count { format!("${}", faces + i + 1) } else { "$-1".into() };
|
||||
recs.push(format!("face $-1 -1 $-1 {next} $6 $2 $-1 $4 forward single #"));
|
||||
}
|
||||
let text = format!("{}\n{}\nEnd-of-ACIS-data\n", one.lines().take(3).collect::<Vec<_>>().join("\n"), recs.join("\n"));
|
||||
let r = import(&drawing("AC1015", ®ion_text(&text, false), &[]), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
|
||||
assert!(outline(&r.document).elements().is_empty());
|
||||
}
|
||||
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fix All Issues",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}",
|
||||
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents. An error, with nothing fixed, when the fixes would delete the artboard an open Create Font Sheet dialog uses → {scope, total, fixed: {kind: count}}",
|
||||
has_doc,
|
||||
fix
|
||||
),
|
||||
@@ -262,6 +262,13 @@ fn fix(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// With nothing to fix, the document and its undo history stay as they are.
|
||||
if total > 0 {
|
||||
if let Some(guard) = &s.artboard_deletion_guard {
|
||||
let st = s.doc()?;
|
||||
let protected = |doc: &Document| doc.artboards.iter().any(|a| a.id == guard.artboard);
|
||||
if (st.uid, st.reverts) == guard.document && protected(&st.doc) && !protected(&d) {
|
||||
return Err(EngineError::Other(guard.message.clone()));
|
||||
}
|
||||
}
|
||||
sel.prune(&d);
|
||||
s.edit("Fix Issues", |doc, selection| {
|
||||
*doc = d;
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Release Type on a Path
|
||||
//! splits type on a path into point type holding the same text and the plain path it was set on
|
||||
//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no
|
||||
//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
//! parity score. Create Font Sheet ([`font_sheet`]) sets a line of sample text in every font. Its
|
||||
//! submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
|
||||
pub mod font_sheet;
|
||||
pub mod numbers;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -76,6 +78,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
numbers::make_numbers
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(font_sheet::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Release Type on a Path's command (the id in [`specs`]).
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
//! Create Font Sheet (`addon.type.fontSheet`; Object › Plug-ins › Type Tools › Create Font
|
||||
//! Sheet…): a line of sample text set once in each font the font menus list (or in the fonts a
|
||||
//! filter or a list names), each labeled with its font's name, flowed down columns on the active
|
||||
//! artboard and on new artboards to its right when it fills, as one group made in one undo step.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Shape};
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
use super::super::super::create::{new_type_para, new_type_style};
|
||||
use super::super::super::panelcmds::artboard_at;
|
||||
use super::super::super::typecmd::refresh_bounds;
|
||||
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.type.fontSheet";
|
||||
/// The sample text when none is given.
|
||||
pub const DEFAULT_TEXT: &str = "The quick brown fox jumps over the lazy dog";
|
||||
/// Most fonts one sheet sets.
|
||||
pub const MAX_FONTS: usize = 5000;
|
||||
/// Most characters the sample text has.
|
||||
pub const MAX_CHARS: usize = 1000;
|
||||
/// The largest size a label is set at; a smaller sample's label is set at the sample's size.
|
||||
const LABEL_SIZE: f64 = 9.0;
|
||||
/// The space between the artboards the sheet adds, as `artboard.new` leaves it.
|
||||
const ARTBOARD_GAP: f64 = 20.0;
|
||||
/// The page a document without artboards lays the sheet out on (US Letter).
|
||||
const LETTER: Rect = Rect { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 };
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.type.fontSheet",
|
||||
"Create Font Sheet",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An entry whose font lacks a glyph needed by the sample stays on the sheet, and is listed in `fallback` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}",
|
||||
has_doc,
|
||||
font_sheet
|
||||
)]
|
||||
}
|
||||
|
||||
/// `key` of `p`: `default` when omitted, else a number in `range`.
|
||||
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && range.contains(n))
|
||||
.ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample text of `p`: one line, not empty, at most [`MAX_CHARS`] characters.
|
||||
fn sample_text(p: &Value) -> Result<String> {
|
||||
let text = match p.get("text") {
|
||||
None | Some(Value::Null) => return Ok(DEFAULT_TEXT.into()),
|
||||
Some(Value::String(t)) => t.clone(),
|
||||
Some(_) => return Err(bad(COMMAND, "`text` must be a string")),
|
||||
};
|
||||
if text.trim().is_empty() {
|
||||
return Err(bad(COMMAND, "`text` must not be empty"));
|
||||
}
|
||||
// The line and paragraph separators break a line too.
|
||||
if text.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) {
|
||||
return Err(bad(COMMAND, "`text` must be one line, without line breaks or other control characters"));
|
||||
}
|
||||
if text.chars().count() > MAX_CHARS {
|
||||
return Err(bad(COMMAND, format!("`text` must be at most {MAX_CHARS} characters")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// The families the sheet sets, in order: those `families` names, else those the font menus of
|
||||
/// `db` list whose name contains `filter`.
|
||||
fn families(p: &Value, db: &FontDb) -> Result<Vec<String>> {
|
||||
let filter = match p.get("filter") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(f)) => Some(f.trim().to_lowercase()).filter(|f| !f.is_empty()),
|
||||
Some(_) => return Err(bad(COMMAND, "`filter` must be a string")),
|
||||
};
|
||||
let listed = match p.get("families") {
|
||||
None | Some(Value::Null) => {
|
||||
let menu = db.menu_family_list();
|
||||
let wanted = |f: &&String| filter.as_ref().is_none_or(|w| f.to_lowercase().contains(w.as_str()));
|
||||
let found: Vec<String> = menu.iter().filter(wanted).cloned().collect();
|
||||
if found.is_empty() {
|
||||
return Err(bad(COMMAND, "no font family matches `filter`"));
|
||||
}
|
||||
return Ok(found);
|
||||
}
|
||||
Some(_) if p.get("filter").is_some_and(|f| !f.is_null()) => return Err(bad(COMMAND, "give `families` or `filter`, not both")),
|
||||
Some(Value::Array(a)) => a,
|
||||
Some(_) => return Err(bad(COMMAND, "`families` must be a list of font family names")),
|
||||
};
|
||||
if listed.is_empty() {
|
||||
return Err(bad(COMMAND, "`families` must name at least one family"));
|
||||
}
|
||||
let mut out: Vec<String> = Vec::with_capacity(listed.len());
|
||||
for f in listed {
|
||||
let f = f.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(COMMAND, "`families` must be a list of font family names"))?;
|
||||
if !db.has_family(f) {
|
||||
return Err(bad(COMMAND, format!("font family `{f}` is not available")));
|
||||
}
|
||||
// The name as the font menus spell it, looked up as the database compares names.
|
||||
let name = match db.composite_font(f) {
|
||||
Some(c) => c.name.clone(),
|
||||
None => db.canonical(f, "").0,
|
||||
};
|
||||
if out.iter().any(|o| o.to_lowercase() == name.to_lowercase()) {
|
||||
return Err(bad(COMMAND, format!("`families` names `{name}` twice")));
|
||||
}
|
||||
out.push(name);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The index of the artboard the view has active, else the one the document opened on, else the first.
|
||||
fn active_artboard(st: &crate::DocState) -> usize {
|
||||
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
|
||||
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn font_sheet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
font_sheet_in(s, p, FontDb::global())
|
||||
}
|
||||
|
||||
/// [`font_sheet`] over the fonts of `db`.
|
||||
fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let text = sample_text(p)?;
|
||||
let size = number(p, "size", 12.0, 1.0..=1296.0)?;
|
||||
let columns = number(p, "columns", 2.0, 1.0..=50.0)?;
|
||||
if columns.fract() != 0.0 {
|
||||
return Err(bad(C, "`columns` must be a whole number 1..50"));
|
||||
}
|
||||
let columns = columns as usize;
|
||||
let gap = number(p, "gap", 12.0, 0.0..=1000.0)?;
|
||||
let margin = number(p, "margin", 36.0, 0.0..=1000.0)?;
|
||||
let all_styles = switch_or(p, "allStyles", false, C)?;
|
||||
let labels = switch_or(p, "labels", true, C)?;
|
||||
let new_artboards = switch_or(p, "newArtboards", true, C)?;
|
||||
let families = families(p, db)?;
|
||||
|
||||
// Each entry's font: (family, style); no style for the family's Regular or closest style.
|
||||
let mut fonts: Vec<(String, Option<String>)> = vec![];
|
||||
for f in &families {
|
||||
let styles = if all_styles { db.styles(f) } else { vec![] };
|
||||
if styles.is_empty() {
|
||||
fonts.push((f.clone(), None));
|
||||
} else {
|
||||
fonts.extend(styles.into_iter().map(|st| (f.clone(), Some(st))));
|
||||
}
|
||||
if fonts.len() > MAX_FONTS {
|
||||
return Err(bad(C, format!("a sheet sets at most {MAX_FONTS} fonts: give `filter` or `families`")));
|
||||
}
|
||||
}
|
||||
|
||||
let label = size.min(LABEL_SIZE);
|
||||
// The artboard named, else `activeArtboard` (a replay of the journal), else the view's active
|
||||
// one, which the journal entry then records as `activeArtboard` so a replay uses the same artboard.
|
||||
let named = artboard_at(&s.doc()?.doc, p, "artboard", C)?;
|
||||
let active = match named.or(artboard_at(&s.doc()?.doc, p, "activeArtboard", C)?) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let st = s.doc()?;
|
||||
let i = active_artboard(st);
|
||||
if i < st.doc.artboards.len() {
|
||||
s.note_journal("activeArtboard", json!(i));
|
||||
}
|
||||
i
|
||||
}
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let template = d.artboards.get(active).cloned();
|
||||
let page = template.as_ref().map_or(LETTER, |a| a.rect);
|
||||
let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max);
|
||||
let system_layout = d.setup.system_layout;
|
||||
let parent = st.target_parent()?;
|
||||
// An entry's first baseline is at least one line's size below its top, and the entry at least
|
||||
// this tall; the fonts are only laid out when the page has room for that.
|
||||
let (least_above, least_height) = (if labels { label } else { size }, if labels { label } else { 0.0 } + size * 1.5);
|
||||
let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin);
|
||||
let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64;
|
||||
let no_room = || bad(C, "the margin, gap and columns leave no room for a font on the artboard");
|
||||
if column_w <= 0.0 || inner_h < least_height {
|
||||
return Err(no_room());
|
||||
}
|
||||
|
||||
let label_style = {
|
||||
let mut style = new_type_style(s, &json!({ "size": label }), C)?;
|
||||
style.leading = Some(label * 1.2);
|
||||
style
|
||||
};
|
||||
// Each entry laid out at the origin, and how far its laid-out ink reaches above and below its first baseline.
|
||||
let mut laid: Vec<(String, TextObject, (f64, f64))> = Vec::with_capacity(fonts.len());
|
||||
let mut skipped: Vec<String> = vec![];
|
||||
// The entries whose font lacks a glyph needed by the sample.
|
||||
let mut fallback: Vec<String> = vec![];
|
||||
for (family, style) in fonts {
|
||||
let mut sample = new_type_style(s, &json!({ "size": size, "font": family, "style": style }), C)?;
|
||||
sample.leading = Some(size * 1.2);
|
||||
let name = match &style {
|
||||
Some(st) => format!("{family} {st}"),
|
||||
None => family.clone(),
|
||||
};
|
||||
// A font that doesn't load is drawn in the fallback font, and a style that doesn't in the
|
||||
// family's closest style: either is left out. A composite font is left out when a part
|
||||
// that sets the sample names a font or style that doesn't load.
|
||||
let composite = db.composite_font(&family).is_some();
|
||||
// Layout picks a font for each character as typed, then draws All Caps type, and the
|
||||
// lowercase letters of Small Caps type, in capitals in that font, so coverage is checked on both.
|
||||
let caps = sample.all_caps || sample.small_caps.is_some();
|
||||
let (loads, covers) = if composite {
|
||||
// Glyph coverage is checked on the characters layout draws, in the sample's numeral system.
|
||||
let covers = db.composite_cased_coverage(&family, &[text.as_str()], sample.digits, caps).is_none_or(|c| c.lacking.is_empty());
|
||||
(db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), covers)
|
||||
} else {
|
||||
let wanted = db.canonical(&family, "").0;
|
||||
match db.face(&sample.font_family, &sample.font_style) {
|
||||
Some(face) if face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st)) => {
|
||||
let drawn = |t: &str| vectorcraft_text::drawn_chars(t, sample.digits).all(|c| face.covers(c));
|
||||
let capitals = || text.chars().flat_map(char::to_uppercase).collect::<String>();
|
||||
(true, drawn(&text) && (!caps || drawn(&capitals())))
|
||||
}
|
||||
_ => (false, true),
|
||||
}
|
||||
};
|
||||
if !loads {
|
||||
skipped.push(name);
|
||||
continue;
|
||||
}
|
||||
if !covers {
|
||||
fallback.push(name.clone());
|
||||
}
|
||||
let (first, more) = if labels {
|
||||
(TextRun::new(format!("{name}\n"), label_style.clone()), Some(TextRun::new(text.clone(), sample)))
|
||||
} else {
|
||||
(TextRun::new(text.clone(), sample), None)
|
||||
};
|
||||
let t = laid_out(first, more, system_layout);
|
||||
let extent = ink_extent(&t);
|
||||
laid.push((name, t, extent));
|
||||
}
|
||||
if laid.is_empty() {
|
||||
return Err(bad(C, "none of the fonts could be loaded"));
|
||||
}
|
||||
|
||||
// Each page's layout: each entry's first baseline as far below its top as its ink reaches above
|
||||
// it, a row as tall as the tallest entry with the gap below it, and the rows that fit inside the margin.
|
||||
let height = laid.iter().map(|(.., (a, b))| a.max(least_above) + b).fold(least_height, f64::max);
|
||||
let pitch = height + gap;
|
||||
if inner_h < height {
|
||||
return Err(no_room());
|
||||
}
|
||||
let rows = (((inner_h + gap) / pitch).floor() as usize).max(1);
|
||||
let per_page = rows * columns;
|
||||
// Where page `k` starts: the active artboard, then to the right of every artboard.
|
||||
let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) };
|
||||
let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(laid.len());
|
||||
for (i, (name, mut t, (above, _))) in laid.into_iter().enumerate() {
|
||||
let (k, j) = (i / per_page, i % per_page);
|
||||
let (col, row) = (j / rows, j % rows);
|
||||
let x = page_x(k) + margin + col as f64 * (column_w + gap);
|
||||
let baseline = page.y0 + margin + row as f64 * pitch + above.max(least_above);
|
||||
// The layout is in text space, so moving the type keeps it.
|
||||
t.xf = Affine::translate((x, baseline));
|
||||
entries.push((name, t));
|
||||
}
|
||||
let count = entries.len();
|
||||
let pages = count.div_ceil(per_page);
|
||||
let boards: Vec<Rect> = (1..pages).map(|k| Rect::new(page_x(k), page.y0, page_x(k) + page.width(), page.y1)).collect();
|
||||
let template = template.filter(|_| new_artboards);
|
||||
let (gid, added) = s.edit("Create Font Sheet", |d, sel| {
|
||||
let mut added = vec![];
|
||||
if let Some(template) = template {
|
||||
for rect in boards {
|
||||
let mut a = template.clone();
|
||||
a.id = d.next_artboard_id();
|
||||
a.name = format!("Artboard {}", d.artboards.len() + 1);
|
||||
a.rect = rect;
|
||||
a.locked = false;
|
||||
d.artboards.push(a);
|
||||
added.push(d.artboards.len() - 1);
|
||||
}
|
||||
}
|
||||
let children: Vec<Arc<Node>> = entries
|
||||
.into_iter()
|
||||
.map(|(name, t)| {
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
n.name = Some(name);
|
||||
Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::new(gid, NodeKind::Group { children, clip: false });
|
||||
g.name = Some("Font Sheet".into());
|
||||
d.insert(parent, usize::MAX, g)?;
|
||||
sel.set([gid]);
|
||||
Ok((gid, added))
|
||||
})?;
|
||||
let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "fallback": fallback, "artboards": added });
|
||||
let warnings: Vec<String> = skipped_warning(&skipped).into_iter().chain(fallback_warning(&fallback)).collect();
|
||||
if !warnings.is_empty() {
|
||||
out["warning"] = json!(warnings.join("; "));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The warning a sheet with entries whose font lacks a glyph of the sample gives, naming the first few.
|
||||
fn fallback_warning(fallback: &[String]) -> Option<String> {
|
||||
const NAMED: usize = 5;
|
||||
let (first, more) = (fallback.iter().take(NAMED).cloned().collect::<Vec<_>>(), fallback.len().saturating_sub(NAMED));
|
||||
match (first.is_empty(), more) {
|
||||
(true, _) => None,
|
||||
(false, 0) => Some(format!("{} font(s) lack glyphs for the sample: {}", fallback.len(), first.join(", "))),
|
||||
(false, more) => Some(format!("{} font(s) lack glyphs for the sample: {} and {more} more", fallback.len(), first.join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Point type set in `first` and then `more`, with its first baseline at the origin, laid out.
|
||||
fn laid_out(first: TextRun, more: Option<TextRun>, system_layout: bool) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "", first.style.clone());
|
||||
t.runs = std::iter::once(first).chain(more).collect();
|
||||
// Every paragraph is aligned left, right-to-left ones too, so each starts at the column's edge.
|
||||
t.para = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Left, ..new_type_para() };
|
||||
t.system_layout = system_layout;
|
||||
t.normalize_paras();
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
t.cached_bounds = Some(layout.bounds);
|
||||
t.cached_baselines = layout.baselines();
|
||||
let mut ink = layout.run_ink_bounds.clone();
|
||||
for (run, bar) in vectorcraft_text::decorations(&layout, FontDb::global(), &t) {
|
||||
if let Some(bounds) = ink.get_mut(run) {
|
||||
let bar = bar.bounding_box();
|
||||
*bounds = Some(bounds.map_or(bar, |bounds| bounds.union(bar)));
|
||||
}
|
||||
}
|
||||
t.cached_ink = Some((layout.bounds, ink.iter().copied().flatten().reduce(|a, b| a.union(b))));
|
||||
if t.runs.len() == 2
|
||||
&& let (Some(label), Some(sample)) = (ink[0], ink[1])
|
||||
{
|
||||
let overlap = label.y1 - sample.y0;
|
||||
if overlap > 0.0
|
||||
&& let Some(run) = t.runs.get_mut(1)
|
||||
{
|
||||
run.style.leading = Some(run.style.leading.unwrap_or(run.style.size * 1.2) + overlap);
|
||||
refresh_bounds(&mut t);
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// How far the ink of laid-out type `t` reaches above and below its first baseline, underline and
|
||||
/// strikethrough bars included; none when nothing draws.
|
||||
fn ink_extent(t: &TextObject) -> (f64, f64) {
|
||||
t.cached_ink.and_then(|(_, ink)| ink).map_or((0.0, 0.0), |b| ((-b.y0).max(0.0), b.y1.max(0.0)))
|
||||
}
|
||||
|
||||
/// The warning a sheet that left fonts out gives, naming the first few.
|
||||
fn skipped_warning(skipped: &[String]) -> Option<String> {
|
||||
const NAMED: usize = 5;
|
||||
let (first, more) = (skipped.iter().take(NAMED).cloned().collect::<Vec<_>>(), skipped.len().saturating_sub(NAMED));
|
||||
match (first.is_empty(), more) {
|
||||
(true, _) => None,
|
||||
(false, 0) => Some(format!("{} font(s) could not be loaded and were left out: {}", skipped.len(), first.join(", "))),
|
||||
(false, more) => Some(format!("{} font(s) could not be loaded and were left out: {} and {more} more", skipped.len(), first.join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,636 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::{COMMAND, DEFAULT_TEXT, MAX_CHARS};
|
||||
use crate::Session;
|
||||
|
||||
/// The bundled families, available on every platform.
|
||||
const BUNDLED: [&str; 3] = ["Inter", "Source Serif 4", "JetBrains Mono"];
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn group(s: &Session, r: &Value) -> Node {
|
||||
s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone()
|
||||
}
|
||||
|
||||
/// Each entry of the sheet `g`: its name and its type.
|
||||
fn entries(g: &Node) -> Vec<(String, TextObject)> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => (n.name.clone().unwrap_or_default(), (**t).clone()),
|
||||
_ => panic!("a font sheet holds only type"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where the first baseline of `t` starts.
|
||||
fn origin(t: &TextObject) -> (f64, f64) {
|
||||
let [.., x, y] = t.xf.as_coeffs();
|
||||
(x, y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_sets_the_text_in_each_family_labeled_in_columns_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let undo = steps(&s);
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 2, "size": 12, "gap": 10, "margin": 20, "text": "Hamburgefonstiv"})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["artboards"], json!([]), "three entries fit on the artboard");
|
||||
assert_eq!(steps(&s), undo + 1, "one undo step");
|
||||
let g = group(&s, &r);
|
||||
assert_eq!(g.name.as_deref(), Some("Font Sheet"));
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [g.id], "the sheet is selected");
|
||||
let e = entries(&g);
|
||||
assert_eq!(e.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), BUNDLED, "in the order given, each named after its font");
|
||||
for ((name, t), family) in e.iter().zip(BUNDLED) {
|
||||
assert_eq!(t.plain_text(), format!("{name}\nHamburgefonstiv"), "a label line, then the sample");
|
||||
let [label, sample] = &t.runs[..] else { panic!("a label run and a sample run: {:?}", t.runs.len()) };
|
||||
assert_eq!(sample.style.font_family, family);
|
||||
assert!((sample.style.size - 12.0).abs() < 1e-9 && (label.style.size - 9.0).abs() < 1e-9, "the label is set at 9 pt");
|
||||
assert_eq!(label.style.font_family, "Source Sans 3", "the label is in the normal type font");
|
||||
}
|
||||
// Down the first column, 9 + 18 + 10 pt apart, inside the 20 pt margin, the first baseline one label below the top.
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let (a, b) = (origin(&e[0].1), origin(&e[1].1));
|
||||
assert!((a.0 - board.x0 - 20.0).abs() < 1e-9 && (a.1 - board.y0 - 29.0).abs() < 1e-9, "{a:?}");
|
||||
assert!((b.0 - a.0).abs() < 1e-9 && (b.1 - a.1 - 37.0).abs() < 1e-9, "{b:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g.id).is_none(), "undo removes the sheet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_artboard_continues_on_new_artboards_to_the_right() {
|
||||
let mut s = session();
|
||||
let undo = steps(&s);
|
||||
// 400 pt tall less 2 × 100 pt of margin: 200 pt, room for two 72 pt entries (9 + 54 + 9).
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100})).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
assert_eq!(r["artboards"], json!([1]), "the third entry goes on a new artboard");
|
||||
assert_eq!(steps(&s), undo + 1, "the new artboard is in the same undo step");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let (first, added) = (doc.artboards[0].rect, doc.artboards[1].rect);
|
||||
assert!((added.x0 - first.x1 - 20.0).abs() < 1e-9 && (added.y0 - first.y0).abs() < 1e-9, "{added:?}");
|
||||
assert!((added.width() - first.width()).abs() < 1e-9 && (added.height() - first.height()).abs() < 1e-9, "the same size");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9, "inset by the margin on the new artboard");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "undo removes the artboard too");
|
||||
|
||||
// Without new artboards, the page after the first is laid out in the same place with none.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100, "newArtboards": false})).unwrap();
|
||||
assert_eq!(r["artboards"], json!([]));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_picks_families_and_all_styles_lists_each_style() {
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"filter": " sOURCE s ", "labels": false})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let names: Vec<&str> = e.iter().map(|(n, _)| n.as_str()).collect();
|
||||
assert!(e.len() >= 2 && names.len() == e.len(), "{names:?}");
|
||||
assert!(names.contains(&"Source Sans 3") && names.contains(&"Source Serif 4"), "{names:?}");
|
||||
assert!(names.iter().all(|n| n.to_lowercase().contains("source s")), "{names:?}");
|
||||
assert!(e.iter().all(|(_, t)| t.runs.len() == 1 && t.plain_text() == DEFAULT_TEXT), "no labels: the sample alone");
|
||||
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Source Sans 3"], "allStyles": true})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let styles: Vec<String> = vectorcraft_text::FontDb::global().styles("Source Sans 3");
|
||||
assert!(styles.len() > 1, "{styles:?}");
|
||||
assert_eq!(e.len(), styles.len(), "one entry for each style");
|
||||
for ((name, t), style) in e.iter().zip(&styles) {
|
||||
assert_eq!(name, &format!("Source Sans 3 {style}"));
|
||||
assert_eq!(&t.runs[1].style.font_style, style);
|
||||
}
|
||||
}
|
||||
|
||||
/// Columns sit side by side, each `gap` apart and as wide as the room inside the margin allows.
|
||||
#[test]
|
||||
fn columns_share_the_room_inside_the_margin() {
|
||||
let mut s = session();
|
||||
// 400 pt less 2 × 50 pt of margin leaves 300 pt: eight 39 pt entries (9 + 18 + 12) fit in a column.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12})).unwrap();
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let e = entries(&group(&s, &r));
|
||||
// The first column fills before the second starts, so all three share it.
|
||||
let xs: Vec<f64> = e.iter().map(|(_, t)| origin(t).0).collect();
|
||||
assert!(!xs.is_empty(), "the sheet has entries");
|
||||
assert!(xs.iter().all(|x| (x - board.x0 - 50.0).abs() < 1e-9), "{xs:?}");
|
||||
// One row per column: each entry starts a column, (500 − 2 × 12) / 3 wide plus the gap apart.
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "size": 150})).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
let step = (500.0 - 24.0) / 3.0 + 12.0;
|
||||
for (i, (_, t)) in e.iter().enumerate() {
|
||||
let (x, y) = origin(t);
|
||||
assert!((x - board.x0 - 50.0 - i as f64 * step).abs() < 1e-9 && (y - board.y0 - 59.0).abs() < 1e-9, "entry {i}: {x}, {y}");
|
||||
}
|
||||
assert_eq!(r["artboards"], json!([]));
|
||||
}
|
||||
|
||||
/// The journal records the active artboard, so a replay in a new session lays the sheet out on the
|
||||
/// same one; an action leaves it out, and a named artboard goes ahead of it.
|
||||
#[test]
|
||||
fn the_journal_records_the_artboard_the_sheet_was_laid_out_on() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].clone();
|
||||
s.doc_mut().unwrap().active_artboard = Some(second.id);
|
||||
let start = s.journal.len();
|
||||
let params = json!({"families": ["Inter"], "margin": 10});
|
||||
let r = s.execute(COMMAND, ¶ms).unwrap();
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "on the active artboard");
|
||||
let (id, recorded) = s.journal.last().unwrap().clone();
|
||||
assert_eq!((id.as_str(), &recorded["activeArtboard"]), (COMMAND, &json!(1)));
|
||||
assert_eq!(s.journal_for_action(start)[0].1.get("activeArtboard"), None, "an action uses the artboard active when it plays");
|
||||
|
||||
// A replay in a session whose view has no active artboard uses the recorded one.
|
||||
let mut fresh = session();
|
||||
fresh.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
|
||||
let r = fresh.replay(COMMAND, &recorded).unwrap();
|
||||
let e = entries(&group(&fresh, &r));
|
||||
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "the replay lays it out on the recorded artboard");
|
||||
// A named artboard goes ahead of the recorded one.
|
||||
let r = fresh.execute(COMMAND, &json!({"families": ["Inter"], "margin": 10, "artboard": 0, "activeArtboard": 1})).unwrap();
|
||||
let e = entries(&group(&fresh, &r));
|
||||
let first = fresh.doc().unwrap().doc.artboards[0].rect;
|
||||
assert!((origin(&e[0].1).0 - first.x0 - 10.0).abs() < 1e-9);
|
||||
assert!(fresh.execute(COMMAND, &json!({"families": ["Inter"], "artboard": 5})).is_err(), "no such artboard");
|
||||
}
|
||||
|
||||
/// A right-to-left sample starts at its column's left edge like any other, so it stays inside its column.
|
||||
#[test]
|
||||
fn a_right_to_left_sample_stays_inside_its_column() {
|
||||
let mut s = session();
|
||||
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
// Alone, and under a left-to-right label: each line starts at the column's left edge.
|
||||
for labels in [false, true] {
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(BUNDLED), "no bundled font has Hebrew glyphs, so each entry is named");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
|
||||
for (name, t) in &entries(&group(&s, &r)) {
|
||||
let x = origin(t).0;
|
||||
assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}");
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), t);
|
||||
for line in &layout.lines {
|
||||
let left = x + line.x0;
|
||||
assert!(left > board.x0 + 50.0 - 1e-6, "{name}, labels {labels}: a line starts at {left}, left of the column's edge");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variation_selector_does_not_require_a_separate_glyph() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
assert!(face.covers('A'));
|
||||
assert!(!face.covers('\u{fe0f}'));
|
||||
let text = "A\u{fe0f}";
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["fallback"], json!([]));
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 1);
|
||||
assert_eq!(e[0].1.plain_text(), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_uses_the_samples_numeral_system() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
assert!(face.covers('1'));
|
||||
assert!(!face.covers('\u{661}'));
|
||||
for (digits, text, missing) in [("hindi", "1", true), ("arabic", "\u{661}", false)] {
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": digits}}))
|
||||
.unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
assert_eq!(r["fallback"], if missing { json!(["Inter"]) } else { json!([]) }, "{digits}: {r}");
|
||||
if missing {
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
|
||||
} else {
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
}
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 1);
|
||||
assert_eq!(e[0].1.plain_text(), text);
|
||||
assert_eq!(e[0].1.runs[0].style.digits.id(), digits);
|
||||
}
|
||||
}
|
||||
|
||||
/// All Caps in the normal character style draws the sample in capitals, so a font with a lowercase
|
||||
/// letter but not its capital is named in `fallback`, plain and composite fonts alike.
|
||||
#[test]
|
||||
fn coverage_checks_the_capitals_all_caps_draws() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
let lower = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let mut up = c.to_uppercase();
|
||||
face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
|
||||
let font = json!({"name": "CF Sheet Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let text = lower.to_string();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"all_caps": true}})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
assert_eq!(r["fallback"], json!(["Inter", "CF Sheet Caps"]), "{lower:?}: {r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs")), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert!(e[0].1.runs[0].style.all_caps);
|
||||
assert_eq!(e[0].1.plain_text(), text, "the sample keeps its own case");
|
||||
// Layout picks the font for the character as typed, so one the font lacks still falls back
|
||||
// when the font has its capitals.
|
||||
let uncased = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let up: String = c.to_uppercase().collect();
|
||||
!face.covers(c) && up != c.to_string() && up.chars().all(|u| face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has every character whose capitals it has"));
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": uncased.to_string()})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(["Inter"]), "{uncased:?}: {r}");
|
||||
}
|
||||
|
||||
/// Small Caps in the normal character style draws lowercase letters as capitals too, so a font with
|
||||
/// a lowercase letter but not its capital is named in `fallback`, plain and composite fonts alike.
|
||||
#[test]
|
||||
fn coverage_checks_the_capitals_small_caps_draws() {
|
||||
let mut s = session();
|
||||
let face = FontDb::global().face("Inter", "Regular").unwrap();
|
||||
let lower = (0x80..0x3000u32)
|
||||
.filter_map(char::from_u32)
|
||||
.find(|&c| {
|
||||
let mut up = c.to_uppercase();
|
||||
c.is_lowercase() && face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
|
||||
let font = json!({"name": "CF Sheet Small Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let text = lower.to_string();
|
||||
let families = json!(["Inter", "CF Sheet Small Caps"]);
|
||||
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"small_caps": 70}})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
let e = entries(&group(&s, &r));
|
||||
assert_eq!(e.len(), 2);
|
||||
assert!(e[0].1.runs[0].style.small_caps.is_some());
|
||||
assert_eq!(r["fallback"], families, "{lower:?}: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
let long = "x".repeat(MAX_CHARS + 1);
|
||||
for bad in [
|
||||
json!({"text": ""}),
|
||||
json!({"text": " "}),
|
||||
json!({"text": "two\nlines"}),
|
||||
json!({"text": "two\u{2028}lines"}),
|
||||
json!({"text": "two\u{2029}paragraphs"}),
|
||||
json!({"text": long}),
|
||||
json!({"text": 5}),
|
||||
json!({"size": 0.5}),
|
||||
json!({"size": "12"}),
|
||||
json!({"columns": 0}),
|
||||
json!({"columns": 1.5}),
|
||||
json!({"gap": -1}),
|
||||
json!({"margin": 2000}),
|
||||
json!({"margin": 300}),
|
||||
json!({"columns": 50, "gap": 1000}),
|
||||
json!({"filter": "no family is called this"}),
|
||||
json!({"filter": 3}),
|
||||
json!({"families": []}),
|
||||
json!({"families": "Inter"}),
|
||||
json!({"families": ["Inter", "inter"]}),
|
||||
json!({"families": ["No Such Family Anywhere"]}),
|
||||
json!({"families": [""]}),
|
||||
json!({"families": ["Inter"], "filter": "Inter"}),
|
||||
json!({"families": ["Inter"], "filter": ""}),
|
||||
json!({"families": ["Inter"], "filter": " "}),
|
||||
json!({"labels": "yes"}),
|
||||
json!({"allStyles": 1}),
|
||||
json!({"newArtboards": "no"}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(steps(&s), before);
|
||||
let layers = &s.doc().unwrap().doc.layers;
|
||||
assert!(!layers.is_empty(), "the document keeps its layers");
|
||||
assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn");
|
||||
}
|
||||
|
||||
/// Fonts left out are named in the warning, the first five of them, with a count of the rest.
|
||||
#[test]
|
||||
fn fonts_left_out_are_named_in_a_warning() {
|
||||
let names = |n: usize| (1..=n).map(|i| format!("Font {i}")).collect::<Vec<_>>();
|
||||
assert_eq!(super::skipped_warning(&[]), None);
|
||||
assert_eq!(super::skipped_warning(&names(2)).as_deref(), Some("2 font(s) could not be loaded and were left out: Font 1, Font 2"));
|
||||
assert_eq!(
|
||||
super::skipped_warning(&names(7)).as_deref(),
|
||||
Some("7 font(s) could not be loaded and were left out: Font 1, Font 2, Font 3, Font 4, Font 5 and 2 more")
|
||||
);
|
||||
let mut s = session();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
|
||||
assert!(r.get("warning").is_none(), "nothing left out: no warning");
|
||||
}
|
||||
|
||||
/// A family the font menus list whose file no longer reads as a font is left out, as is a style
|
||||
/// that would be drawn in another style of its family; the rest of the sheet is made.
|
||||
#[test]
|
||||
fn fonts_that_do_not_load_are_left_out_and_named() {
|
||||
use vectorcraft_text::test_fonts::named_copy;
|
||||
let dir = vectorcraft_testkit::temp_dir("font-sheet-unreadable");
|
||||
let file = |family: &str, style: &str| dir.join(format!("{}-{style}.ttf", family.replace(' ', "")));
|
||||
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Regular"), ("Sheet Half", "Bold")] {
|
||||
let postscript = format!("{}-{style}", family.replace(' ', ""));
|
||||
std::fs::write(file(family, style), named_copy(false, (family, style, "Version 1.000", &postscript)).unwrap()).unwrap();
|
||||
}
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
// Cataloged while every file reads; then two of them stop reading as fonts.
|
||||
assert_eq!(db.styles("Sheet Half").len(), 2, "{:?}", db.styles("Sheet Half"));
|
||||
assert!(db.menu_family_list().iter().any(|f| f == "Sheet Gone"));
|
||||
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Bold")] {
|
||||
std::fs::write(file(family, style), b"not a font").unwrap();
|
||||
}
|
||||
let mut s = session();
|
||||
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone", "Inter"]}), &db).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["Sheet Gone"]), "drawn in the fallback font, it is left out: {r}");
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: Sheet Gone");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Half"], "allStyles": true}), &db).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["Sheet Half Bold"]), "drawn in its Regular, the Bold is left out: {r}");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Sheet Half Regular"]);
|
||||
// Nothing that loads: an error, with nothing changed.
|
||||
let before = steps(&s);
|
||||
assert!(super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone"]}), &db).is_err());
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
/// Where the ink of `t` starts and ends down the page.
|
||||
fn ink_rows(t: &TextObject) -> (f64, f64) {
|
||||
let (_, y) = origin(t);
|
||||
let b = vectorcraft_text::layout(FontDb::global(), t).ink_bounds().unwrap();
|
||||
(y + b.y0, y + b.y1)
|
||||
}
|
||||
|
||||
/// A composite font whose Roman part sets the sample at four times its size gets rows as tall as
|
||||
/// its laid-out ink: the first entry stays inside the margin, the second starts below the first,
|
||||
/// and each sample starts below its own label.
|
||||
#[test]
|
||||
fn rows_fit_the_laid_out_ink_of_a_composite_font() {
|
||||
let mut s = session();
|
||||
let big = |name: &str| json!({"name": name, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter", "size": 400}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [big("CF Sheet Big A"), big("CF Sheet Big B")]})).unwrap();
|
||||
let p = json!({"families": ["CF Sheet Big A", "CF Sheet Big B"], "columns": 1, "size": 12, "gap": 10, "margin": 20, "text": "Hamburg"});
|
||||
let r = s.execute(COMMAND, &p).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
let e = entries(&group(&s, &r));
|
||||
let ((top0, bottom0), (top1, _)) = (ink_rows(&e[0].1), ink_rows(&e[1].1));
|
||||
assert!(top0 >= board.y0 + 20.0 - 1e-6, "the first entry reaches into the margin: {top0}");
|
||||
assert!(top1 >= bottom0 - 1e-6, "the second entry overlaps the first: {top1} < {bottom0}");
|
||||
for (name, t) in &e {
|
||||
let mut label = t.clone();
|
||||
label.runs.truncate(1);
|
||||
let mut sample = t.clone();
|
||||
sample.runs.remove(0);
|
||||
let (y0, y1) = (t.cached_baselines[0].0.y, t.cached_baselines[1].0.y);
|
||||
let label_bottom = y0 + vectorcraft_text::layout(FontDb::global(), &label).ink_bounds().unwrap().y1;
|
||||
let sample_top = y1 + vectorcraft_text::layout(FontDb::global(), &sample).ink_bounds().unwrap().y0;
|
||||
assert!(sample_top >= label_bottom - 1e-6, "{name}: the sample reaches into its label: {sample_top} < {label_bottom}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite font named in other letter case, accented letters included, is found by its own name.
|
||||
#[test]
|
||||
fn a_composite_font_named_in_other_case_is_set() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "\u{c9}preuve Sheet", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["\u{e9}preuve sheet"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!((r["skipped"].clone(), r["count"].clone()), (json!([]), json!(1)), "{r}");
|
||||
assert_eq!(entries(&group(&s, &r))[0].0, "\u{c9}preuve Sheet");
|
||||
let twice = s.execute(COMMAND, &json!({"families": ["\u{c9}preuve Sheet", "\u{e9}PREUVE SHEET"]})).unwrap_err().to_string();
|
||||
assert!(twice.contains("twice"), "{twice}");
|
||||
}
|
||||
|
||||
/// A composite font whose part setting the sample names a font that doesn't load is left out and
|
||||
/// named, as a family that doesn't load is.
|
||||
#[test]
|
||||
fn a_composite_font_with_a_missing_part_is_left_out() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "CF Sheet Gone", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Sheet Font"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Gone", "Inter"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["CF Sheet Gone"]), "{r}");
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composite_font_with_an_unavailable_part_style_is_left_out() {
|
||||
let mut s = session();
|
||||
let font = json!({
|
||||
"name": "CF Sheet Missing Style",
|
||||
"parts": {
|
||||
"kanji": {"font": "Source Sans 3"},
|
||||
"roman": {"font": "Inter", "style": "No Such Sheet Style"}
|
||||
}
|
||||
});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let coverage = FontDb::global().composite_coverage("CF Sheet Missing Style", &["Hamburg"]).unwrap();
|
||||
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Style);
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style", "Inter"], "text": "Hamburg"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!(["CF Sheet Missing Style"]));
|
||||
assert_eq!(r["count"], 1);
|
||||
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: CF Sheet Missing Style");
|
||||
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
assert!(s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style"], "text": "Hamburg"})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc, before.0);
|
||||
assert_eq!(steps(&s), before.1);
|
||||
}
|
||||
|
||||
/// A composite font whose parts load but lack a glyph the sample needs stays on the sheet and is
|
||||
/// named in `fallback`, as a plain font is.
|
||||
#[test]
|
||||
fn a_composite_font_lacking_a_sample_glyph_is_named_as_a_fallback() {
|
||||
let mut s = session();
|
||||
let font = json!({"name": "CF Sheet Lacking", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
|
||||
let coverage = FontDb::global().composite_coverage("CF Sheet Lacking", &[rtl]).unwrap();
|
||||
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Exact);
|
||||
assert!(!coverage.lacking.is_empty());
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": rtl})).unwrap();
|
||||
assert_eq!((&r["count"], &r["skipped"]), (&json!(1), &json!([])), "{r}");
|
||||
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("CF Sheet Lacking")), "{r}");
|
||||
// A variation selector needs no glyph of its own, and digits are checked in the sample's numeral system.
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "A\u{fe0f}"})).unwrap();
|
||||
assert_eq!(r["fallback"], json!([]), "{r}");
|
||||
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": "hindi"}}))
|
||||
.unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "1"})).unwrap();
|
||||
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_without_overlap_need_no_additional_layouts() {
|
||||
use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread};
|
||||
|
||||
let mut counts = vec![];
|
||||
for labels in [false, true] {
|
||||
let mut s = session();
|
||||
let before = layouts_on_this_thread();
|
||||
let ink_before = ink_work_on_this_thread();
|
||||
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "text": "Hamburg", "labels": labels})).unwrap();
|
||||
let ink_after = ink_work_on_this_thread();
|
||||
counts.push(layouts_on_this_thread() - before);
|
||||
assert_eq!(r["count"], BUNDLED.len());
|
||||
let mut outlines = 0;
|
||||
for (_, t) in entries(&group(&s, &r)) {
|
||||
assert!(t.cached_ink.unwrap().1.is_some());
|
||||
assert_eq!(t.cached_baselines.len(), if labels { 2 } else { 1 });
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
outlines += layout.glyphs.iter().chain(&layout.ruby).filter(|glyph| !glyph.outline.elements().is_empty()).count() as u64;
|
||||
assert_eq!(t.cached_ink.unwrap().1, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
|
||||
}
|
||||
assert_eq!(ink_after.0 - ink_before.0, outlines, "each glyph outline is measured once");
|
||||
assert_eq!(ink_after.1 - ink_before.1, BUNDLED.len() as u64, "decorations are measured once per entry");
|
||||
}
|
||||
assert!(counts[0] > 0);
|
||||
assert_eq!(counts[1], counts[0], "labels that fit must not cause separate label and sample layouts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reused_font_sheet_ink_includes_decorations_and_handles_blank_runs() {
|
||||
use vectorcraft_doc::{CharStyle, TextRun};
|
||||
|
||||
for text in ["Hamburg", " "] {
|
||||
for labels in [false, true] {
|
||||
let style = CharStyle { font_family: "Inter".into(), size: 12.0, underline: true, strikethrough: true, ..Default::default() };
|
||||
let sample = TextRun::new(text, style.clone());
|
||||
let (first, more) = if labels { (TextRun::new("Font\n", style), Some(sample)) } else { (sample, None) };
|
||||
let t = super::laid_out(first, more, false);
|
||||
let layout = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
let bars = vectorcraft_text::decorations(&layout, FontDb::global(), &t);
|
||||
assert!(!bars.is_empty(), "the entry includes underline and strikethrough bars");
|
||||
let ink = t.cached_ink.unwrap().1;
|
||||
assert_eq!(ink, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
|
||||
let ink = ink.unwrap();
|
||||
for (_, bar) in bars {
|
||||
let bounds = vectorcraft_geom::Shape::bounding_box(&bar);
|
||||
assert!(ink.x0 <= bounds.x0 && ink.y0 <= bounds.y0 && ink.x1 >= bounds.x1 && ink.y1 >= bounds.y1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"artboards": 3})).unwrap();
|
||||
let state = s.doc().unwrap();
|
||||
let document = (state.uid, state.reverts);
|
||||
let artboard = state.doc.artboards[1].id;
|
||||
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for params in [json!({"index": 0}), json!({"indices": [1, 0]})] {
|
||||
let error = s.execute("artboard.delete", ¶ms).unwrap_err();
|
||||
assert_eq!(error.to_string(), "The artboard is in use.");
|
||||
assert_eq!(s.doc().unwrap().doc, before.0);
|
||||
assert_eq!(steps(&s), before.1);
|
||||
}
|
||||
s.execute("file.new", &json!({"artboards": 2})).unwrap();
|
||||
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "another document is not protected");
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
s.doc_mut().unwrap().reverts += 1;
|
||||
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected");
|
||||
}
|
||||
|
||||
/// Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards keep the guarded artboard too.
|
||||
#[test]
|
||||
fn an_artboard_deletion_guard_covers_every_command_that_deletes_artboards() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"artboards": 3})).unwrap();
|
||||
let state = s.doc().unwrap();
|
||||
let document = (state.uid, state.reverts);
|
||||
let artboard = state.doc.artboards[1].id;
|
||||
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
|
||||
let before = (s.doc().unwrap().doc.clone(), steps(&s));
|
||||
for (command, params) in [
|
||||
("artboard.cut", json!({"index": 1})),
|
||||
("artboard.deleteEmpty", json!({})),
|
||||
("addon.cleanup.fix", json!({"kinds": ["emptyArtboards"], "scope": "document"})),
|
||||
] {
|
||||
let error = s.execute(command, ¶ms).unwrap_err();
|
||||
assert_eq!(error.to_string(), "The artboard is in use.", "{command}");
|
||||
assert_eq!(s.doc().unwrap().doc, before.0, "{command}");
|
||||
assert_eq!(steps(&s), before.1, "{command}");
|
||||
}
|
||||
s.execute("artboard.cut", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2, "another artboard is cut");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_needs_a_document() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.execute(COMMAND, &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_layer_takes_no_sheet() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err());
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_current_layer_sends_the_sheet_to_the_topmost_editable_layer() {
|
||||
let mut s = session();
|
||||
let editable = s.doc().unwrap().doc.layers[0].id;
|
||||
let locked = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
|
||||
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
|
||||
let gid = NodeId(r["id"].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let holds = |layer: NodeId| doc.children(Some(layer)).is_some_and(|c| c.iter().any(|n| n.id == gid));
|
||||
assert!(holds(editable), "the sheet goes to the layer that is shown and unlocked");
|
||||
assert!(!holds(locked));
|
||||
}
|
||||
@@ -178,14 +178,14 @@ pub(crate) use export_names::{
|
||||
artboard_file_names_keeping_dots, default_name, merge, unique_file_names_keeping_dots, with_black_output, write_or_return,
|
||||
};
|
||||
use export_names::{distinct_names_by, write_encoded};
|
||||
pub(crate) use formats::is_own_title;
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
|
||||
pub use formats::{
|
||||
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
|
||||
export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions,
|
||||
open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions,
|
||||
readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
|
||||
open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters, places_with_importer,
|
||||
plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
|
||||
};
|
||||
pub(crate) use formats::{is_own_title, reads};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -785,7 +785,7 @@ fn is_openable(path: &str) -> bool {
|
||||
if ext.is_empty() {
|
||||
return false;
|
||||
}
|
||||
open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| f.read && f.extensions.iter().any(|e| *e == ext))
|
||||
open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| super::formats::reads(f) && f.extensions.iter().any(|e| *e == ext))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -389,7 +389,10 @@ impl RasterOptions {
|
||||
top_down: self.flip_rows.unwrap_or(false),
|
||||
gray: color_model == jpeg::ColorModel::Gray,
|
||||
},
|
||||
tga: tga::TgaOptions { depth: self.depth.unwrap_or(24) },
|
||||
tga: {
|
||||
let gray = color_model == jpeg::ColorModel::Gray;
|
||||
tga::TgaOptions { depth: self.depth.unwrap_or_else(|| tga::TgaOptions::default_depth(gray)), gray }
|
||||
},
|
||||
psd: psd::PsdOptions {
|
||||
color_model,
|
||||
layers: self.layers.unwrap_or(true),
|
||||
@@ -413,12 +416,12 @@ fn bmp_layout(s: &str) -> Option<bool> {
|
||||
}
|
||||
|
||||
/// Refuse options `format` can't write together: BMP and Targa depths and layouts, and colour
|
||||
/// models (BMP is RGB or grey, Targa RGB).
|
||||
/// models (BMP and Targa are RGB or grey).
|
||||
fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> {
|
||||
let model = o.jpeg.color_model;
|
||||
let r = match format {
|
||||
RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()),
|
||||
RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()),
|
||||
RasterFormat::Tga if model == jpeg::ColorModel::Cmyk => Err("Targa files are RGB or grayscale: colorModel rgb or gray".to_string()),
|
||||
RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()),
|
||||
RasterFormat::Bmp => o.bmp.check(),
|
||||
RasterFormat::Tga => o.tga.check(),
|
||||
|
||||
@@ -315,14 +315,18 @@ const BMP_OPTIONS: &[FormatOption] = &[
|
||||
DITHER_AMOUNT,
|
||||
];
|
||||
|
||||
const TGA_COLOR_MODEL: FormatOption =
|
||||
FormatOption { name: "colorModel", ty: "string", default: "\"rgb\"", description: "rgb (true color) or gray (grayscale)" };
|
||||
|
||||
const TGA_DEPTH: FormatOption = FormatOption {
|
||||
name: "depth",
|
||||
ty: "integer",
|
||||
default: "24",
|
||||
description: "bits per pixel: 16 (one-bit alpha), 24 (flattened on white) or 32 (keeps transparency)",
|
||||
description: "bits per pixel: with rgb 16 (one-bit alpha), 24 (flattened on white) or 32 (keeps transparency); with gray 8 (the default, flattened on white) or 16 (keeps transparency)",
|
||||
};
|
||||
|
||||
const TGA_OPTIONS: &[FormatOption] = &[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, TGA_DEPTH];
|
||||
const TGA_OPTIONS: &[FormatOption] =
|
||||
&[ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, RECT, PPI, SCALE, WIDTH, HEIGHT, BACKGROUND, ANTI_ALIAS, TGA_COLOR_MODEL, TGA_DEPTH];
|
||||
|
||||
const PSD_LAYERS: FormatOption = FormatOption {
|
||||
name: "layers",
|
||||
@@ -603,6 +607,7 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"pns",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"jpe",
|
||||
"gif",
|
||||
"webp",
|
||||
"tif",
|
||||
@@ -656,14 +661,15 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
|
||||
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib`, `.rle` and `.jpe`
|
||||
/// names of PNG, BMP and JPEG files (File › Open and Place still read them all). On Linux the desktop
|
||||
/// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers
|
||||
/// offer VectorCraft for them.
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
|
||||
"heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c",
|
||||
"jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
|
||||
];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
@@ -708,6 +714,7 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"pns",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"jpe",
|
||||
"gif",
|
||||
"webp",
|
||||
"tif",
|
||||
@@ -763,13 +770,14 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"doc",
|
||||
];
|
||||
|
||||
/// The extensions File › Open and Place read PNG, BMP and Photoshop files by: the format's own,
|
||||
/// then the other names its files have (`.pns`, `.dib` and `.rle`, `.pdd`). Exports write only
|
||||
/// the format's own extension.
|
||||
const READ_ALIASES: &[(&str, &[&str])] = &[("png", &["png", "pns"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])];
|
||||
/// The extensions File › Open and Place read PNG, JPEG, BMP and Photoshop files by: the format's
|
||||
/// own, then the other names its files have (`.pns`, `.jpe`, `.dib` and `.rle`, `.pdd`). Exports
|
||||
/// write only the format's own extensions.
|
||||
const READ_ALIASES: &[(&str, &[&str])] =
|
||||
&[("png", &["png", "pns"]), ("jpg", &["jpg", "jpeg", "jpe"]), ("bmp", &["bmp", "dib", "rle"]), ("psd", &["psd", "pdd"])];
|
||||
|
||||
/// The extensions File › Open and Place read format `f` by: its own, and for PNG, BMP and PSD
|
||||
/// those of [`READ_ALIASES`].
|
||||
/// The extensions File › Open and Place read format `f` by: its own, and for PNG, JPEG, BMP and
|
||||
/// PSD those of [`READ_ALIASES`].
|
||||
pub fn read_extensions(f: &Format) -> &'static [&'static str] {
|
||||
READ_ALIASES.iter().find(|(id, _)| *id == f.id).map_or(f.extensions, |(_, exts)| *exts)
|
||||
}
|
||||
@@ -777,9 +785,52 @@ pub fn read_extensions(f: &Format) -> &'static [&'static str] {
|
||||
/// The built-in readable format of extension `ext` (any case, leading dot allowed): [`format`]'s
|
||||
/// when it reads, else the one [`READ_ALIASES`] gives it (`.dib` is BMP). Importer plug-ins are
|
||||
/// not looked at ([`importer_formats`]).
|
||||
/// DWG drawings are readable only in a build with a DWG decoder ([`vectorcraft_cad::dwg::DECODES`]).
|
||||
pub fn readable_format(ext: &str) -> Option<&'static Format> {
|
||||
readable_format_in(ext, vectorcraft_cad::dwg::DECODES)
|
||||
}
|
||||
|
||||
/// The built-in format a file of extension `ext` is taken for ([`super::load::detect`]): [`readable_format`]'s,
|
||||
/// with DWG also in a build without a DWG decoder.
|
||||
pub(crate) fn recognized_format(ext: &str) -> Option<&'static Format> {
|
||||
readable_format_in(ext, true)
|
||||
}
|
||||
|
||||
/// [`readable_format`] in a build that decodes DWG drawings when `dwg`.
|
||||
fn readable_format_in(ext: &str, dwg: bool) -> Option<&'static Format> {
|
||||
let k = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
builtin(&k).filter(|f| f.read).or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id)))
|
||||
builtin(&k)
|
||||
.filter(|f| reads_in(f, dwg))
|
||||
.or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id)))
|
||||
}
|
||||
|
||||
/// Whether format `f` reads in this build: DWG drawings only where a DWG decoder is built in.
|
||||
pub(crate) fn reads(f: &Format) -> bool {
|
||||
reads_in(f, vectorcraft_cad::dwg::DECODES)
|
||||
}
|
||||
|
||||
/// Whether format `f` reads in a build that decodes DWG drawings when `dwg`.
|
||||
fn reads_in(f: &Format, dwg: bool) -> bool {
|
||||
f.read && (dwg || !reads_as_dwg(f.id))
|
||||
}
|
||||
|
||||
/// `exts` less `.dwg`, `.dws` and `.dwt` in a build without a DWG decoder (`dwg` false).
|
||||
fn listed_in(exts: &[&'static str], dwg: bool) -> Vec<&'static str> {
|
||||
exts.iter().copied().filter(|e| dwg || !matches!(*e, "dwg" | "dws" | "dwt")).collect()
|
||||
}
|
||||
|
||||
/// The extensions File › Open reads as a document in this build: [`OPEN_EXTS`], less `.dwg`, `.dws` and `.dwt` where
|
||||
/// no DWG decoder is built in ([`vectorcraft_cad::dwg::DECODES`]).
|
||||
pub fn open_exts() -> &'static [&'static str] {
|
||||
static EXTS: std::sync::LazyLock<Vec<&'static str>> = std::sync::LazyLock::new(|| listed_in(OPEN_EXTS, vectorcraft_cad::dwg::DECODES));
|
||||
&EXTS
|
||||
}
|
||||
|
||||
/// The extensions File › Place reads in this build: [`PLACE_EXTS`], less `.dwg` where no DWG
|
||||
/// decoder is built in ([`vectorcraft_cad::dwg::DECODES`]).
|
||||
pub fn place_exts() -> &'static [&'static str] {
|
||||
static EXTS: std::sync::LazyLock<Vec<&'static str>> = std::sync::LazyLock::new(|| listed_in(PLACE_EXTS, vectorcraft_cad::dwg::DECODES));
|
||||
&EXTS
|
||||
}
|
||||
|
||||
/// The readable format a file name's extension names ([`readable_format`]).
|
||||
@@ -789,7 +840,12 @@ pub fn readable_format_for_name(name: &str) -> Option<&'static Format> {
|
||||
|
||||
/// One dialog filter per readable format.
|
||||
fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f)))
|
||||
format_filters_in(vectorcraft_cad::dwg::DECODES)
|
||||
}
|
||||
|
||||
/// [`format_filters`] in a build that decodes DWG drawings when `dwg`.
|
||||
fn format_filters_in(dwg: bool) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
FORMATS.iter().filter(move |f| reads_in(f, dwg)).map(|f| (f.label, read_extensions(f)))
|
||||
}
|
||||
|
||||
/// Whether a file named `name` can only be opened, by an importer plug-in: an installed importer lists
|
||||
@@ -798,7 +854,7 @@ fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static st
|
||||
pub fn opens_with_importer(name: &str) -> bool {
|
||||
let ext = extension(name);
|
||||
!ext.is_empty()
|
||||
&& !PLACE_EXTS.contains(&ext.as_str())
|
||||
&& !place_exts().contains(&ext.as_str())
|
||||
&& !vectorcraft_plugins::import::for_extension(&ext).is_empty()
|
||||
&& !places_with_importer(name)
|
||||
}
|
||||
@@ -810,7 +866,7 @@ pub fn places_with_importer(name: &str) -> bool {
|
||||
let ext = extension(name);
|
||||
!ext.is_empty()
|
||||
&& readable_format(&ext).is_none()
|
||||
&& !PLACE_EXTS.contains(&ext.as_str())
|
||||
&& !place_exts().contains(&ext.as_str())
|
||||
&& !vectorcraft_plugins::import::placing(&ext).is_empty()
|
||||
}
|
||||
|
||||
@@ -856,7 +912,7 @@ fn importer_open_part() -> ImporterPart {
|
||||
{
|
||||
return part.clone();
|
||||
}
|
||||
let mut exts: Vec<&'static str> = OPEN_EXTS.to_vec();
|
||||
let mut exts: Vec<&'static str> = open_exts().to_vec();
|
||||
let mut filters = Vec::new();
|
||||
for f in importer_formats() {
|
||||
let own: Vec<&'static str> = f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !opens_as_other(e)).collect();
|
||||
@@ -871,7 +927,7 @@ fn importer_open_part() -> ImporterPart {
|
||||
let own: &'static [&'static str] = if own.len() == f.extensions.len() { f.extensions } else { Box::leak(own.into_boxed_slice()) };
|
||||
filters.push((f.label, own));
|
||||
}
|
||||
let exts: &'static [&'static str] = if exts.len() == OPEN_EXTS.len() { OPEN_EXTS } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let exts: &'static [&'static str] = if exts.len() == open_exts().len() { open_exts() } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let part = (exts, filters);
|
||||
*made = Some((revision, part.clone()));
|
||||
part
|
||||
@@ -898,7 +954,7 @@ pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static
|
||||
/// open dialogs whose files the built-in readers read (New from Template, Load Styles, a document
|
||||
/// picked for its swatches, symbols, brushes or graphic styles).
|
||||
pub fn builtin_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters())
|
||||
std::iter::once(("All readable files", open_exts())).chain(format_filters()).chain(other_open_filters())
|
||||
}
|
||||
|
||||
/// The open-dialog filters after the document formats: swatch and graphic style libraries,
|
||||
@@ -934,7 +990,7 @@ pub fn library_open_filters(
|
||||
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
|
||||
/// RTF and Word (`.docx` and `.doc`).
|
||||
pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All placeable files", PLACE_EXTS))
|
||||
std::iter::once(("All placeable files", place_exts()))
|
||||
.chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext))))
|
||||
.chain(std::iter::once(("Text", TEXT_EXTS)))
|
||||
.chain(std::iter::once(("RTF", RTF_EXTS)))
|
||||
@@ -956,12 +1012,16 @@ fn importer_place_part() -> ImporterPart {
|
||||
{
|
||||
return part.clone();
|
||||
}
|
||||
let mut exts: Vec<&'static str> = PLACE_EXTS.to_vec();
|
||||
let mut exts: Vec<&'static str> = place_exts().to_vec();
|
||||
let mut filters = Vec::new();
|
||||
for p in import::installed().into_iter().filter(|p| p.manifest().place) {
|
||||
let m = p.manifest();
|
||||
let own: Vec<&'static str> =
|
||||
m.extensions.iter().filter(|e| readable_format(e).is_none() && !PLACE_EXTS.contains(&e.as_str())).map(|e| registry::intern(e)).collect();
|
||||
let own: Vec<&'static str> = m
|
||||
.extensions
|
||||
.iter()
|
||||
.filter(|e| readable_format(e).is_none() && !place_exts().contains(&e.as_str()))
|
||||
.map(|e| registry::intern(e))
|
||||
.collect();
|
||||
if own.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -973,7 +1033,7 @@ fn importer_place_part() -> ImporterPart {
|
||||
let own: &'static [&'static str] = Box::leak(own.into_boxed_slice());
|
||||
filters.push((registry::intern(&m.name), own));
|
||||
}
|
||||
let exts: &'static [&'static str] = if exts.len() == PLACE_EXTS.len() { PLACE_EXTS } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let exts: &'static [&'static str] = if exts.len() == place_exts().len() { place_exts() } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let part = (exts, filters);
|
||||
*made = Some((revision, part.clone()));
|
||||
part
|
||||
@@ -1138,6 +1198,9 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = |pick: fn(&Format) -> bool| all().filter(|f| pick(f)).map(|f| f.id).collect::<Vec<_>>();
|
||||
let listed = |f: &Format| {
|
||||
let mut v = f.to_json();
|
||||
if f.read && !reads(f) {
|
||||
v["read"] = json!(false);
|
||||
}
|
||||
if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) {
|
||||
v["plugin"] = json!(id);
|
||||
if vectorcraft_plugins::import::by_format(f.id).is_some_and(|p| p.manifest().place) {
|
||||
@@ -1148,9 +1211,37 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
};
|
||||
Ok(json!({
|
||||
"formats": all().map(listed).collect::<Vec<_>>(),
|
||||
"readable": ids(|f| f.read),
|
||||
"readable": ids(reads),
|
||||
"writable": ids(|f| f.write),
|
||||
"openExtensions": open_extensions(),
|
||||
"unsupported": UNSUPPORTED.iter().map(Unsupported::to_json).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dwg_listing_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dwg_is_listed_only_in_a_build_that_decodes_it() {
|
||||
assert_eq!(readable_format_in("dwg", true).map(|f| f.id), Some("dwg"));
|
||||
assert_eq!(listed_in(OPEN_EXTS, true), OPEN_EXTS);
|
||||
assert_eq!(listed_in(PLACE_EXTS, true), PLACE_EXTS);
|
||||
assert!(format_filters_in(true).any(|(_, exts)| exts.contains(&"dwg")));
|
||||
// Without a decoder, nothing offers DWG drawings, standards files or templates.
|
||||
for e in ["dwg", "dws", "dwt"] {
|
||||
assert!(readable_format_in(e, false).is_none(), ".{e} is not readable");
|
||||
assert!(!listed_in(OPEN_EXTS, false).contains(&e), "File › Open does not list .{e}");
|
||||
assert!(!listed_in(PLACE_EXTS, false).contains(&e), "File › Place does not list .{e}");
|
||||
assert!(format_filters_in(false).all(|(_, exts)| !exts.contains(&e)), "no filter lists .{e}");
|
||||
}
|
||||
assert!(readable_format_in("dxf", false).is_some(), "DXF still is");
|
||||
let drawing_exts = OPEN_EXTS.iter().filter(|e| matches!(**e, "dwg" | "dws" | "dwt")).count();
|
||||
assert_eq!(listed_in(OPEN_EXTS, false).len(), OPEN_EXTS.len() - drawing_exts, "every other extension stays");
|
||||
// This build lists DWG exactly when it decodes it.
|
||||
let dwg = vectorcraft_cad::dwg::DECODES;
|
||||
assert_eq!(open_exts().contains(&"dwg"), dwg);
|
||||
assert_eq!(place_exts().contains(&"dwg"), dwg);
|
||||
assert_eq!(readable_format("dwg").is_some(), dwg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
//! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one
|
||||
//! around the art of a new document, and File › Place leaves them out.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
@@ -61,7 +62,7 @@ pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result<Option<Arc<Plu
|
||||
check_extension(C, plugin.manifest(), name)?;
|
||||
return Ok(Some(plugin));
|
||||
}
|
||||
if detect(name, bytes).is_some() {
|
||||
if detect(name, bytes).is_some_and(super::formats::reads) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(import::for_extension(&extension(name)).into_iter().next())
|
||||
@@ -97,7 +98,7 @@ fn importer_reads(ext: &str, mode: Mode) -> bool {
|
||||
super::readable_format(ext).is_none()
|
||||
&& match mode {
|
||||
Mode::Import => !import::for_extension(ext).is_empty(),
|
||||
Mode::Place => !super::PLACE_EXTS.contains(&ext) && !import::placing(ext).is_empty(),
|
||||
Mode::Place => !super::place_exts().contains(&ext) && !import::placing(ext).is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,7 +141,7 @@ fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> {
|
||||
if !explicit {
|
||||
let start: Vec<u8> = b64.bytes().filter(|b| !b.is_ascii_whitespace()).take(SNIFF_BYTES / 3 * 4).collect();
|
||||
let head = std::str::from_utf8(&start).ok().and_then(vectorcraft_format::base64_decode);
|
||||
if head.is_some_and(|head| detect(name, &head).is_some()) {
|
||||
if head.is_some_and(|head| detect(name, &head).is_some_and(super::formats::reads)) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -171,7 +172,7 @@ fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result<Vec<u8>
|
||||
if head.len() < SNIFF_BYTES {
|
||||
return Ok(head);
|
||||
}
|
||||
if detect(path, &head).is_some() {
|
||||
if detect(path, &head).is_some_and(super::formats::reads) {
|
||||
return super::read_file(path);
|
||||
}
|
||||
read_for_importer(path, mode)
|
||||
@@ -202,17 +203,43 @@ fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result<Vec<u8>> {
|
||||
/// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except
|
||||
/// that a file an importer would place (one `importer` names, or an extension no built-in format
|
||||
/// reads that an importer which places its files lists) is read, or decoded, only when it is at
|
||||
/// most [`import::MAX_INPUT_BYTES`] long.
|
||||
pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result<Source<'a>> {
|
||||
/// most [`import::MAX_INPUT_BYTES`] long. `given`: the bytes of the file `path` names, read already,
|
||||
/// which are borrowed instead of reading the path again (by the same size rule).
|
||||
pub(crate) fn place_source<'a, 'b>(p: &'a Value, cmd: &str, given: Option<&'b [u8]>) -> Result<PlaceSource<'a, 'b>> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }),
|
||||
Some(path) => {
|
||||
let bytes: Cow<'b, [u8]> = match given {
|
||||
Some(bytes) => {
|
||||
// The roots in force now still apply to the path, though it is not read again.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
super::may_read(path)?;
|
||||
let explicit = named(p, cmd)?.is_some();
|
||||
let importer = explicit || importer_reads(&extension(path), Mode::Place);
|
||||
let built_in = !explicit && detect(path, bytes.get(..SNIFF_BYTES).unwrap_or(bytes)).is_some();
|
||||
if importer && !built_in && bytes.len() > import::MAX_INPUT_BYTES {
|
||||
return Err(too_large(path, Mode::Place));
|
||||
}
|
||||
Cow::Borrowed(bytes)
|
||||
}
|
||||
None => Cow::Owned(read_path_for(path, p, Mode::Place, cmd)?),
|
||||
};
|
||||
Ok(PlaceSource { name: path, bytes, path: Some(path) })
|
||||
}
|
||||
None => {
|
||||
check_data_for(p, Mode::Place, cmd)?;
|
||||
super::source(p, cmd)
|
||||
let Source { name, bytes, path } = super::source(p, cmd)?;
|
||||
Ok(PlaceSource { name, bytes: Cow::Owned(bytes), path })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file [`place_source`] gives: as [`Source`], its bytes borrowed when they were given.
|
||||
pub(crate) struct PlaceSource<'a, 'b> {
|
||||
pub name: &'a str,
|
||||
pub bytes: Cow<'b, [u8]>,
|
||||
pub path: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// What [`read`] gives: the importer's format, the new document, its objects' ids, the artboards
|
||||
/// the importer returned and its warnings.
|
||||
type Read = (&'static Format, Document, Vec<NodeId>, Vec<import::OutArtboard>, Vec<String>);
|
||||
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_render::effects::pixel::LoadedTexture;
|
||||
use super::super::fileinfo::imported_title;
|
||||
use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param};
|
||||
use super::pdfimport::LoadOptions;
|
||||
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file, readable_format_for_name};
|
||||
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file};
|
||||
use crate::cmd::links::Resolved;
|
||||
use crate::{EngineError, Prefs};
|
||||
|
||||
@@ -93,7 +93,7 @@ pub fn file_name(name: &str) -> String {
|
||||
/// The readable format of a file: from its content (magic bytes) when that tells, else from the
|
||||
/// extension of `name`.
|
||||
pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
let by_name = readable_format_for_name(name);
|
||||
let by_name = super::formats::recognized_format(&super::extension(name));
|
||||
if vectorcraft_affinity::is_affinity(bytes) {
|
||||
return format("affinity");
|
||||
}
|
||||
@@ -308,10 +308,12 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool {
|
||||
|
||||
/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part
|
||||
/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages'
|
||||
/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its
|
||||
/// type as text?
|
||||
/// trim boxes by default, with its type as text?
|
||||
fn reads_layers_alone(opts: &LoadOptions) -> bool {
|
||||
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
reads_editing_copy(opts)
|
||||
&& !opts.explicit_crop_box
|
||||
&& opts.crop == vectorcraft_pdf::CropTo::Crop
|
||||
&& opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
}
|
||||
|
||||
/// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts`
|
||||
@@ -475,8 +477,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// The file is read and checked once, for the document it carries, its pages, the
|
||||
// editor's copy and its File Info.
|
||||
let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref());
|
||||
// Saved with Preserve Editing: the document it carries, unless some pages are picked.
|
||||
let editing = (opts.pages.is_none() && opts.native)
|
||||
// Restore the preserved document when opening all pages at their original size.
|
||||
let editing = (opts.pages.is_none() && opts.native && !opts.explicit_crop_box)
|
||||
.then(|| opened.as_ref().ok().and_then(|o| o.editing()))
|
||||
.flatten()
|
||||
.map(|e| (e.intact, move || Some(e.data)));
|
||||
@@ -524,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let alone = (r.only_text || empty)
|
||||
let alone = (!opts.explicit_crop_box && (r.only_text || empty))
|
||||
.then(copy_alone)
|
||||
.flatten()
|
||||
.and_then(|read| read.ok())
|
||||
|
||||
@@ -173,7 +173,13 @@ impl LoadOptions {
|
||||
/// box, a password, without its hidden layers, without the VectorCraft document it carries, its
|
||||
/// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name).
|
||||
pub fn is_partial(&self) -> bool {
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
|
||||
self.pages.is_some()
|
||||
|| self.crop != CropTo::default()
|
||||
|| self.explicit_crop_box
|
||||
|| self.password.is_some()
|
||||
|| !self.layers
|
||||
|| !self.native
|
||||
|| self.link_pages
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible
|
||||
|
||||
@@ -453,14 +453,14 @@ fn open_exts_cover_every_readable_format() {
|
||||
assert!(OPEN_EXTS.contains(e), "OPEN_EXTS lacks .{e} ({})", f.label);
|
||||
}
|
||||
}
|
||||
for e in OPEN_EXTS {
|
||||
assert!(readable_format(e).is_some(), ".{e} in OPEN_EXTS is no readable format");
|
||||
for e in open_exts() {
|
||||
assert!(readable_format(e).is_some(), ".{e} in open_exts() is no readable format");
|
||||
}
|
||||
let filters: Vec<_> = open_filters().collect();
|
||||
assert_eq!(filters[0], ("All readable files", OPEN_EXTS));
|
||||
assert_eq!(filters[0], ("All readable files", open_exts()));
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
13 + FORMATS.iter().filter(|f| f.read).count(),
|
||||
13 + FORMATS.iter().filter(|f| formats::reads(f)).count(),
|
||||
"and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \
|
||||
fonts, shortcut sets, scripts, plug-ins"
|
||||
);
|
||||
@@ -484,7 +484,7 @@ fn library_open_filters_list_library_formats_first() {
|
||||
let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS).collect();
|
||||
assert_eq!(filters[0], ("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS));
|
||||
assert!(filters[0].1.contains(&"ase"));
|
||||
assert_eq!(filters[1], ("All readable files", OPEN_EXTS));
|
||||
assert_eq!(filters[1], ("All readable files", open_exts()));
|
||||
let styles: &'static [&'static str] = std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT);
|
||||
for (label, exts) in [("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS), ("Graphic Style Libraries", styles)] {
|
||||
let filters: Vec<_> = library_open_filters(label, exts).collect();
|
||||
@@ -576,7 +576,7 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
|
||||
let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap();
|
||||
assert_eq!(png["options"]["scale"]["default"], Value::Null);
|
||||
assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len());
|
||||
assert_eq!(r["openExtensions"].as_array().unwrap().len(), open_exts().len());
|
||||
}
|
||||
|
||||
/// The format ids `command`'s params text lists for `format` (`a|b (default)|c (…)`, up to the
|
||||
|
||||
@@ -1395,8 +1395,7 @@ fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
|
||||
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
|
||||
/// Linked pages default to the trim box with the bleed and honor an explicit Crop Box.
|
||||
#[test]
|
||||
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
|
||||
@@ -1416,6 +1415,13 @@ fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
|
||||
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
|
||||
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true, "cropTo": "crop"})).unwrap();
|
||||
let cropped = &s.doc().unwrap().doc;
|
||||
assert!(cropped.artboards[0].rect.width() > board.width());
|
||||
let placed = &cropped.layers[0].children().unwrap()[0];
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!(p.page_box, vectorcraft_doc::PageBox::Crop);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! JPEG Options: colour model, coding method, scans, profile and image maps.
|
||||
//! JPEG Options: colour model, coding method, scans, profile and image maps; JPEG files named
|
||||
//! `.jpe` open and place.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -87,3 +88,28 @@ fn image_maps_list_the_objects_with_a_url() {
|
||||
// One file only: Export for Screens can't add the map.
|
||||
assert!(s.execute("document.exportForScreens", &json!({"formats": [{"format": "jpg", "imageMap": "client"}]})).is_err());
|
||||
}
|
||||
|
||||
/// JPEG files named `.jpe` open and place as JPEG, in any case; the dialogs and a drop on the
|
||||
/// window take them by their extension, the desktop packaging doesn't associate them, and exports
|
||||
/// still write `.jpg`.
|
||||
#[test]
|
||||
fn jpe_files_open_and_place() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
|
||||
let jpg = b64(&s.execute("document.export", &json!({"format": "jpg"})).unwrap());
|
||||
let data = vectorcraft_format::base64_encode(&jpg);
|
||||
for name in ["art.jpe", "ART.JPE"] {
|
||||
assert_eq!(readable_format_for_name(name).map(|f| f.id), Some("jpg"), "{name}");
|
||||
let r = s.execute("document.open", &json!({"name": name, "dataBase64": data})).unwrap();
|
||||
assert_eq!((&r["format"], &r["warnings"]), (&json!("jpg"), &json!([])), "{name}: {r}");
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": name, "dataBase64": data})).unwrap();
|
||||
assert_eq!((&r["format"], r["ids"].as_array().map(Vec::len)), (&json!("jpg"), Some(1)), "{name}: {r}");
|
||||
}
|
||||
assert!(OPEN_EXTS.contains(&"jpe") && PLACE_EXTS.contains(&"jpe") && UNASSOCIATED_EXTS.contains(&"jpe"));
|
||||
let jpeg = ("JPEG", &["jpg", "jpeg", "jpe"][..]);
|
||||
assert!(open_filters().any(|f| f == jpeg) && place_filters().any(|f| f == jpeg));
|
||||
assert!(!export_extensions().contains(&"jpe"));
|
||||
assert!(format_for_name("x.jpe").is_none() && writable_format(None, Some("x.jpe")).is_err());
|
||||
assert!(s.execute("document.export", &json!({"path": "x.jpe"})).is_err());
|
||||
}
|
||||
|
||||
@@ -138,8 +138,38 @@ fn targa_depth_reaches_the_file() {
|
||||
}
|
||||
let tga = export(&mut s, json!({"format": "tga"}));
|
||||
assert_eq!(tga[16], 24, "24 bits by default");
|
||||
for bad in [json!({"depth": 8}), json!({"colorModel": "gray"})] {
|
||||
assert!(s.execute("document.export", &merge(json!({"format": "tga"}), bad.clone())).is_err(), "{bad}");
|
||||
for bad in [
|
||||
json!({"depth": 8}),
|
||||
json!({"colorModel": "cmyk"}),
|
||||
json!({"colorModel": "lab"}),
|
||||
json!({"colorModel": "gray", "depth": 24}),
|
||||
json!({"colorModel": "gray", "depth": 32}),
|
||||
] {
|
||||
let e = s.execute("document.export", &merge(json!({"format": "tga"}), bad.clone())).unwrap_err();
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targa_color_model_gray_writes_grayscale() {
|
||||
let mut s = session();
|
||||
let gray = export(&mut s, json!({"format": "tga", "colorModel": "gray"}));
|
||||
assert_eq!((gray[2], gray[16], gray[17]), (3, 8, 0), "grayscale, 8 bits by default, no alpha");
|
||||
let img = image::load_from_memory_with_format(&gray, image::ImageFormat::Tga).unwrap().to_rgba8();
|
||||
assert_eq!(img.dimensions(), (60, 40));
|
||||
assert_eq!(img.get_pixel(5, 5).0, [255; 4], "flattened on white");
|
||||
let black = img.get_pixel(40, 20).0;
|
||||
assert!(black[0] == black[1] && black[1] == black[2] && black[0] < 80, "{black:?}");
|
||||
|
||||
let alpha = export(&mut s, json!({"format": "tga", "colorModel": "gray", "depth": 16}));
|
||||
assert_eq!((alpha[2], alpha[16], alpha[17]), (3, 16, 8), "grayscale with an 8-bit alpha");
|
||||
let img = image::load_from_memory_with_format(&alpha, image::ImageFormat::Tga).unwrap().to_rgba8();
|
||||
assert_eq!(img.get_pixel(5, 5).0[3], 0, "transparent where nothing is drawn");
|
||||
assert_eq!(img.get_pixel(40, 20).0[3], 255);
|
||||
|
||||
for file in [gray, alpha] {
|
||||
let r = s.execute("document.open", &json!({"name": "back.tga", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap();
|
||||
assert_eq!(r["format"], "tga");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one is an error",
|
||||
"{index | indices: [index…]} delete artboards (with their guides) in one step; one is always left, and a locked one, or the one an open Create Font Sheet dialog uses, is an error",
|
||||
has_doc,
|
||||
artboard_delete
|
||||
),
|
||||
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Empty Artboards",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go) → {deleted: [index…]} (the indices before deleting)",
|
||||
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go); an error, with nothing deleted, when one of them is the artboard an open Create Font Sheet dialog uses → {deleted: [index…]} (the indices before deleting)",
|
||||
has_empty_artboards,
|
||||
artboard_delete_empty
|
||||
),
|
||||
@@ -1225,11 +1225,25 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn artboard_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let indices = super::panelcmds::artboard_indices(&s.doc()?.doc, p, "artboard.delete")?;
|
||||
refuse_guarded(s, &indices)?;
|
||||
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
|
||||
s.edit("Delete Artboard", |d, sel| remove_artboards(d, sel, &indices))?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The session's artboard deletion guard's message when deleting artboards `indices` of the
|
||||
/// active document would delete the artboard it protects.
|
||||
pub(crate) fn refuse_guarded(s: &Session, indices: &[usize]) -> Result<()> {
|
||||
let Some(guard) = &s.artboard_deletion_guard else { return Ok(()) };
|
||||
let state = s.doc()?;
|
||||
if (state.uid, state.reverts) == guard.document
|
||||
&& indices.iter().any(|&index| state.doc.artboards.get(index).is_some_and(|a| a.id == guard.artboard))
|
||||
{
|
||||
return Err(EngineError::Other(guard.message.clone()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete artboards `indices` (sorted, each once) of `d` with their guides; at least one must be
|
||||
/// left. The other artboards keep their order, no later artboard takes a deleted one's id, and
|
||||
/// `sel` forgets the deleted guides. One walk over the artboards and one over the ruler guides,
|
||||
@@ -1306,6 +1320,7 @@ fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if indices.is_empty() {
|
||||
return Err(EngineError::Other("no empty artboards to delete".into()));
|
||||
}
|
||||
refuse_guarded(s, &indices)?;
|
||||
s.edit("Delete Empty Artboards", |d, sel| remove_artboards(d, sel, &indices))?;
|
||||
Ok(json!({ "deleted": indices }))
|
||||
}
|
||||
|
||||
@@ -3061,6 +3061,22 @@ fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::R
|
||||
if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) }
|
||||
}
|
||||
|
||||
/// `path` with `.ext` added when it has no extension: the file Unembed writes for a `path` given.
|
||||
fn with_unembed_extension(path: &str, ext: &str) -> String {
|
||||
if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() }
|
||||
}
|
||||
|
||||
/// The file `links.unembed {id, path}` writes embedded image `id` of the active document to: `path`
|
||||
/// with the extension of the format the image is stored in added when `path` has none. `None` when
|
||||
/// `id` is not an embedded image there.
|
||||
pub fn unembed_path(s: &Session, id: u64, path: &str) -> Option<String> {
|
||||
let st = s.doc().ok()?;
|
||||
let doc = with_brush_art(&st.doc);
|
||||
let im = image_of(&doc, NodeId(id)).filter(|im| im.link.is_none())?;
|
||||
let blob = st.doc.images.get(&im.key)?;
|
||||
Some(with_unembed_extension(path, stored_extension(blob)))
|
||||
}
|
||||
|
||||
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.unembed";
|
||||
let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null());
|
||||
@@ -3097,7 +3113,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());
|
||||
return Ok(json!({ "name": format!("{stem}.{ext}"), "dataBase64": vectorcraft_format::base64_encode(&bytes) }));
|
||||
};
|
||||
let path = absolute_path(&if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() });
|
||||
let path = absolute_path(&with_unembed_extension(path, &ext));
|
||||
// Read before writing: pixels that can't be read leave no file behind.
|
||||
let img = linked_image(&bytes, Some(&path))?;
|
||||
write_file(&path, &bytes)?;
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.cut")?;
|
||||
@@ -366,6 +366,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result<Val
|
||||
return Err(EngineError::Other("a document needs at least one artboard".into()));
|
||||
}
|
||||
if cut {
|
||||
super::layer::refuse_guarded(s, &indices)?;
|
||||
refuse_locked(&st.doc, &indices)?;
|
||||
}
|
||||
let art = st.doc.paint_order(arts.into_iter().flat_map(|(_, a)| a));
|
||||
|
||||
@@ -1089,45 +1089,82 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(),
|
||||
}
|
||||
};
|
||||
let changed = super::overprint::edit_counted(s, "Reverse Path Direction", |d| {
|
||||
// A compound path's own strokes run along its members' subpaths in order, so they turn
|
||||
// with them, read before any member turns.
|
||||
let compounds: BTreeSet<NodeId> = ids.iter().map(|id| compound_or_self(d, *id)).filter(|c| ids.binary_search(c).is_err()).collect();
|
||||
for c in compounds {
|
||||
let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue };
|
||||
let flip: Vec<bool> = children
|
||||
.iter()
|
||||
.filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] }))
|
||||
.flatten()
|
||||
.collect();
|
||||
if flip.contains(&true)
|
||||
&& let Some(n) = d.node_mut(c)
|
||||
{
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
let mut d = (*s.doc()?.doc).clone();
|
||||
// A compound path's own strokes run along its members' subpaths in order, so they turn
|
||||
// with them, read before any member turns.
|
||||
let compounds: BTreeSet<NodeId> = ids.iter().map(|id| compound_or_self(&d, *id)).filter(|c| ids.binary_search(c).is_err()).collect();
|
||||
for c in compounds {
|
||||
let Some(NodeKind::Compound { children, .. }) = d.node(c).map(|n| &n.kind) else { continue };
|
||||
let flip: Vec<bool> = children
|
||||
.iter()
|
||||
.filter_map(|m| m.path_data().map(|pd| if ids.binary_search(&m.id).is_ok() { flip_of(pd) } else { vec![false; pd.subpaths.len()] }))
|
||||
.flatten()
|
||||
.collect();
|
||||
if flip.contains(&true)
|
||||
&& let Some(n) = d.node_mut(c)
|
||||
{
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
}
|
||||
}
|
||||
let mut turned = Vec::new();
|
||||
for id in &ids {
|
||||
let path = path_mut(&mut d, *id)?;
|
||||
let flip = flip_of(path);
|
||||
if !flip.contains(&true) {
|
||||
continue;
|
||||
}
|
||||
// The stroke's width profile and pen recordings turn with the path, read before it turns.
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
}
|
||||
let path = path_mut(&mut d, *id)?;
|
||||
for (sp, f) in path.subpaths.iter_mut().zip(&flip) {
|
||||
if *f {
|
||||
sp.reverse();
|
||||
}
|
||||
}
|
||||
let mut changed = 0;
|
||||
for id in &ids {
|
||||
let path = path_mut(d, *id)?;
|
||||
let flip = flip_of(path);
|
||||
if !flip.contains(&true) {
|
||||
continue;
|
||||
}
|
||||
// The stroke's width profile and pen recordings turn with the path, read before it turns.
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
|
||||
}
|
||||
let path = path_mut(d, *id)?;
|
||||
for (sp, f) in path.subpaths.iter_mut().zip(flip) {
|
||||
if f {
|
||||
sp.reverse();
|
||||
turned.push((*id, flip));
|
||||
}
|
||||
if !turned.is_empty() {
|
||||
s.edit("Reverse Path Direction", |doc, sel| {
|
||||
*doc = d;
|
||||
for (id, flip) in &turned {
|
||||
if let Some(path) = doc.node(*id).and_then(Node::path_data) {
|
||||
reverse_selected_anchors(sel, *id, path, flip);
|
||||
}
|
||||
}
|
||||
changed += 1;
|
||||
}
|
||||
Ok(changed)
|
||||
})?;
|
||||
Ok(json!({ "changed": changed }))
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "changed": turned.len() }))
|
||||
}
|
||||
|
||||
/// Point the selected anchors, selected segments and key anchor of `sel` on path `id` at the same
|
||||
/// points after the subpaths of `path` marked in `flip` were reversed ([`SubPath::reverse`]). In a
|
||||
/// reversed subpath of `n` anchors, anchor `i` becomes anchor `n - 1 - i` and segment `j` becomes
|
||||
/// segment `n - 2 - j`; a closed subpath's closing segment (`n - 1`) stays its closing segment.
|
||||
fn reverse_selected_anchors(sel: &mut Selection, id: NodeId, path: &PathData, flip: &[bool]) {
|
||||
let reversed = |si: usize| path.subpaths.get(si).filter(|_| flip.get(si) == Some(&true)).map(|sp| (sp.anchors.len(), sp.closed));
|
||||
let anchor = |(si, ai): AnchorRef| match reversed(si) {
|
||||
Some((n, _)) if ai < n => (si, n - 1 - ai),
|
||||
_ => (si, ai),
|
||||
};
|
||||
let segment = |(si, j): SegmentRef| match reversed(si) {
|
||||
Some((n, true)) if j < n => (si, (2 * n - 2 - j) % n),
|
||||
Some((n, false)) if j < n.saturating_sub(1) => (si, n - 2 - j),
|
||||
_ => (si, j),
|
||||
};
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
*set = set.iter().map(|r| anchor(*r)).collect();
|
||||
}
|
||||
if let Some(set) = sel.segments.get_mut(&id) {
|
||||
*set = set.iter().map(|r| segment(*r)).collect();
|
||||
}
|
||||
if let Some((key, r)) = sel.key_anchor
|
||||
&& key == id
|
||||
{
|
||||
sel.key_anchor = Some((id, anchor(r)));
|
||||
}
|
||||
}
|
||||
|
||||
/// First and last anchor points of a subpath.
|
||||
@@ -2409,8 +2446,9 @@ fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f
|
||||
shares
|
||||
}
|
||||
|
||||
/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors and
|
||||
/// selected segments after it on that subpath one higher, so the selection keeps the same points.
|
||||
/// After an anchor is added at `(si, added)` of path `id`, number the direct-selected anchors,
|
||||
/// selected segments and key anchor after it on that subpath one higher, so the selection keeps
|
||||
/// the same points.
|
||||
/// A selected segment that the new anchor splits stays selected as its two halves, and the new
|
||||
/// anchor joins its ends in the anchors that move with it.
|
||||
fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) {
|
||||
@@ -2419,6 +2457,14 @@ fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usiz
|
||||
// renumbering saturates instead of overflowing.
|
||||
*set = set.iter().map(|&(s, a)| if s == si && a >= added { (s, a.saturating_add(1)) } else { (s, a) }).collect();
|
||||
}
|
||||
// The key anchor moves along with the anchors after the new one.
|
||||
if let Some((key, (s, a))) = sel.key_anchor
|
||||
&& key == id
|
||||
&& s == si
|
||||
&& a >= added
|
||||
{
|
||||
sel.key_anchor = Some((id, (s, a.saturating_add(1))));
|
||||
}
|
||||
let split = added.checked_sub(1);
|
||||
if sel.segments.get(&id).is_some_and(|set| split.is_some_and(|g| set.contains(&(si, g)))) {
|
||||
sel.anchors.entry(id).or_default().insert((si, added));
|
||||
|
||||
@@ -183,13 +183,13 @@ pub(crate) fn pt_per_px(ppi: Option<(f64, f64)>) -> (f64, f64) {
|
||||
|
||||
/// [`load_sliced`] without the slices.
|
||||
fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loaded> {
|
||||
load_into(p, cmd, board, link_pdf, &mut vec![])
|
||||
load_into(p, cmd, board, link_pdf, None, &mut vec![])
|
||||
}
|
||||
|
||||
/// [`load_into`], with the slices of a PSD or PSB file that `importSlices` brings in.
|
||||
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<(Loaded, Slices)> {
|
||||
fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: Option<&[u8]>) -> Result<(Loaded, Slices)> {
|
||||
let mut slices = vec![];
|
||||
let l = load_into(p, cmd, board, link_pdf, &mut slices)?;
|
||||
let l = load_into(p, cmd, board, link_pdf, given, &mut slices)?;
|
||||
Ok((l, slices))
|
||||
}
|
||||
|
||||
@@ -197,9 +197,10 @@ fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Res
|
||||
/// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed
|
||||
/// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB
|
||||
/// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one
|
||||
/// no built-in format reads) is read by it ([`plugin_art`]).
|
||||
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_out: &mut Slices) -> Result<Loaded> {
|
||||
let src = fileio::importer::place_source(p, cmd)?;
|
||||
/// no built-in format reads) is read by it ([`plugin_art`]). `given`: the bytes of the file `p`'s
|
||||
/// `path` names, read already ([`PlaceJob::with_bytes`]).
|
||||
fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: Option<&[u8]>, slices_out: &mut Slices) -> Result<Loaded> {
|
||||
let src = fileio::importer::place_source(p, cmd, given)?;
|
||||
let name = fileio::file_name(src.name);
|
||||
if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? {
|
||||
return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd);
|
||||
@@ -238,11 +239,14 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, slices_o
|
||||
}
|
||||
return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None });
|
||||
}
|
||||
let Some(format) = fileio::detect(src.name, &src.bytes) else {
|
||||
return match fileio::importer::for_place(src.name) {
|
||||
Some(plugin) => plugin_art(name, src.name, &src.bytes, &plugin, p, cmd),
|
||||
None => Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))),
|
||||
};
|
||||
let format = fileio::detect(src.name, &src.bytes);
|
||||
if format.is_none_or(|f| !fileio::reads(f))
|
||||
&& let Some(plugin) = fileio::importer::for_place(src.name)
|
||||
{
|
||||
return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd);
|
||||
}
|
||||
let Some(format) = format else {
|
||||
return Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")));
|
||||
};
|
||||
let page = match p.get("page") {
|
||||
None => 1,
|
||||
@@ -760,8 +764,13 @@ pub struct PlaceJob {
|
||||
/// The object Replace swaps as it was when Place started.
|
||||
replaced: Option<Node>,
|
||||
target: Option<Rect>,
|
||||
/// The bytes of the file `path` names, read already ([`PlaceJob::with_bytes`]).
|
||||
bytes: Option<GivenBytes>,
|
||||
}
|
||||
|
||||
/// The bytes of a file read already, shared with whoever read them ([`PlaceJob::with_bytes`]).
|
||||
pub type GivenBytes = Arc<dyn AsRef<[u8]> + Send + Sync>;
|
||||
|
||||
/// A file [`PlaceJob::read`] read, which [`Session::place_read`] places.
|
||||
pub struct PlaceRead {
|
||||
job: PlaceJob,
|
||||
@@ -775,6 +784,14 @@ impl PlaceJob {
|
||||
str_param(&self.params, "path").or_else(|| str_param(&self.params, "name")).map(fileio::file_name).unwrap_or_else(|| "Untitled".into())
|
||||
}
|
||||
|
||||
/// The job placing `bytes` as the file its `path` names, which [`PlaceJob::read`] then does not
|
||||
/// read again: the placed object's link and the journaled params keep the path. Without a
|
||||
/// `path` the bytes are not used.
|
||||
pub fn with_bytes(mut self, bytes: GivenBytes) -> Self {
|
||||
self.bytes = Some(bytes);
|
||||
self
|
||||
}
|
||||
|
||||
/// Read and decode the file, as `file.place` does, without the session. The pixels of a PNG,
|
||||
/// JPEG, GIF or WebP file are decoded here to check that they can be read (an error when they
|
||||
/// can't), a linked image's preview is made from that decode, and the decoded pixels are kept in
|
||||
@@ -782,7 +799,7 @@ impl PlaceJob {
|
||||
/// ([`super::links::readable_and_kept`]).
|
||||
pub fn read(self) -> Result<PlaceRead> {
|
||||
crate::cancel::check()?;
|
||||
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?;
|
||||
let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true, self.bytes.as_deref().map(AsRef::as_ref))?;
|
||||
let linked = loaded.link.is_some() && bool_or(&self.params, "link", true);
|
||||
match &mut loaded.art {
|
||||
Art::Image(img, _) => {
|
||||
@@ -941,12 +958,12 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
|
||||
};
|
||||
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
|
||||
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
|
||||
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at), bytes: None })
|
||||
}
|
||||
|
||||
/// Place the file `read` holds in the active document.
|
||||
fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
let PlaceRead { job: PlaceJob { params, old, target: read_for, .. }, mut loaded, slices: read_slices } = read;
|
||||
let PlaceRead { job: PlaceJob { params, old, target: read_for, bytes, .. }, mut loaded, slices: read_slices } = read;
|
||||
let p = ¶ms;
|
||||
let template = bool_or(p, "template", false);
|
||||
let at = at_param(p)?;
|
||||
@@ -957,10 +974,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
// The artboard under `at` as it is now, as a replay of the journal finds it: a DXF drawing laid
|
||||
// out on the artboard it was read for is read again when that artboard changed meanwhile.
|
||||
// out on the artboard it was read for is read again when that artboard changed meanwhile, from
|
||||
// the same bytes when the job was given them.
|
||||
let target = board_at(&st.doc, at);
|
||||
if loaded.board.is_some() && target != read_for {
|
||||
loaded = load(p, PLACE, target, true)?;
|
||||
loaded = load_into(p, PLACE, target, true, bytes.as_deref().map(AsRef::as_ref), &mut vec![])?;
|
||||
}
|
||||
// Type reflows rather than scales: its frame takes the size it is placed at.
|
||||
let is_text = matches!(loaded.art, Art::Text(_));
|
||||
@@ -1347,7 +1365,7 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["link"], "file.place.info")?;
|
||||
check_numbers(p, &["thumbnail"], "file.place.info")?;
|
||||
// A PDF/.ai page linked or not has the same size and art.
|
||||
let (mut l, slices) = load_sliced(p, "file.place.info", None, false)?;
|
||||
let (mut l, slices) = load_sliced(p, "file.place.info", None, false, None)?;
|
||||
let natural = l.natural;
|
||||
let mut out = json!({
|
||||
"name": l.name,
|
||||
|
||||
@@ -767,6 +767,7 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
"addon.pen.nextSegment",
|
||||
"addon.type.fontSheet",
|
||||
"addon.type.numbers",
|
||||
"color.contrast",
|
||||
"effect.refreshDeferred",
|
||||
|
||||
@@ -39,7 +39,7 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 39] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
@@ -70,6 +70,7 @@ const REPLAY_ONLY: [(&str, &str); 39] = [
|
||||
("artboard.distribute", "activeArtboard"),
|
||||
("artboard.distributeSpacing", "selectedArtboards"),
|
||||
("artboard.distributeSpacing", "activeArtboard"),
|
||||
("addon.type.fontSheet", "activeArtboard"),
|
||||
("addon.document.floodFillArtboards", "activeArtboard"),
|
||||
("edit.copy", "selectedArtboards"),
|
||||
("edit.copy", "art"),
|
||||
|
||||
@@ -118,7 +118,7 @@ pub struct DocState {
|
||||
/// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not
|
||||
/// change it, and a batch that fails puts it back with the document.
|
||||
pub reverts: u64,
|
||||
/// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects
|
||||
/// Advances when Undo, Redo or a canceled undo group restores an older document snapshot. The same node ID can name different objects
|
||||
/// across that boundary.
|
||||
pub history_restores: u64,
|
||||
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
|
||||
|
||||
@@ -19,6 +19,10 @@ pub struct Interaction {
|
||||
/// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an
|
||||
/// interaction runs its commands inside it.
|
||||
pub(crate) tool: bool,
|
||||
/// A dialog's live preview began it: a command from outside the dialog runs as a step of its
|
||||
/// own under it, as it does under a drag, so the next preview, OK and Cancel keep its edit
|
||||
/// (a `file.*` command still runs inside it).
|
||||
pub dialog: bool,
|
||||
/// A tool began or joined this interaction through `Action::Begin`.
|
||||
pub(crate) tool_joined: bool,
|
||||
/// A replaced or canceled preview restores these new-art paints from before the interaction.
|
||||
@@ -100,6 +104,10 @@ pub(crate) struct HeldInteraction {
|
||||
/// The new-art paints when the command began: a change the command makes to them stays when
|
||||
/// the interaction's next preview or a cancel puts back the paints it began with.
|
||||
pub(crate) paint: vectorcraft_tools::PaintDefaults,
|
||||
/// The command's own selection steps went into the journal before it ran.
|
||||
pub(crate) journaled: bool,
|
||||
/// The command returned an error.
|
||||
pub(crate) refused: bool,
|
||||
}
|
||||
|
||||
/// The per-document state an interaction puts back when it is canceled, besides the document and
|
||||
|
||||
@@ -58,6 +58,12 @@ pub use vectorcraft_tools as tools;
|
||||
pub use vectorcraft_doc::MAX_COORD;
|
||||
const _: () = assert!(vectorcraft_doc::MAX_DEPTH == 32, "TOO_DEEP (and its catalog rows) names the cap");
|
||||
|
||||
pub struct ArtboardDeletionGuard {
|
||||
pub document: (u64, u64),
|
||||
pub artboard: u32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// The maximum number of newest swatch renames a session keeps until they are taken.
|
||||
pub(crate) const MAX_SWATCH_RENAMES: usize = 64;
|
||||
|
||||
@@ -67,6 +73,7 @@ pub struct Session {
|
||||
pub prefs: Prefs,
|
||||
/// Whether Caps Lock is on, as the desktop host reports it; never saved with the preferences.
|
||||
pub caps_lock: bool,
|
||||
pub artboard_deletion_guard: Option<ArtboardDeletionGuard>,
|
||||
/// Fill/stroke for new art (the toolbar proxy).
|
||||
pub paint: PaintDefaults,
|
||||
/// Which proxy is in front (true = Fill, false = Stroke) — the X key toggles.
|
||||
|
||||
@@ -98,6 +98,10 @@ pub struct ScriptDialog {
|
||||
/// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app
|
||||
/// gives an RGB pick back as CMYK. False for the other dialogs.
|
||||
pub cmyk_document: bool,
|
||||
/// `showColorPicker`: the RGB and CMYK profiles the run's active document is assigned (`None`:
|
||||
/// none) when the picker opens, which the app converts the pick through. `(None, None)` for the
|
||||
/// other dialogs.
|
||||
pub profiles: (Option<String>, Option<String>),
|
||||
}
|
||||
|
||||
/// The answer to a [`ScriptDialog`].
|
||||
@@ -705,7 +709,10 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
if preset.len() > MAX_PROMPT_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
|
||||
}
|
||||
wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false })
|
||||
wait_or_answer(
|
||||
host,
|
||||
ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false, profiles: (None, None) },
|
||||
)
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK,
|
||||
@@ -713,7 +720,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostError> {
|
||||
// During a slice the session holds the run's working copy, whose active document may be one
|
||||
// the script made; between slices the app sees the documents as they were before the run.
|
||||
let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk);
|
||||
let (cmyk_document, profiles) = host
|
||||
.session
|
||||
.borrow()
|
||||
.active()
|
||||
.map_or((false, (None, None)), |s| (s.doc.color_mode == crate::doc::ColorMode::Cmyk, crate::cmd::colormgmt::doc_profiles(&s.doc)));
|
||||
let dialog = ScriptDialog {
|
||||
kind: DialogKind::ColorPicker,
|
||||
message: String::new(),
|
||||
@@ -723,6 +734,7 @@ pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostE
|
||||
preset: String::new(),
|
||||
color: Some(color),
|
||||
cmyk_document,
|
||||
profiles,
|
||||
};
|
||||
wait_or_answer(host, dialog)
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS};
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS, REMOVE_ALL_VISITS};
|
||||
|
||||
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
@@ -707,13 +707,19 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many objects [`items_remove_all`] walked on this thread, for the tests.
|
||||
pub(crate) static REMOVE_ALL_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or
|
||||
/// locked path, one in a hidden or locked layer or group, or one on a locked artboard stops it
|
||||
/// before anything is deleted, as `PageItems.removeAll()` does. A compound path's
|
||||
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
|
||||
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path
|
||||
/// or visible type that lays out glyphs to clip by.
|
||||
/// that keeps other objects, or leave a compound path or group that clips one with no visible path,
|
||||
/// image, placed document or visible type that lays out glyphs to clip by.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let (doc, c) = items_scope(h, a)?;
|
||||
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
|
||||
@@ -727,9 +733,42 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect();
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
let mut next: Vec<_> = d.layers.iter().collect();
|
||||
// The document's list is checked against every object. A layer's or group's list is checked
|
||||
// against the container's subtree, or, when the container lies in the clipping path of a
|
||||
// clipping group above it, against the subtree of the highest such clipping path and the
|
||||
// group it clips; no other outline holds its paths. An empty list is not walked.
|
||||
let mut next: Vec<&Arc<crate::doc::Node>> = Vec::new();
|
||||
let mut nodes = Vec::new();
|
||||
if !ids.is_empty() {
|
||||
match c.and_then(|c| d.index_path(c)) {
|
||||
None => next.extend(d.layers.iter()),
|
||||
Some(at) => {
|
||||
// A damaged file can give two objects one id; a path that the id finds outside
|
||||
// the container would be deleted in place of the container's own.
|
||||
if let Some(id) = ids.iter().find(|i| d.index_path(**i).is_none_or(|p| p.len() != at.len() + 1 || !p.starts_with(&at))) {
|
||||
return Err(HostError::Error(format!("cannot delete PathItem {}: its id also names another object", id.0)));
|
||||
}
|
||||
let mut line: Vec<&Arc<crate::doc::Node>> = Vec::with_capacity(at.len());
|
||||
let mut kids = d.layers.as_slice();
|
||||
for &i in &at {
|
||||
let Some(n) = kids.get(i) else { break };
|
||||
line.push(n);
|
||||
kids = n.children().map_or(&[][..], Vec::as_slice);
|
||||
}
|
||||
// A clipping path is its group's first child, found by place, not by id.
|
||||
let clip = (1..line.len()).find(|&k| line[k - 1].clips() && at[k] == 0);
|
||||
if let Some(k) = clip {
|
||||
#[cfg(test)]
|
||||
REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1));
|
||||
nodes.push(line[k - 1]);
|
||||
}
|
||||
next.extend(line.get(clip.unwrap_or(line.len().saturating_sub(1))).copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
while let Some(n) = next.pop() {
|
||||
#[cfg(test)]
|
||||
REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1));
|
||||
nodes.push(n);
|
||||
next.extend(n.children().into_iter().flatten());
|
||||
}
|
||||
@@ -768,12 +807,15 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
{
|
||||
going.insert(n.id);
|
||||
}
|
||||
// A clip outline takes in visible paths and the glyphs of visible type, as
|
||||
// `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no
|
||||
// outline. A list marker is a glyph too, so whitespace-only type is laid out as well.
|
||||
// A clip outline takes in visible paths, the frames of visible images and placed
|
||||
// documents that enclose an area, and the glyphs of visible type, as `push_clip_shapes` does; type that lays
|
||||
// out no glyphs (blank, or overset) gives no outline. A list marker is a glyph too, so
|
||||
// whitespace-only type is laid out as well.
|
||||
let shape = n.visible
|
||||
&& match &n.kind {
|
||||
NodeKind::Path { .. } => true,
|
||||
// A frame collapsed to a line or a point encloses nothing to clip by.
|
||||
NodeKind::Image(_) | NodeKind::PlacedDocument(_) => n.clip_shapes(None).iter().any(|(frame, _)| encloses(frame)),
|
||||
NodeKind::Text(t) => {
|
||||
in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty()
|
||||
}
|
||||
@@ -785,10 +827,18 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if n.visible && ((shape && !going.contains(&n.id)) || inner) {
|
||||
geometry.insert(n.id);
|
||||
}
|
||||
// The live geometry effects of what stays in the clipping path reshape the region it
|
||||
// clips by, as the renderer draws it; deleting paths that lets an effect shrink the
|
||||
// region to nothing leaves no outline. A region that was empty before is left as it is.
|
||||
// The region is the area the outline fills under its fill rule, so outlines that run
|
||||
// opposite ways over the same area under nonzero fill nothing.
|
||||
let reshaped_empty = |m: &vectorcraft_doc::Node| {
|
||||
vectorcraft_render::effects::reshaped_clip_outline(m).is_some_and(|o| !o.is_some_and(|(bp, rule)| fills(&bp, rule)))
|
||||
};
|
||||
if n.clips()
|
||||
&& let Some(mask) = kids.first()
|
||||
&& affected.contains(&mask.id)
|
||||
&& !geometry.contains(&mask.id)
|
||||
&& (!geometry.contains(&mask.id) || (reshaped_empty(&without(mask, &going, &affected)) && !reshaped_empty(mask)))
|
||||
&& kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
&& masks.len() < 20
|
||||
{
|
||||
@@ -819,6 +869,57 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// Whether a subpath of `outline` encloses an area. Each subpath's area is measured from its first
|
||||
/// point, so its position does not change the result, and an area within roundoff of its own
|
||||
/// bounding box's is counted as none.
|
||||
fn encloses(outline: &kurbo::BezPath) -> bool {
|
||||
let mut subpaths: Vec<kurbo::BezPath> = Vec::new();
|
||||
for el in outline.elements() {
|
||||
if matches!(el, kurbo::PathEl::MoveTo(_)) || subpaths.is_empty() {
|
||||
subpaths.push(kurbo::BezPath::new());
|
||||
}
|
||||
if let Some(last) = subpaths.last_mut() {
|
||||
last.push(*el);
|
||||
}
|
||||
}
|
||||
subpaths.into_iter().any(|mut sub| {
|
||||
let Some(start) = sub.elements().iter().find_map(|e| e.end_point()) else { return false };
|
||||
sub.apply_affine(kurbo::Affine::translate(-start.to_vec2()));
|
||||
let area = kurbo::Shape::area(&sub).abs();
|
||||
area > 0.0 && area > 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area()
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `outline` fills an area under `rule`: a subpath encloses an area ([`encloses`]) and the
|
||||
/// outline with its overlaps resolved, thin strips included, has an area. An outline the path
|
||||
/// operations refuse is judged by [`encloses`] alone.
|
||||
fn fills(outline: &kurbo::BezPath, rule: vectorcraft_geom::FillRule) -> bool {
|
||||
if !encloses(outline) {
|
||||
return false;
|
||||
}
|
||||
match vectorcraft_pathops::try_area(&vectorcraft_geom::PathData::from_bezpath(outline), rule) {
|
||||
Ok(area) => area > 0.0,
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` without the members in `going`, at every depth. Only the members in `affected` (those that
|
||||
/// hold a member in `going`) are copied; the others are shared.
|
||||
fn without(
|
||||
n: &vectorcraft_doc::Node,
|
||||
going: &std::collections::HashSet<NodeId>,
|
||||
affected: &std::collections::HashSet<NodeId>,
|
||||
) -> vectorcraft_doc::Node {
|
||||
let mut m = n.clone();
|
||||
if let Some(kids) = m.children_mut() {
|
||||
kids.retain(|k| !going.contains(&k.id));
|
||||
for k in kids.iter_mut().filter(|k| affected.contains(&k.id)) {
|
||||
*k = Arc::new(without(k, going, affected));
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
|
||||
/// read it.
|
||||
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
|
||||
@@ -281,6 +281,7 @@ fn set_warning(h: &Host, on: bool) -> Answer {
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
profiles: (None, None),
|
||||
};
|
||||
if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) {
|
||||
return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into()));
|
||||
|
||||
@@ -51,6 +51,7 @@ impl Session {
|
||||
active: None,
|
||||
prefs: Prefs::default(),
|
||||
caps_lock: false,
|
||||
artboard_deletion_guard: None,
|
||||
paint: PaintDefaults::default(),
|
||||
fill_active: true,
|
||||
clipboard: Clipboard::default(),
|
||||
|
||||
@@ -343,19 +343,26 @@ impl Session {
|
||||
/// it updates Recent Colors and converts or remaps the new-art paints at once, as it does with
|
||||
/// no drag in progress.
|
||||
///
|
||||
/// The interaction stays as it is, and the command runs inside it, for an interaction a dialog
|
||||
/// or a panel began (it builds its preview from commands), for typing in progress
|
||||
/// A dialog's live preview ([`crate::Interaction::dialog`]) is set aside the same way, except
|
||||
/// for a command that acts on the drawing on show ([`reads_preview`]). Outside commands use
|
||||
/// the shown selection with objects absent from the base document removed, and without a path
|
||||
/// whose selected anchors the preview renumbered. A selection of only preview objects becomes
|
||||
/// empty. The journal records that selection before the command, and records the dialog's
|
||||
/// own selection again when the command is refused. The interaction stays as it is, and the command runs
|
||||
/// inside it, for an interaction a panel or
|
||||
/// another dialog began (it builds its preview from commands), for typing in progress
|
||||
/// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside
|
||||
/// it ends the path it draws), and for a copy made with `object.transform` during a drag that
|
||||
/// copies (it copies the document as the drag's move left it). A command that settles,
|
||||
/// commits or cancels the interaction, or that hands the active tool actions to apply, gets it
|
||||
/// back first ([`Session::put_back_interaction`]), as it found it.
|
||||
pub(crate) fn outside_interaction(&mut self, id: &str, params: &Value, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
if cmd::typing_in_progress(self) || self.tool_id() == vectorcraft_tools::quickpen::ID {
|
||||
let dialog = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.dialog);
|
||||
if cmd::typing_in_progress(self) || (!dialog && self.tool_id() == vectorcraft_tools::quickpen::ID) {
|
||||
return f(self);
|
||||
}
|
||||
let Some(st) = self.active_mut() else { return f(self) };
|
||||
let Some(it) = st.interaction.as_ref().filter(|it| it.tool) else { return f(self) };
|
||||
let Some(it) = st.interaction.as_ref().filter(|it| it.tool || (it.dialog && !reads_preview(id))) else { return f(self) };
|
||||
// A drag that copies: its latest preview, applied or held back by Real-time Drawing off, copies.
|
||||
let copying = it.preview.as_ref().is_some_and(|(c, p)| c == "object.transform" && p.get("copy").and_then(Value::as_bool) == Some(true));
|
||||
if copying && id == "object.transform" && params.get("copy").and_then(Value::as_bool) == Some(true) {
|
||||
@@ -367,36 +374,57 @@ impl Session {
|
||||
let shown = previewed.then(|| (st.doc.clone(), st.selection.clone()));
|
||||
if previewed {
|
||||
st.doc = interaction.doc.clone();
|
||||
st.selection.clone_from(&interaction.selection);
|
||||
if let Some((shown_doc, _)) = shown.as_ref().filter(|_| interaction.dialog) {
|
||||
shown_base_selection(&mut st.selection, shown_doc, &st.doc);
|
||||
} else {
|
||||
st.selection.clone_from(&interaction.selection);
|
||||
}
|
||||
st.revision += 1;
|
||||
cmd::globaledit::follow_history(st);
|
||||
}
|
||||
// The journal holds the dialog's base selection, so the command replays on the one it acts on.
|
||||
let reselect = (interaction.dialog && st.selection != *interaction.selection)
|
||||
.then(|| selection_steps(&st.selection, &interaction.selection, &st.doc, st.active_layer, &st.highlighted_rows()));
|
||||
let (uid, state) = (st.uid, crate::interaction::ViewState::of(st));
|
||||
let paint = self.paint.clone();
|
||||
self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint });
|
||||
let journaled = reselect.is_some();
|
||||
if let Some(steps) = reselect {
|
||||
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
|
||||
for step in steps {
|
||||
self.journal.push(step);
|
||||
}
|
||||
self.journal_in_undo_groups(Some(uid), &grouped, from);
|
||||
}
|
||||
self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint, journaled, refused: false });
|
||||
if previewed {
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
let r = f(self);
|
||||
if let Some(held) = self.held_interaction.as_mut().filter(|_| r.is_err()) {
|
||||
held.refused = true;
|
||||
}
|
||||
self.put_back_interaction();
|
||||
r
|
||||
}
|
||||
|
||||
/// Put back the interaction [`Session::outside_interaction`] set aside. When the command left
|
||||
/// the document and the selection as it found them, the preview on show before it is on show
|
||||
/// again. Otherwise the interaction starts from the document the command left and from its
|
||||
/// own selection, without the objects the command removed, hid or locked, and the preview that Real-time
|
||||
/// Drawing showed is applied to it again. The warning or the error of that preview goes to
|
||||
/// again. Otherwise a tool drag starts from the document the command left and from its own
|
||||
/// selection, without the objects the command removed, hid or locked. The preview that
|
||||
/// Real-time Drawing showed is applied to it again. The warning or the error of that preview goes to
|
||||
/// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the
|
||||
/// interaction with nothing to commit. An interaction whose document the command closed ends,
|
||||
/// and so does one with anchors or segments selected on a path the command changed in more
|
||||
/// than a move. A document
|
||||
/// the command left an interaction of its own on keeps that one.
|
||||
/// than a move. A document the command left an interaction of its own on keeps that one.
|
||||
/// A dialog adopts the command's selection and paints and reruns its preview on its next pass.
|
||||
pub(crate) fn put_back_interaction(&mut self) {
|
||||
let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return };
|
||||
let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint, journaled, refused }) = self.held_interaction.take() else {
|
||||
return;
|
||||
};
|
||||
// A selection command loaded the paints of the selection it made into the fill and stroke
|
||||
// proxies. The drag goes on with its own selection, so they show its paints again.
|
||||
if self.paint != paint
|
||||
if !it.dialog
|
||||
&& self.paint != paint
|
||||
&& let Some(st) = self.active_mut().filter(|d| d.uid == uid && d.interaction.is_none())
|
||||
{
|
||||
let own = drag_selection(&it.selection, &st.doc);
|
||||
@@ -450,7 +478,19 @@ impl Session {
|
||||
// isolation stays when the interaction is canceled.
|
||||
state.rebase(crate::interaction::ViewState::of(st), &mut it);
|
||||
let previewed = shown.is_some();
|
||||
if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == *it.selection {
|
||||
// A refused command leaves the selection it was given: a dialog's is the one on show without
|
||||
// preview objects. A command that ran (Deselect) and left that selection keeps it.
|
||||
let given = match shown.as_ref().filter(|_| it.dialog && refused) {
|
||||
Some((shown_doc, selection)) => {
|
||||
let mut given = selection.clone();
|
||||
shown_base_selection(&mut given, shown_doc, &it.doc);
|
||||
given
|
||||
}
|
||||
None => (*it.selection).clone(),
|
||||
};
|
||||
if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == given {
|
||||
// The journal goes back to the dialog's base selection, as the preview on show again holds it.
|
||||
let back = (journaled && active).then(|| selection_steps(&it.selection, &given, &st.doc, st.active_layer, &st.highlighted_rows()));
|
||||
if let Some((doc, selection)) = shown {
|
||||
st.doc = doc;
|
||||
st.selection = selection;
|
||||
@@ -458,6 +498,13 @@ impl Session {
|
||||
cmd::globaledit::follow_history(st);
|
||||
}
|
||||
st.interaction = Some(it);
|
||||
if let Some(steps) = back {
|
||||
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
|
||||
for step in steps {
|
||||
self.journal.push(step);
|
||||
}
|
||||
self.journal_in_undo_groups(Some(uid), &grouped, from);
|
||||
}
|
||||
if previewed {
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
@@ -472,8 +519,17 @@ impl Session {
|
||||
}
|
||||
let began = std::mem::replace(&mut it.doc, st.doc.clone());
|
||||
// The drag acts on the objects it began with: a selection the command made (a paste, a
|
||||
// duplicate, Select All) does not change what the drag moves.
|
||||
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
|
||||
// duplicate, Select All) does not change what the drag moves. A dialog's preview acts on
|
||||
// the selection the command left, and its dialog previews again on its next pass, from the
|
||||
// values it shows then, so nothing is applied here.
|
||||
if it.dialog {
|
||||
if st.selection != *it.selection {
|
||||
it.selection = Arc::new(st.selection.clone());
|
||||
}
|
||||
it.preview = None;
|
||||
} else {
|
||||
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
|
||||
}
|
||||
// The journal holds the selection the command left. The drag's own selection is journaled
|
||||
// after it, so the drag and the commands after it replay on the objects they act on.
|
||||
let reselect = (active && st.selection != *it.selection)
|
||||
@@ -569,6 +625,7 @@ impl Session {
|
||||
revision: st.revision,
|
||||
preview: None,
|
||||
tool: false,
|
||||
dialog: false,
|
||||
tool_joined: false,
|
||||
paint,
|
||||
used_defaults_only: false,
|
||||
@@ -944,6 +1001,39 @@ fn take_changed_paints(
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether command `id` acts on the drawing as a dialog's preview shows it (a copy, a save, a
|
||||
/// revert), so it runs inside that preview rather than as a step of its own.
|
||||
fn reads_preview(id: &str) -> bool {
|
||||
id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode")
|
||||
}
|
||||
|
||||
/// The selection on show in a dialog's preview `shown`, as a command from outside the dialog acts
|
||||
/// on it in the base document `base`: without the objects the preview made, and without a path
|
||||
/// whose selected anchors or segments are numbered in a shape the preview changed in more than a
|
||||
/// move (Set Corners recut it), since those numbers can name other points in `base`.
|
||||
fn shown_base_selection(selection: &mut Selection, shown: &Document, base: &Document) {
|
||||
selection.prune(base);
|
||||
let recut: Vec<_> = selection
|
||||
.anchors
|
||||
.keys()
|
||||
.chain(selection.segments.keys())
|
||||
.copied()
|
||||
.filter(|&id| {
|
||||
let path = |d: &Document| d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.clone());
|
||||
match (path(shown), path(base)) {
|
||||
(Some(now), Some(was)) => !moved_whole(&was, &now),
|
||||
(now, was) => now.is_some() != was.is_some(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
for id in recut {
|
||||
selection.objects.retain(|o| *o != id);
|
||||
selection.anchors.remove(&id);
|
||||
selection.segments.remove(&id);
|
||||
}
|
||||
selection.prune(base);
|
||||
}
|
||||
|
||||
/// The selection a drag began with, without the objects that a command run during it removed,
|
||||
/// hid or locked in `doc`.
|
||||
fn drag_selection(began: &Selection, doc: &Document) -> Selection {
|
||||
|
||||
@@ -123,6 +123,7 @@ impl Session {
|
||||
st.sync_new_art();
|
||||
cmd::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
st.history_restores += 1;
|
||||
st.revision += 1;
|
||||
// The journal drops only the canceled groups' own entries and keeps the ones made in other documents meanwhile.
|
||||
journal.extend(g.journal);
|
||||
@@ -280,6 +281,9 @@ impl Session {
|
||||
st.drop_stale_variables_highlight();
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
st.history.recost_last(&st.doc);
|
||||
if !Arc::ptr_eq(&undone, &st.doc) {
|
||||
st.history_restores += 1;
|
||||
}
|
||||
st.revision += 1;
|
||||
if colors_changed {
|
||||
self.paint = scope.paint;
|
||||
|
||||
@@ -180,6 +180,106 @@ fn reverse_path_direction_on_and_off_set_the_winding() {
|
||||
assert!(s.execute("path.reverse", &json!({})).is_err(), "nothing to reverse");
|
||||
}
|
||||
|
||||
/// Points of what is direct-selected on one path, rounded to whole points.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Picked {
|
||||
/// The selected anchors' points, sorted.
|
||||
anchors: Vec<(i64, i64)>,
|
||||
/// The end points of the selected segments, each pair and the list sorted.
|
||||
segments: Vec<[(i64, i64); 2]>,
|
||||
/// The key anchor's point, when the key anchor is on the path.
|
||||
key: Option<(i64, i64)>,
|
||||
}
|
||||
|
||||
/// What is direct-selected on path `id`, as points.
|
||||
fn picked_points(s: &Session, id: NodeId) -> Picked {
|
||||
let st = s.doc().unwrap();
|
||||
let sp = &st.doc.node(id).unwrap().path_data().unwrap().subpaths;
|
||||
let at = |(si, ai): (usize, usize)| {
|
||||
let p = sp[si].anchors[ai].p;
|
||||
(p.x.round() as i64, p.y.round() as i64)
|
||||
};
|
||||
let mut anchors: Vec<_> = st.selection.anchors.get(&id).into_iter().flatten().map(|r| at(*r)).collect();
|
||||
anchors.sort_unstable();
|
||||
let mut segments: Vec<_> = st
|
||||
.selection
|
||||
.segments
|
||||
.get(&id)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|&(si, j)| {
|
||||
let mut ends = [at((si, j)), at((si, (j + 1) % sp[si].anchors.len()))];
|
||||
ends.sort_unstable();
|
||||
ends
|
||||
})
|
||||
.collect();
|
||||
segments.sort_unstable();
|
||||
let key = st.selection.key_anchor.filter(|(k, _)| *k == id).map(|(_, r)| at(r));
|
||||
Picked { anchors, segments, key }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_path_direction_keeps_the_same_anchors_and_segments_direct_selected() {
|
||||
let mut s = session();
|
||||
let path = |s: &mut Session, anchors: Value, closed: bool| {
|
||||
NodeId(run(s, "path.create", json!({"anchors": anchors, "closed": closed}))["id"].as_u64().unwrap())
|
||||
};
|
||||
let open = path(&mut s, json!([{"x": 0, "y": 50}, {"x": 40, "y": 50}, {"x": 100, "y": 50}]), false);
|
||||
let closed = path(&mut s, json!([{"x": 10, "y": 10}, {"x": 90, "y": 10}, {"x": 90, "y": 90}, {"x": 10, "y": 90}]), true);
|
||||
run(&mut s, "select.anchorsMany", json!({"items": [{"id": open.0, "anchors": [[0, 0]]}, {"id": closed.0, "anchors": [[0, 1], [0, 2]]}]}));
|
||||
run(&mut s, "select.key", json!({"id": closed.0, "anchor": [0, 1]}));
|
||||
let before = [picked_points(&s, open), picked_points(&s, closed)];
|
||||
assert_eq!(before[0].anchors, [(0, 50)]);
|
||||
assert_eq!((before[1].anchors.clone(), before[1].key), (vec![(90, 10), (90, 90)], Some((90, 10))));
|
||||
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2);
|
||||
let first = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[0].p;
|
||||
assert_eq!((first(&s, open).x, first(&s, closed).y), (100.0, 90.0), "both paths turned");
|
||||
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same points stay direct-selected after Reverse Path Direction");
|
||||
// Undo turns the paths back with the selection they had.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(first(&s, open).x, 0.0);
|
||||
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "undo");
|
||||
|
||||
// Selected segments, the closing segment of a closed path included, stay the same segments.
|
||||
run(&mut s, "select.segments", json!({"id": closed.0, "segments": [[0, 0], [0, 3]], "mode": "set"}));
|
||||
run(&mut s, "select.segments", json!({"id": open.0, "segments": [[0, 0]], "mode": "add"}));
|
||||
let before = [picked_points(&s, open), picked_points(&s, closed)];
|
||||
assert_eq!(before[0].segments, [[(0, 50), (40, 50)]]);
|
||||
assert_eq!(before[1].segments, [[(10, 10), (10, 90)], [(10, 10), (90, 10)]]);
|
||||
assert_eq!(run(&mut s, "path.reverse", json!({}))["changed"], 2);
|
||||
assert_eq!([picked_points(&s, open), picked_points(&s, closed)], before, "the same segments stay selected after Reverse Path Direction");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_path_direction_of_one_subpath_leaves_the_others_selection_as_it_is() {
|
||||
let mut s = session();
|
||||
let id = NodeId(run(&mut s, "path.create", json!({"d": "M0 0 L40 0 L100 0 M0 200 L40 200 L100 200"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 0], [1, 0]]}]}));
|
||||
run(&mut s, "select.key", json!({"id": id.0, "anchor": [0, 0]}));
|
||||
let before = picked_points(&s, id);
|
||||
assert_eq!((before.anchors.clone(), before.key), (vec![(0, 0), (0, 200)], Some((0, 0))));
|
||||
assert_eq!(run(&mut s, "path.reverse", json!({"subpath": 1}))["changed"], 1);
|
||||
let first = |s: &Session, si: usize| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[si].anchors[0].p;
|
||||
assert_eq!((first(&s, 0).x, first(&s, 1).x), (0.0, 100.0), "only the second subpath turned");
|
||||
assert_eq!(picked_points(&s, id), before, "the same points stay direct-selected on both subpaths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_anchor_point_keeps_the_key_anchor_on_its_point() {
|
||||
let mut s = session();
|
||||
let anchors = json!([{"x": 10, "y": 10}, {"x": 90, "y": 10}, {"x": 90, "y": 90}, {"x": 10, "y": 90}]);
|
||||
let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors, "closed": true}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "select.anchorsMany", json!({"items": [{"id": id.0, "anchors": [[0, 1], [0, 2]]}]}));
|
||||
run(&mut s, "select.key", json!({"id": id.0, "anchor": [0, 2]}));
|
||||
let before = picked_points(&s, id);
|
||||
assert_eq!((before.anchors.clone(), before.key), (vec![(90, 10), (90, 90)], Some((90, 90))));
|
||||
run(&mut s, "path.insertAnchor", json!({"id": id.0, "segment": 0}));
|
||||
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.len(), 5);
|
||||
assert_eq!(picked_points(&s, id), before, "the key anchor and the selected anchors stay on their points after Add Anchor Point");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(picked_points(&s, id), before, "undo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_path_direction_turns_the_width_profile_and_pen_records_with_the_path() {
|
||||
use vectorcraft_doc::{AngleProfile, PressureProfile, WidthProfile};
|
||||
|
||||
@@ -175,6 +175,32 @@ fn an_undo_group_lets_no_other_documents_steps_go_until_it_ends() {
|
||||
assert!(history_bytes(&s) <= s.history_budget);
|
||||
}
|
||||
|
||||
/// A canceled undo group, and a canceled undo scope that joined one, put back an older snapshot:
|
||||
/// both advance the document's history restores, as Undo does, and a kept one does not.
|
||||
#[test]
|
||||
fn canceled_undo_groups_and_scopes_count_as_history_restores() {
|
||||
let mut s = session_with_rects(2);
|
||||
let restores = |s: &Session| s.docs[0].history_restores;
|
||||
s.begin_undo_group();
|
||||
moves(&mut s, 2);
|
||||
s.end_undo_group(false);
|
||||
assert_eq!(restores(&s), 0, "a kept group restores nothing");
|
||||
s.begin_undo_group();
|
||||
moves(&mut s, 2);
|
||||
s.end_undo_group(true);
|
||||
assert_eq!(restores(&s), 1, "a canceled group");
|
||||
s.begin_undo_group();
|
||||
moves(&mut s, 1);
|
||||
let scope = s.begin_undo_scope().unwrap();
|
||||
moves(&mut s, 2);
|
||||
s.end_undo_scope(scope, true);
|
||||
assert_eq!(restores(&s), 2, "a canceled scope that joined the open group");
|
||||
let scope = s.begin_undo_scope().unwrap();
|
||||
s.end_undo_scope(scope, true);
|
||||
assert_eq!(restores(&s), 2, "a canceled scope that made no edit puts back the same snapshot");
|
||||
s.end_undo_group(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_kept_outside_a_command_keep_to_the_shared_budget() {
|
||||
let mut s = session_with_rects(50);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -211,6 +211,33 @@ fn exclude_makes_compound() {
|
||||
assert!((area_of(&s, r[0]) - 15000.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divide_over_work_budget_preserves_art_and_selection() {
|
||||
let mut s = session();
|
||||
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let line = s.execute("shape.line", &json!({"x1": -10, "y1": -10, "x2": 110, "y2": 110})).unwrap();
|
||||
let cutter = NodeId(line["id"].as_u64().unwrap());
|
||||
// The existing pathops work-budget fixture uses 1,500 overlapping lines.
|
||||
// Put them in one open path so the setup only makes two document objects.
|
||||
let line = SubPath::polyline(&[Point::new(-10.0, -10.0), Point::new(110.0, 110.0)], false);
|
||||
s.edit("complex cutter", |d, _| {
|
||||
let NodeKind::Path { path, .. } = &mut d.node_mut(cutter).unwrap().kind else { panic!("expected a path") };
|
||||
*path = PathData::new(vec![line; 1_500]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [square.0, cutter.0]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let selection = s.doc().unwrap().selection.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let error = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("too many segments or pieces"), "{error}");
|
||||
let state = s.doc().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&state.doc, &before), "the original document must be restored");
|
||||
assert_eq!(state.selection, selection);
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn divide_produces_group_of_faces() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -179,6 +179,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() {
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
profiles: (None, None),
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
|
||||
@@ -4095,6 +4095,55 @@ const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m =
|
||||
try { p.removeAll(); } catch (e) { m = e.message; }\
|
||||
vc.log(m); vc.log(p.length);";
|
||||
|
||||
/// A group's `pathItems.removeAll()` walks the group, not the document: emptying a group of two
|
||||
/// paths beside 500 other paths looks at a handful of objects, and an empty group's looks at none.
|
||||
#[test]
|
||||
fn group_path_items_remove_all_walks_only_the_group() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
for i in 0..500 {
|
||||
rect(&mut s, f64::from(i % 25) * 10.0, f64::from(i / 25) * 10.0, 5.0, 5.0);
|
||||
}
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let start = crate::script::dom::REMOVE_ALL_VISITS.with(|n| n.get());
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var g = app.activeDocument.groupItems[0]; g.pathItems.removeAll(); g.pathItems.removeAll();\
|
||||
vc.log(g.pathItems.length); vc.log(app.activeDocument.pathItems.length);",
|
||||
);
|
||||
let visits = crate::script::dom::REMOVE_ALL_VISITS.with(|n| n.get()) - start;
|
||||
assert_eq!(out, vec![json!(0), json!(500)]);
|
||||
assert!(visits <= 3, "{visits} objects walked to empty a group of two paths");
|
||||
}
|
||||
|
||||
/// In a damaged document where a path outside a group has the same id as a path in it, the
|
||||
/// group's `pathItems.removeAll()` throws and deletes nothing, instead of deleting the outside path.
|
||||
#[test]
|
||||
fn group_path_items_remove_all_refuses_an_id_found_outside_the_group() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("object.arrange.sendToBack", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
|
||||
d.node_mut(c).unwrap().id = a;
|
||||
d.drop_lookup_cache();
|
||||
// The first object in tree order with the id is the one outside the group.
|
||||
assert_eq!(d.index_path(a).map(|p| p.len()), Some(2));
|
||||
let n = d.layers[0].children().map_or(0, Vec::len);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, m = ''; try { d.groupItems[0].pathItems.removeAll(); } catch (e) { m = e.message; }\
|
||||
vc.log(m); vc.log(d.groupItems[0].pathItems.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(format!("cannot delete PathItem {}: its id also names another object", a.0)), json!(2)]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.layers[0].children().map_or(0, Vec::len), n, "the path outside the group is kept");
|
||||
}
|
||||
|
||||
/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the
|
||||
/// group keeps other art, and deletes nothing, as the scoped collections do.
|
||||
#[test]
|
||||
@@ -4420,6 +4469,103 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empt
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// An image's frame clips as a clipping path does, so a clipping group whose clipping path keeps
|
||||
/// an image still has an outline after its paths are deleted.
|
||||
#[test]
|
||||
fn document_path_items_remove_all_keeps_a_clipping_group_whose_clipping_path_keeps_an_image() {
|
||||
for frame in [Frame::Square, Frame::Line, Frame::Far, Frame::Inset, Frame::Mirrored, Frame::Strip] {
|
||||
remove_all_beside_an_image(frame);
|
||||
}
|
||||
}
|
||||
|
||||
/// The image frame of [`remove_all_beside_an_image`].
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Frame {
|
||||
/// 40 pt square.
|
||||
Square,
|
||||
/// Collapsed to a line.
|
||||
Line,
|
||||
/// 1/64 pt square 3,500,000 pt from the origin.
|
||||
Far,
|
||||
/// 40 pt square with a live Offset Path of -30 pt, which leaves nothing.
|
||||
Inset,
|
||||
/// 40 pt square with a live Transform effect that adds one copy reflected about its center:
|
||||
/// the two outlines run opposite ways over the same area and fill nothing under nonzero.
|
||||
Mirrored,
|
||||
/// 40 pt square with a live Transform effect that scales it to 0.004 pt high, which still
|
||||
/// clips to a thin strip.
|
||||
Strip,
|
||||
}
|
||||
|
||||
/// A clipping group whose clipping path is a group of one path and an image with `frame`, then the
|
||||
/// document's `pathItems.removeAll()`.
|
||||
fn remove_all_beside_an_image(frame: Frame) {
|
||||
let flat = matches!(frame, Frame::Line | Frame::Inset | Frame::Mirrored);
|
||||
let (mut s, a, b) = doc();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let image = s
|
||||
.edit("Place", |d, _| {
|
||||
let id = d.alloc_id();
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "pic".into(),
|
||||
width: 4,
|
||||
height: 4,
|
||||
xf: match frame {
|
||||
Frame::Square | Frame::Inset | Frame::Mirrored | Frame::Strip => kurbo::Affine::scale(10.0),
|
||||
Frame::Line => kurbo::Affine::scale_non_uniform(10.0, 0.0),
|
||||
Frame::Far => kurbo::Affine::translate((3_500_000.0, 3_500_000.0)) * kurbo::Affine::scale(1.0 / 256.0),
|
||||
},
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(Some(mask), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
if frame == Frame::Inset {
|
||||
s.execute("effect.apply", &json!({"effect": "path.offsetPath", "params": {"offset": -30}, "ids": [image.0], "item": null})).unwrap();
|
||||
}
|
||||
if frame == Frame::Mirrored {
|
||||
s.execute(
|
||||
"effect.apply",
|
||||
&json!({"effect": "distort.transform", "params": {"reflectX": true, "copies": 1, "reference": 4}, "ids": [image.0], "item": null}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
if frame == Frame::Strip {
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleV": 0.01}, "ids": [image.0], "item": null})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap();
|
||||
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("Clip", |d, _| {
|
||||
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
|
||||
children.sort_by_key(|c| c.id != mask);
|
||||
*clip = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
|
||||
if flat {
|
||||
assert_eq!(
|
||||
out[0],
|
||||
json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0))
|
||||
);
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
return;
|
||||
}
|
||||
assert_eq!(out, [json!(""), json!(0)]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(a).is_none() && d.node(b).is_none());
|
||||
assert!(d.node(outer).unwrap().clips());
|
||||
assert_eq!(d.parent_of(image), Some(mask));
|
||||
assert!(d.node(t).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() {
|
||||
for compound in [false, true] {
|
||||
|
||||
@@ -106,6 +106,7 @@ fn yes_to_the_confirm_turns_the_warning_off() {
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
profiles: (None, None),
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(s.script_dialog_turns_warning_off());
|
||||
|
||||
@@ -19,7 +19,7 @@ fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::canonicalize(&base).unwrap()
|
||||
crate::cmd::findfiles::plain(std::fs::canonicalize(&base).unwrap())
|
||||
}
|
||||
|
||||
fn write(path: &Path, bytes: &[u8]) {
|
||||
|
||||
@@ -57,7 +57,7 @@ impl AsRef<Path> for Folder {
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path.
|
||||
fn folder(name: &str) -> Folder {
|
||||
let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}"));
|
||||
let base = std::fs::canonicalize(&*guard).unwrap();
|
||||
let base = crate::cmd::findfiles::plain(std::fs::canonicalize(&*guard).unwrap());
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
Folder { _guard: guard, path: base }
|
||||
}
|
||||
|
||||
@@ -1160,7 +1160,7 @@ fn place_reads_what_open_reads_and_text_files() {
|
||||
assert_eq!(PLACE_EXTS, [OPEN_EXTS, TEXT_EXTS, RTF_EXTS, DOCX_EXTS, DOC_EXTS].concat());
|
||||
let filters: Vec<_> = cmd::fileio::place_filters().collect();
|
||||
let word: (&str, &[&str]) = ("Word", &["docx", "doc"]);
|
||||
assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", PLACE_EXTS)), Some(&word)));
|
||||
assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", cmd::fileio::place_exts())), Some(&word)));
|
||||
assert_eq!(filters.get(filters.len() - 3..), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..]));
|
||||
assert!(
|
||||
!cmd::fileio::open_filters().any(|(_, exts)| ["txt", "rtf", "docx", "doc"].iter().any(|e| exts.contains(e))),
|
||||
|
||||
@@ -3711,12 +3711,20 @@ fn arb_dxf_entity() -> impl Strategy<Value = Vec<(i32, String)>> {
|
||||
"ATTRIB",
|
||||
"DIMENSION",
|
||||
"VIEWPORT",
|
||||
"REGION",
|
||||
]);
|
||||
let code = prop::sample::select(vec![
|
||||
2, 6, 7, 8, 10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 48, 50, 51, 60, 62, 66, 67, 70, 71, 72, 73, 74, 75, 76, 90, 91, 92, 93,
|
||||
94, 95, 96, 97, 210, 220, 230, 370, 420, 440, 450,
|
||||
1, 2, 3, 6, 7, 8, 10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43, 44, 45, 48, 50, 51, 60, 62, 66, 67, 70, 71, 72, 73, 74, 75, 76, 90, 91, 92,
|
||||
93, 94, 95, 96, 97, 210, 220, 230, 370, 420, 440, 450,
|
||||
]);
|
||||
let value = prop_oneof![arb_num(), Just("B".to_string()), Just("*U1".to_string()), Just(r"{\fA;x}\P%%c^".to_string())];
|
||||
let value = prop_oneof![
|
||||
arb_num(),
|
||||
Just("B".to_string()),
|
||||
Just("*U1".to_string()),
|
||||
Just(r"{\fA;x}\P%%c^".to_string()),
|
||||
Just("700 0 1 0".to_string()),
|
||||
Just("body $-1 -1 $-1 $0 $-1 $-1 #".to_string()),
|
||||
];
|
||||
(kind, prop::collection::vec((code, value), 0..24)).prop_map(|(k, g)| std::iter::once((0, k.to_string())).chain(g).collect())
|
||||
}
|
||||
|
||||
@@ -3730,6 +3738,107 @@ fn hostile_dxf(block: &[Vec<(i32, String)>], body: &[Vec<(i32, String)>]) -> Vec
|
||||
dxf_text(&all).into_bytes()
|
||||
}
|
||||
|
||||
/// A region's solid-modeler text data: one face whose loop is two lines and a quarter circle,
|
||||
/// (0, 0) to (100, 0), round to (0, 100) and back.
|
||||
const REGION_SAT: &str = "700 0 1 0
|
||||
4 Fuzz 3 ASM 4 none
|
||||
1 9.9999999999999995e-07 1e-10
|
||||
body $-1 -1 $-1 $1 $-1 $-1 #
|
||||
lump $-1 -1 $-1 $-1 $2 $0 #
|
||||
shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1 #
|
||||
face $-1 -1 $-1 $-1 $4 $2 $-1 $-1 forward single #
|
||||
loop $-1 -1 $-1 $-1 $5 $3 #
|
||||
coedge $-1 -1 $-1 $6 $7 $-1 $8 forward $4 $-1 #
|
||||
coedge $-1 -1 $-1 $7 $5 $-1 $9 forward $4 $-1 #
|
||||
coedge $-1 -1 $-1 $5 $6 $-1 $10 forward $4 $-1 #
|
||||
edge $-1 -1 $-1 $11 0 $12 1 $5 $-1 forward @7 unknown #
|
||||
edge $-1 -1 $-1 $12 0 $13 1 $6 $17 forward @7 unknown #
|
||||
edge $-1 -1 $-1 $13 0 $11 1 $7 $-1 forward @7 unknown #
|
||||
vertex $-1 -1 $-1 $8 $14 #
|
||||
vertex $-1 -1 $-1 $9 $15 #
|
||||
vertex $-1 -1 $-1 $10 $16 #
|
||||
point $-1 -1 $-1 0 0 0 #
|
||||
point $-1 -1 $-1 100 0 0 #
|
||||
point $-1 -1 $-1 0 100 0 #
|
||||
ellipse-curve $-1 -1 $-1 0 0 0 0 0 1 100 0 0 1 I I #
|
||||
End-of-ACIS-data
|
||||
";
|
||||
|
||||
/// [`REGION_SAT`]'s records as binary data: tagged values, type names in parts.
|
||||
fn region_sab() -> Vec<u8> {
|
||||
let mut b = b"ACIS BinaryFile".to_vec();
|
||||
for v in [700u32, 0, 1, 0] {
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
let string = |b: &mut Vec<u8>, tag: u8, s: &str| {
|
||||
b.push(tag);
|
||||
b.push(u8::try_from(s.len()).unwrap_or(0));
|
||||
b.extend(s.as_bytes());
|
||||
};
|
||||
for line in REGION_SAT.lines().skip(3).take_while(|l| !l.starts_with("End-of")) {
|
||||
let mut words = line.split_whitespace();
|
||||
let parts: Vec<&str> = words.next().unwrap_or_default().split('-').collect();
|
||||
for (i, p) in parts.iter().enumerate() {
|
||||
string(&mut b, if i + 1 == parts.len() { 0x0D } else { 0x0E }, p);
|
||||
}
|
||||
while let Some(w) = words.next() {
|
||||
match w {
|
||||
"#" => {}
|
||||
"forward" => b.push(0x0B),
|
||||
"reversed" => b.push(0x0A),
|
||||
w if w.starts_with('$') => {
|
||||
b.push(0x0C);
|
||||
b.extend(w[1..].parse::<i32>().unwrap_or(-1).to_le_bytes());
|
||||
}
|
||||
w if w.starts_with('@') => string(&mut b, 0x07, words.next().unwrap_or_default()),
|
||||
w => match w.parse::<f64>() {
|
||||
Ok(v) => {
|
||||
b.push(0x06);
|
||||
b.extend(v.to_le_bytes());
|
||||
}
|
||||
Err(_) => string(&mut b, 0x07, w),
|
||||
},
|
||||
}
|
||||
}
|
||||
b.push(0x11);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// A drawing with one REGION: `text` as its data in groups 1 (DXF 2000), or `binary` in the
|
||||
/// ACDSDATA section (DXF 2013).
|
||||
fn region_dxf(text: &str, binary: Option<&[u8]>) -> Vec<u8> {
|
||||
let version = if binary.is_some() { "AC1027" } else { "AC1015" };
|
||||
let mut p: Vec<(i32, String)> =
|
||||
[(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, version), (0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES"), (0, "REGION"), (5, "2A")]
|
||||
.iter()
|
||||
.map(|(c, v)| (*c, v.to_string()))
|
||||
.collect();
|
||||
p.extend([(8, "0".to_string()), (100, "AcDbEntity".into()), (100, "AcDbModelerGeometry".into()), (70, "1".into())]);
|
||||
p.extend(text.lines().map(|l| (1, l.to_string())));
|
||||
p.push((0, "ENDSEC".into()));
|
||||
if let Some(bytes) = binary {
|
||||
p.extend([(0, "SECTION"), (2, "ACDSDATA"), (0, "ACDSRECORD"), (320, "2A"), (2, "ASM_Data")].iter().map(|(c, v)| (*c, v.to_string())));
|
||||
p.push((94, bytes.len().to_string()));
|
||||
p.extend(bytes.chunks(127).map(|c| (310, c.iter().map(|b| format!("{b:02X}")).collect())));
|
||||
p.push((0, "ENDSEC".into()));
|
||||
}
|
||||
p.push((0, "EOF".into()));
|
||||
dxf_text(&p).into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_seeds_open_as_a_filled_path() {
|
||||
let o = vectorcraft_cad::ImportOptions::default();
|
||||
for bytes in [region_dxf(REGION_SAT, None), region_dxf("", Some(®ion_sab()))] {
|
||||
let r = vectorcraft_cad::import(&bytes, &o).expect("opens");
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("REGION")), "{:?}", r.warnings);
|
||||
let mut paths = 0;
|
||||
r.document.walk(|n: &vectorcraft_doc::Node| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })));
|
||||
assert_eq!(paths, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Import with every option at once, and place it; whatever comes back must render and export.
|
||||
fn survive_dxf(what: &str, bytes: &[u8], fit: bool) -> Result<(), TestCaseError> {
|
||||
let o = vectorcraft_cad::ImportOptions { fit, center: !fit, merge_layers: fit, ..Default::default() };
|
||||
@@ -3783,6 +3892,23 @@ proptest! {
|
||||
bytes.truncate(cut.max(8));
|
||||
survive_dxf("mutated dxf", &bytes, cut % 2 == 0)?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxf_mutated_regions_never_panic(
|
||||
binary in any::<bool>(),
|
||||
cut in 0usize..2_000,
|
||||
edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec![b'0', b'1', b'9', b'-', b'.', b'e', b'$', b'#', b' ', b'@', 0xFF, 0x0C])), 0..12),
|
||||
) {
|
||||
let mut data = if binary { region_sab() } else { REGION_SAT.as_bytes().to_vec() };
|
||||
for &(at, b) in &edits {
|
||||
let n = data.len();
|
||||
// Text stays ASCII, as group values are.
|
||||
data[at % n] = if binary || (b' '..0x80).contains(&b) { b } else { b' ' };
|
||||
}
|
||||
data.truncate(cut.max(8));
|
||||
let bytes = if binary { region_dxf("", Some(&data)) } else { region_dxf(&String::from_utf8_lossy(&data), None) };
|
||||
survive_dxf("mutated region", &bytes, cut % 2 == 0)?;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Windows metafiles: opened, placed and pasted ----------
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! [`Backend`].
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_engine::cmd::fileio::{ARTBOARD_PARAMS, FORMATS, OPEN_EXTS, SAVE_FORMATS, format, writable_format};
|
||||
use vectorcraft_engine::cmd::fileio::{ARTBOARD_PARAMS, FORMATS, SAVE_FORMATS, format, open_exts, writable_format};
|
||||
|
||||
use crate::backend::Backend;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::dispatch::{BRIEF, MAX_SIDE_WINDOW, MENU_FILTER, TRACE_VIEWS};
|
||||
use super::handlers::MAX_DIALOG_FIELDS;
|
||||
use super::{FORMATS, OPEN_EXTS, SAVE_FORMATS, Value, format, json};
|
||||
use super::{FORMATS, SAVE_FORMATS, Value, format, json, open_exts};
|
||||
|
||||
// ---------- schemas ----------
|
||||
|
||||
@@ -365,7 +365,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
"Open file",
|
||||
&format!(
|
||||
"Open a file as a new, active document: .{} (see run_command document.formats). Templates (.ait, native templates) open as a new untitled document. The reply's `warnings` say what didn't come in as it was (an EPS shown as its preview image says why its PostScript couldn't be read). A file of an extension no built-in format reads opens with the installed importer plug-in that lists it; `importer` names the importer to use (File › Open With), also for an extension a built-in format reads, and `params` gives that importer's parameters.",
|
||||
OPEN_EXTS.join(", .")
|
||||
open_exts().join(", .")
|
||||
),
|
||||
obj(
|
||||
json!({
|
||||
|
||||
@@ -1555,7 +1555,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.cleanup.releaseAll|addon.document.floodFillArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
@@ -1780,7 +1780,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.placementOptionsDialog",
|
||||
"Placement Options…",
|
||||
"",
|
||||
"{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)",
|
||||
"{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo, a Redo or a canceled edit that put back an earlier state there (reopen the dialog)",
|
||||
),
|
||||
(
|
||||
"ui.relinkDialog",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Targa export: depths, alpha and the footer.
|
||||
//! Targa export: depths, grayscale, alpha and the footer.
|
||||
|
||||
use super::on_white;
|
||||
use super::tests_bmp::{art, decode, u16_at};
|
||||
@@ -9,7 +9,7 @@ fn targa_depths_alpha_and_footer() {
|
||||
let (w, h) = (7, 3);
|
||||
let px = art(w, h);
|
||||
for (depth, alpha_bits) in [(16, 1), (24, 0), (32, 8)] {
|
||||
let file = tga::encode(&px, w, h, &TgaOptions { depth }).unwrap();
|
||||
let file = tga::encode(&px, w, h, &TgaOptions { depth, gray: false }).unwrap();
|
||||
assert_eq!((file[2], file[16], file[17]), (2, depth, alpha_bits), "true colour, the depth byte, alpha bits");
|
||||
assert_eq!((u16_at(&file, 12), u16_at(&file, 14)), (7, 3));
|
||||
assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26);
|
||||
@@ -18,13 +18,39 @@ fn targa_depths_alpha_and_footer() {
|
||||
assert_eq!(img.dimensions(), (w, h));
|
||||
let want = on_white(px[(2 * w as usize + 3) * 4..][..4].try_into().unwrap());
|
||||
let got = img.get_pixel(3, 2).0;
|
||||
assert!(got[..3].iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 8), "depth {depth}: {got:?} vs {want:?}");
|
||||
for c in 0..3 {
|
||||
assert!(got[c].abs_diff(want[c]) <= 8, "depth {depth}, channel {c}: {got:?} vs {want:?}");
|
||||
}
|
||||
match depth {
|
||||
32 => assert_eq!((img.get_pixel(0, 0).0[3], img.get_pixel(1, 0).0[3]), (0, 128), "8-bit alpha"),
|
||||
24 => assert_eq!(img.get_pixel(0, 0).0, [255; 4], "flattened on white"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(tga::encode(&px, w, h, &TgaOptions { depth: 8 }).is_err());
|
||||
assert!(tga::encode(&px, w, h, &TgaOptions { depth: 8, gray: false }).is_err());
|
||||
assert!(tga::encode(&px, 70_000, 1, &TgaOptions::default()).is_err(), "too wide");
|
||||
}
|
||||
|
||||
/// Grayscale Targa files are image type 3: 8 bits flattened on white, or 16 with an 8-bit alpha.
|
||||
#[test]
|
||||
fn targa_grayscale_writes_lightness() {
|
||||
let (w, h) = (7, 3);
|
||||
let px = art(w, h);
|
||||
for (depth, alpha_bits) in [(8, 0), (16, 8)] {
|
||||
let file = tga::encode(&px, w, h, &TgaOptions { depth, gray: true }).unwrap();
|
||||
assert_eq!((file[2], file[16], file[17]), (3, depth, alpha_bits), "grayscale, the depth byte, alpha bits");
|
||||
assert_eq!(file.len(), 18 + (w * h) as usize * usize::from(depth / 8) + 26);
|
||||
let img = decode(&file, craft_image_codecs::Format::Tga);
|
||||
assert_eq!(img.dimensions(), (w, h));
|
||||
// (0, 2) is opaque red 230, 40, 30: Rec. 601 lightness 96, the same in every channel.
|
||||
let [r, g, b, a] = img.get_pixel(0, 2).0;
|
||||
assert!(r == g && g == b && r.abs_diff(96) <= 1 && a == 255, "depth {depth}: {:?}", [r, g, b, a]);
|
||||
match depth {
|
||||
8 => assert_eq!(img.get_pixel(0, 0).0, [255; 4], "flattened on white"),
|
||||
_ => assert_eq!((img.get_pixel(0, 0).0[3], img.get_pixel(1, 0).0[3]), (0, 128), "8-bit alpha"),
|
||||
}
|
||||
}
|
||||
for depth in [24, 32] {
|
||||
assert!(tga::encode(&px, w, h, &TgaOptions { depth, gray: true }).is_err(), "{depth} bits gray");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,55 @@
|
||||
//! Targa export: uncompressed true colour at 16 bits per pixel (5-5-5 and a one-bit alpha), 24 or
|
||||
//! 32 (8-bit alpha), rows bottom-up, with the version 2 footer.
|
||||
//! 32 (8-bit alpha), or uncompressed grayscale at 8 bits or 16 (8-bit alpha), rows bottom-up, with
|
||||
//! the version 2 footer.
|
||||
|
||||
use super::on_white;
|
||||
use super::quantize::luma;
|
||||
|
||||
/// Bits per pixel a Targa export can have.
|
||||
/// Bits per pixel a true-colour Targa export can have.
|
||||
pub const DEPTHS: [u8; 3] = [16, 24, 32];
|
||||
|
||||
/// Bits per pixel a grayscale Targa export can have.
|
||||
pub const GRAY_DEPTHS: [u8; 2] = [8, 16];
|
||||
|
||||
/// The Targa options of a raster export.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TgaOptions {
|
||||
/// Bits per pixel ([`DEPTHS`]).
|
||||
/// Bits per pixel ([`DEPTHS`], or [`GRAY_DEPTHS`] when `gray`).
|
||||
pub depth: u8,
|
||||
/// Grayscale (image type 3) instead of true colour (image type 2).
|
||||
pub gray: bool,
|
||||
}
|
||||
|
||||
impl Default for TgaOptions {
|
||||
fn default() -> Self {
|
||||
Self { depth: 24 }
|
||||
Self { depth: Self::default_depth(false), gray: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl TgaOptions {
|
||||
/// The depth a colour model starts with: 24 bits for true colour, 8 for grayscale.
|
||||
pub fn default_depth(gray: bool) -> u8 {
|
||||
if gray { 8 } else { 24 }
|
||||
}
|
||||
|
||||
/// The depths the colour model can be written at.
|
||||
pub fn depths(gray: bool) -> &'static [u8] {
|
||||
if gray { &GRAY_DEPTHS } else { &DEPTHS }
|
||||
}
|
||||
|
||||
/// Why these options can't be written, if they can't.
|
||||
pub fn check(&self) -> Result<(), String> {
|
||||
if DEPTHS.contains(&self.depth) { Ok(()) } else { Err(format!("Targa depth {}: 16, 24 or 32 bits per pixel", self.depth)) }
|
||||
match (self.gray, Self::depths(self.gray).contains(&self.depth)) {
|
||||
(_, true) => Ok(()),
|
||||
(false, false) => Err(format!("Targa depth {}: 16, 24 or 32 bits per pixel", self.depth)),
|
||||
(true, false) => Err(format!("grayscale Targa depth {}: 8 or 16 bits per pixel", self.depth)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Straight-alpha RGBA pixels as a Targa file. 24 bits blend partly transparent pixels over white;
|
||||
/// at 16 bits a pixel is opaque from half opacity up, else transparent.
|
||||
/// Straight-alpha RGBA pixels as a Targa file. 24 bits and 8-bit grayscale blend partly
|
||||
/// transparent pixels over white; at 16 bits true colour a pixel is opaque from half opacity up,
|
||||
/// else transparent.
|
||||
pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Vec<u8>, String> {
|
||||
o.check()?;
|
||||
let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else {
|
||||
@@ -40,21 +62,23 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Ve
|
||||
}
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
let mut out = Vec::with_capacity((w * h).saturating_mul(usize::from(o.depth / 8)).saturating_add(18 + 26));
|
||||
// No image id or colour map, uncompressed true colour, origin (0, 0).
|
||||
out.extend([0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
// No image id or colour map, uncompressed true colour (2) or grayscale (3), origin (0, 0).
|
||||
out.extend([0, 0, if o.gray { 3 } else { 2 }, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
out.extend(w16.to_le_bytes());
|
||||
out.extend(h16.to_le_bytes());
|
||||
// Bits per pixel, then the alpha bits (rows bottom-up, left to right).
|
||||
let alpha_bits = match o.depth {
|
||||
16 => 1,
|
||||
32 => 8,
|
||||
let alpha_bits = match (o.gray, o.depth) {
|
||||
(false, 16) => 1,
|
||||
(true, 16) | (false, 32) => 8,
|
||||
_ => 0,
|
||||
};
|
||||
out.extend([o.depth, alpha_bits]);
|
||||
for row in px.chunks(w).rev() {
|
||||
for p in row {
|
||||
match o.depth {
|
||||
16 => {
|
||||
match (o.gray, o.depth) {
|
||||
(true, 8) => out.push(luma(on_white(p))),
|
||||
(true, _) => out.extend([luma([p[0], p[1], p[2]]), p[3]]),
|
||||
(false, 16) => {
|
||||
let v = if p[3] >= 128 {
|
||||
let [r, g, b] = [p[0], p[1], p[2]].map(|c| u16::from(c >> 3));
|
||||
0x8000 | r << 10 | g << 5 | b
|
||||
@@ -63,7 +87,7 @@ pub fn encode(rgba: &[u8], width: u32, height: u32, o: &TgaOptions) -> Result<Ve
|
||||
};
|
||||
out.extend(v.to_le_bytes());
|
||||
}
|
||||
24 => {
|
||||
(false, 24) => {
|
||||
let [r, g, b] = on_white(p);
|
||||
out.extend([b, g, r]);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use vectorcraft_doc::text::CompositeClasses;
|
||||
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, TextObject, TextRun};
|
||||
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, Digits, TextObject, TextRun};
|
||||
|
||||
use super::face::FALLBACK_FAMILY;
|
||||
use super::{Arc, FontDb, FontFace, FontMatch};
|
||||
@@ -242,6 +242,24 @@ impl FontDb {
|
||||
/// match, and the characters (neither whitespace nor control characters, sorted, each once)
|
||||
/// that their part's face lacks. `None` when `name` is no composite font.
|
||||
pub fn composite_coverage(&self, name: &str, texts: &[&str]) -> Option<CompositeCoverage> {
|
||||
self.coverage_of(name, texts, None)
|
||||
}
|
||||
|
||||
/// [`FontDb::composite_coverage`] of the characters layout draws in numeral system `digits`:
|
||||
/// each grapheme cluster's part is chosen by its own first character, and the part's face is
|
||||
/// checked for the cluster's drawn characters ([`crate::drawn_chars`]).
|
||||
pub fn composite_drawn_coverage(&self, name: &str, texts: &[&str], digits: Digits) -> Option<CompositeCoverage> {
|
||||
self.coverage_of(name, texts, Some((digits, false)))
|
||||
}
|
||||
|
||||
/// [`FontDb::composite_drawn_coverage`] of type set in All Caps when `all_caps` is on: each
|
||||
/// cluster's part is still chosen by its own first character, and the part's face is also
|
||||
/// checked for the capitals layout draws.
|
||||
pub fn composite_cased_coverage(&self, name: &str, texts: &[&str], digits: Digits, all_caps: bool) -> Option<CompositeCoverage> {
|
||||
self.coverage_of(name, texts, Some((digits, all_caps)))
|
||||
}
|
||||
|
||||
fn coverage_of(&self, name: &str, texts: &[&str], digits: Option<(Digits, bool)>) -> Option<CompositeCoverage> {
|
||||
let f = self.composite_font(name)?;
|
||||
let rank = |m: FontMatch| match m {
|
||||
FontMatch::Exact => 0,
|
||||
@@ -272,7 +290,18 @@ impl FontDb {
|
||||
if worst.as_ref().is_none_or(|(w, _)| rank(m) > rank(*w)) {
|
||||
worst = Some((m, found.as_ref().map(|(face, _)| face.clone())));
|
||||
}
|
||||
lacking.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c))));
|
||||
match digits {
|
||||
Some((d, caps)) => {
|
||||
let missing = |c: &char| !found.as_ref().is_some_and(|(face, _)| face.covers(*c));
|
||||
lacking.extend(crate::drawn_chars(g, d).filter(missing));
|
||||
if caps {
|
||||
let upper: String = g.chars().flat_map(char::to_uppercase).collect();
|
||||
lacking.extend(crate::drawn_chars(&upper, d).filter(missing));
|
||||
}
|
||||
}
|
||||
None => lacking
|
||||
.extend(g.chars().filter(|c| !c.is_whitespace() && !c.is_control() && !found.as_ref().is_some_and(|(face, _)| face.covers(*c)))),
|
||||
}
|
||||
}
|
||||
lacking.sort_unstable();
|
||||
lacking.dedup();
|
||||
|
||||
@@ -99,6 +99,8 @@ pub fn fit_source_lines(db: &FontDb, t: &mut TextObject, lines: usize) -> bool {
|
||||
/// own underline and strikeout metrics through the glyph's transform (so the size, baseline shift
|
||||
/// and scaling follow) → (run, bar in text space). Type on a path and vertical type have none yet.
|
||||
pub fn decorations(layout: &TextLayout, db: &FontDb, t: &TextObject) -> Vec<(usize, BezPath)> {
|
||||
#[cfg(any(test, feature = "test-fonts"))]
|
||||
crate::test_fonts::count_decorations();
|
||||
let mut out = vec![];
|
||||
if layout.on_path || layout.vertical {
|
||||
return out;
|
||||
@@ -449,6 +451,14 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout
|
||||
let original = |run: &mut usize| *run = from.get(*run).copied().unwrap_or(*run);
|
||||
l.glyphs.iter_mut().chain(l.ruby.iter_mut()).for_each(|g| original(&mut g.run));
|
||||
l.inlines.iter_mut().for_each(|i| original(&mut i.run));
|
||||
let mut ink: Vec<Option<Rect>> = vec![None; t.runs.len()];
|
||||
for (mut run, bounds) in std::mem::take(&mut l.run_ink_bounds).into_iter().enumerate() {
|
||||
original(&mut run);
|
||||
if let (Some(ink), Some(bounds)) = (ink.get_mut(run), bounds) {
|
||||
*ink = Some(ink.map_or(bounds, |ink| ink.union(bounds)));
|
||||
}
|
||||
}
|
||||
l.run_ink_bounds = ink;
|
||||
l
|
||||
}
|
||||
|
||||
@@ -572,6 +582,6 @@ fn layout_runs(db: &FontDb, t: &TextObject, opts: &LayoutOptions, set: Option<&T
|
||||
cx.out.line_xf = line_xf;
|
||||
}
|
||||
keep_lone_ligature_carets(&mut cx.out.glyphs);
|
||||
finish_bounds(&mut cx.out);
|
||||
finish_bounds(&mut cx.out, t.runs.len());
|
||||
cx.out
|
||||
}
|
||||
|
||||
@@ -402,9 +402,17 @@ pub(super) fn stands_upright(g: &SGlyph) -> bool {
|
||||
!needs_vertical_form || g.gid != g.face.glyph_for(g.ch)
|
||||
}
|
||||
|
||||
pub(super) fn finish_bounds(out: &mut TextLayout) {
|
||||
pub(super) fn finish_bounds(out: &mut TextLayout, runs: usize) {
|
||||
let xf = out.line_xf;
|
||||
let mut b: Option<Rect> = out.ink_bounds();
|
||||
let mut ink: Vec<Option<Rect>> = vec![None; runs];
|
||||
let mut b: Option<Rect> = None;
|
||||
out.for_each_ink(|run, bounds| {
|
||||
b = Some(b.map_or(bounds, |b| b.union(bounds)));
|
||||
if let Some(ink) = ink.get_mut(run) {
|
||||
*ink = Some(ink.map_or(bounds, |ink| ink.union(bounds)));
|
||||
}
|
||||
});
|
||||
out.run_ink_bounds = ink;
|
||||
let mut add = |r: Rect| b = Some(b.map_or(r, |b| b.union(r)));
|
||||
if !out.on_path {
|
||||
for l in &out.lines {
|
||||
|
||||
+30
-8
@@ -60,7 +60,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader};
|
||||
pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout};
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};
|
||||
pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled};
|
||||
pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
|
||||
pub use shape::{aki_space, drawn_chars, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
|
||||
pub use vectorcraft_doc::TextObject;
|
||||
|
||||
pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign};
|
||||
@@ -388,6 +388,9 @@ pub struct TextLayout {
|
||||
pub lines: Vec<LineInfo>,
|
||||
/// Ink/advance bounds in text space.
|
||||
pub bounds: Rect,
|
||||
/// Ink bounds per text run when layout completed, excluding decorations. These bounds do
|
||||
/// not update when glyph geometry changes; [`Self::ink_bounds`] measures the current geometry.
|
||||
pub run_ink_bounds: Vec<Option<Rect>>,
|
||||
/// True if area text did not fit its frame (the red overflow "+" marker), or on-path text ran
|
||||
/// past the end of the path.
|
||||
pub overflow: bool,
|
||||
@@ -422,6 +425,7 @@ impl Default for TextLayout {
|
||||
ruby: Vec::new(),
|
||||
lines: Vec::new(),
|
||||
bounds: Rect::ZERO,
|
||||
run_ink_bounds: Vec::new(),
|
||||
overflow: false,
|
||||
on_path: false,
|
||||
frames: Vec::new(),
|
||||
@@ -477,16 +481,34 @@ impl TextLayout {
|
||||
/// inline graphics included, without the lines' em boxes that [`Self::bounds`] also covers.
|
||||
/// What Align to Glyph Bounds aligns. `None` when nothing draws (only spaces, or no text).
|
||||
pub fn ink_bounds(&self) -> Option<Rect> {
|
||||
let outlined = |g: &PositionedGlyph| (!g.outline.elements().is_empty()).then(|| g.outline.bounding_box());
|
||||
let glyphs = self.glyphs.iter().flat_map(|g| {
|
||||
let mut bounds: Option<Rect> = None;
|
||||
self.for_each_ink(|_, ink| bounds = Some(bounds.map_or(ink, |bounds| bounds.union(ink))));
|
||||
bounds
|
||||
}
|
||||
fn for_each_ink(&self, mut add: impl FnMut(usize, Rect)) {
|
||||
let outlined = |g: &PositionedGlyph| {
|
||||
(!g.outline.elements().is_empty()).then(|| {
|
||||
#[cfg(any(test, feature = "test-fonts"))]
|
||||
test_fonts::count_ink_outline();
|
||||
g.outline.bounding_box()
|
||||
})
|
||||
};
|
||||
for g in &self.glyphs {
|
||||
let image = g.placed_image().map(|(image, xf)| xf.transform_rect_bbox(image.rect()));
|
||||
let colour = g.colour.as_ref().and_then(|c| c.geometric_bounds()).map(|b| g.xf.transform_rect_bbox(b));
|
||||
[outlined(g), image, colour]
|
||||
});
|
||||
for ink in [outlined(g), image, colour].into_iter().flatten() {
|
||||
add(g.run, ink);
|
||||
}
|
||||
}
|
||||
// Ruby is covered by its line's ascent, but its ink can overhang sideways past the line.
|
||||
let ruby = self.ruby.iter().map(outlined);
|
||||
let inlines = self.inlines.iter().map(|i| Some(i.bounds));
|
||||
glyphs.chain(ruby).chain(inlines).flatten().reduce(|a, b| a.union(b))
|
||||
for g in &self.ruby {
|
||||
if let Some(ink) = outlined(g) {
|
||||
add(g.run, ink);
|
||||
}
|
||||
}
|
||||
for inline in &self.inlines {
|
||||
add(inline.run, inline.bounds);
|
||||
}
|
||||
}
|
||||
/// The box of [`Self::ink_bounds`]' ink with text space mapped by `m`: the glyph and ruby
|
||||
/// outlines are mapped point by point, so a rotated or sheared `m` gives the outlines' own
|
||||
|
||||
@@ -1382,11 +1382,11 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
&& ligatures_suppressed_by(*tracking) == ligatures_suppressed_by(b.tracking)
|
||||
}
|
||||
|
||||
/// The characters of a grapheme cluster that need a glyph of their own, in the numeral system
|
||||
/// The characters of the text that need a glyph of their own, in the numeral system
|
||||
/// `digits`: not what the layout handles itself (tab, line and paragraph breaks), joiners or
|
||||
/// variation selectors.
|
||||
fn drawn_chars(cluster: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
|
||||
craft::font_catalog::drawable_characters(cluster, move |c| digits.map(c))
|
||||
pub fn drawn_chars(text: &str, digits: Digits) -> impl Iterator<Item = char> + '_ {
|
||||
craft::font_catalog::drawable_characters(text, move |c| digits.map(c))
|
||||
}
|
||||
|
||||
/// Does the face with charmap `map` have a glyph for `c` (any face does when it has no charmap)?
|
||||
|
||||
@@ -29,6 +29,20 @@ pub(crate) fn keeps_shape_plans() -> bool {
|
||||
std::thread_local! {
|
||||
/// How many layouts this thread has started ([`layouts_on_this_thread`]).
|
||||
static LAYOUTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
static INK_OUTLINES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
static DECORATIONS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
pub(crate) fn count_ink_outline() {
|
||||
INK_OUTLINES.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
|
||||
pub(crate) fn count_decorations() {
|
||||
DECORATIONS.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
|
||||
pub fn ink_work_on_this_thread() -> (u64, u64) {
|
||||
(INK_OUTLINES.with(std::cell::Cell::get), DECORATIONS.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
pub(crate) fn count_layout() {
|
||||
|
||||
@@ -89,16 +89,16 @@ pub fn menu() -> Vec<Node> {
|
||||
]
|
||||
}
|
||||
|
||||
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None };
|
||||
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
|
||||
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
|
||||
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
|
||||
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None };
|
||||
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None };
|
||||
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
|
||||
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None };
|
||||
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None };
|
||||
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None };
|
||||
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None, pin_opening_artboard: false };
|
||||
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None, pin_opening_artboard: false };
|
||||
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None, pin_opening_artboard: false };
|
||||
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None, pin_opening_artboard: false };
|
||||
static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None, pin_opening_artboard: false };
|
||||
static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None, pin_opening_artboard: false };
|
||||
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None, pin_opening_artboard: false };
|
||||
static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None, pin_opening_artboard: false };
|
||||
static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None, pin_opening_artboard: false };
|
||||
static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The dialog over `rows`, titled by the heading of `command`.
|
||||
fn dialog<'a>(command: &str, rows: Vec<Param>) -> ParamDialog<'a> {
|
||||
|
||||
@@ -298,6 +298,28 @@ fn add_artboard_guides_does_not_replace_a_deleted_artboard_with_its_neighbor() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_artboard_guides_preview_keeps_an_artboard_deleted_while_it_shows() {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
app.view_mut().unwrap().artboard = 0;
|
||||
click(&mut app, "Add Artboard Guides…");
|
||||
let id = host::dialog_id(&app);
|
||||
host::set(&app, id, "preview", json!(true));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(artboard_guides(&app).len(), 1);
|
||||
app.run("artboard.delete", json!({"index": 0})).unwrap();
|
||||
assert!(artboard_guides(&app).is_empty(), "the remaining artboard gets no guide");
|
||||
host::frame(&mut app);
|
||||
assert_eq!(app.session.doc().unwrap().doc.artboards.len(), 1);
|
||||
assert!(artboard_guides(&app).is_empty());
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert_eq!(app.session.doc().unwrap().doc.artboards.len(), 1);
|
||||
assert!(artboard_guides(&app).is_empty());
|
||||
assert_eq!(app.ui.status, "The artboard no longer exists.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_guides_menu_dialog_is_available_without_a_selection() {
|
||||
let (mut app, _, _) = app();
|
||||
|
||||
@@ -19,7 +19,7 @@ const SCOPES: [(&str, &str); 2] = [("selection", "Selection"), ("document", "Doc
|
||||
const KINDS: [(&str, &str); 3] = [("groups", "Groups"), ("clipGroups", "Clipping Masks"), ("compoundPaths", "Compound Paths")];
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The dialog's rows.
|
||||
fn rows() -> Vec<Param> {
|
||||
|
||||
@@ -17,7 +17,7 @@ pub const COMMAND: &str = "addon.color.swatchLegend";
|
||||
pub const VALUES: [(&str, &str); 5] = [("hex", "HEX"), ("rgb", "RGB"), ("cmyk", "CMYK"), ("lab", "Lab"), ("gray", "Grayscale")];
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The command's params from the dialog's fields.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
|
||||
@@ -21,7 +21,7 @@ const SEEDS: u64 = 1_000_000;
|
||||
/// The schemes the Colors choice offers: (`scheme`, label).
|
||||
const SCHEMES: [(&str, &str); 3] = [("color", "Any Color"), ("tint", "Tints of a Swatch"), ("gray", "Grays")];
|
||||
|
||||
static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
fn percent(key: &str, label: &'static str, default: f64) -> Param {
|
||||
Param::number(key, tl!(label), default, 1.0, 0).bounds(Some(0.0), Some(100.0)).unit(UnitKind::Percent).enabled_when_in("scheme", ["tint", "gray"])
|
||||
|
||||
@@ -27,6 +27,7 @@ pub(crate) struct Spec {
|
||||
pub params: fn(&DialogFields) -> Value,
|
||||
/// Receives the answer of each preview run (or its error), to show it in the dialog.
|
||||
pub found: Option<Found>,
|
||||
pub pin_opening_artboard: bool,
|
||||
}
|
||||
|
||||
impl Spec {
|
||||
@@ -45,6 +46,8 @@ pub(crate) struct AddonDialogs {
|
||||
open: Option<Open>,
|
||||
preview: LivePreview,
|
||||
preview_error: Option<(u64, String)>,
|
||||
/// Preview and OK are running with the dialog's opening artboard.
|
||||
pub(crate) using_opening_artboard: bool,
|
||||
/// The open Tangent Circle Tool radius dialog.
|
||||
pub(crate) tangent_radius: Option<super::pathtools::tangent_circle_radius::Open>,
|
||||
}
|
||||
@@ -55,6 +58,8 @@ struct Open {
|
||||
spec: &'static Spec,
|
||||
/// The opening document's uid and revert count: File › Revert keeps the uid but replaces the drawing.
|
||||
document: Option<(u64, u64)>,
|
||||
/// The view's active artboard when the dialog opened.
|
||||
artboard: Option<u32>,
|
||||
}
|
||||
|
||||
impl Open {
|
||||
@@ -73,6 +78,40 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> {
|
||||
app.session.active().map(|state| (state.uid, state.reverts))
|
||||
}
|
||||
|
||||
/// Runs the open dialog's command with its opening artboard, then restores the saved artboard.
|
||||
pub(crate) fn with_opening_artboard<T>(app: &mut VectorcraftApp, command: &str, run: impl FnOnce(&mut VectorcraftApp) -> T) -> T {
|
||||
let saved =
|
||||
app.addon_dialogs.open.filter(|open| open.spec.pin_opening_artboard && open.spec.command == command && open.on_document(app)).and_then(
|
||||
|open| {
|
||||
let state = app.session.active_mut()?;
|
||||
let saved = (state.uid, state.active_artboard);
|
||||
state.active_artboard = open.artboard;
|
||||
Some(saved)
|
||||
},
|
||||
);
|
||||
let using_opening_artboard = app.addon_dialogs.using_opening_artboard;
|
||||
if saved.is_some() {
|
||||
app.addon_dialogs.using_opening_artboard = true;
|
||||
}
|
||||
let answer = run(app);
|
||||
app.addon_dialogs.using_opening_artboard = using_opening_artboard;
|
||||
if let Some((uid, artboard)) = saved
|
||||
&& let Some(state) = app.session.document_mut(uid)
|
||||
{
|
||||
state.active_artboard = artboard;
|
||||
}
|
||||
answer
|
||||
}
|
||||
|
||||
pub(crate) fn artboard_deletion_guard(app: &VectorcraftApp) -> Option<vectorcraft_engine::ArtboardDeletionGuard> {
|
||||
let open = app.addon_dialogs.open.filter(|open| open.spec.pin_opening_artboard)?;
|
||||
Some(vectorcraft_engine::ArtboardDeletionGuard {
|
||||
document: open.document?,
|
||||
artboard: open.artboard?,
|
||||
message: "Close Create Font Sheet before deleting its opening artboard.".to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Closes the open add-on dialog without an answer and rolls its preview back.
|
||||
pub(crate) fn close_open(app: &mut VectorcraftApp) {
|
||||
let Some(open) = app.addon_dialogs.open.take() else { return };
|
||||
@@ -97,14 +136,28 @@ pub(crate) fn open(
|
||||
spec: &'static Spec,
|
||||
fields: DialogFields,
|
||||
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
|
||||
) -> Result<Value, String> {
|
||||
open_with(app, spec, fields, build, true)
|
||||
}
|
||||
|
||||
/// [`open`], with the Preview box on at the start when `previewing`, else off.
|
||||
pub(crate) fn open_with(
|
||||
app: &mut VectorcraftApp,
|
||||
spec: &'static Spec,
|
||||
fields: DialogFields,
|
||||
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
|
||||
previewing: bool,
|
||||
) -> Result<Value, String> {
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window")?;
|
||||
let dialog = HostedParamDialog::new(&ctx, spec.command, fields, build);
|
||||
let dialog = if previewing { dialog } else { dialog.preview_off() };
|
||||
let host = app.dialogs().ok_or("no window")?;
|
||||
close_open(app);
|
||||
crate::io::remember_active_artboard(app);
|
||||
let artboard = app.session.active().and_then(|state| state.active_artboard);
|
||||
let id = dialog.id();
|
||||
host.with(|h| h.open(dialog));
|
||||
app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app) });
|
||||
app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app), artboard });
|
||||
Ok(json!({ "dialog": spec.command }))
|
||||
}
|
||||
|
||||
@@ -120,6 +173,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
|
||||
pathtools::tangents::BRIDGE => pathtools::tangents::open_connected,
|
||||
pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open,
|
||||
typetools::COMMAND => typetools::open,
|
||||
typetools::font_sheet::COMMAND => typetools::font_sheet::open,
|
||||
typetools::numbers::COMMAND => typetools::numbers::open,
|
||||
color::legend::COMMAND => color::legend::open,
|
||||
color::nearest::COMMAND => color::nearest::open,
|
||||
@@ -147,13 +201,23 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
let Some(host) = app.dialogs() else { return };
|
||||
let Open { id, spec, .. } = open;
|
||||
let on_document = open.on_document(app);
|
||||
let missing_artboard = spec.pin_opening_artboard
|
||||
&& on_document
|
||||
&& open.artboard.is_some_and(|id| app.session.active().is_some_and(|state| !state.doc.artboards.iter().any(|artboard| artboard.id == id)));
|
||||
if !on_document {
|
||||
// Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing.
|
||||
app.addon_dialogs.preview = LivePreview::default();
|
||||
app.addon_dialogs.preview_error = None;
|
||||
}
|
||||
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), spec.params(app, d.fields()))));
|
||||
if on_document && let Some((previewing, params)) = &live {
|
||||
if missing_artboard {
|
||||
mem::take(&mut app.addon_dialogs.preview).cancel(app);
|
||||
app.status(tl!("The opening artboard was deleted. Reopen this dialog to continue."));
|
||||
}
|
||||
if on_document
|
||||
&& !missing_artboard
|
||||
&& let Some((previewing, params)) = &live
|
||||
{
|
||||
let mut preview = mem::take(&mut app.addon_dialogs.preview);
|
||||
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
|
||||
let answer = match params {
|
||||
@@ -165,6 +229,10 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
Some(Err(error.clone()))
|
||||
}
|
||||
};
|
||||
// Edit Points Only previews a selection, which an outside command (Clear) has to see as shown.
|
||||
if spec.command != super::select::points_only::COMMAND {
|
||||
preview.keep_outside_edits(app);
|
||||
}
|
||||
app.addon_dialogs.preview = preview;
|
||||
if spec.command == super::select::points_only::COMMAND {
|
||||
match &answer {
|
||||
@@ -183,13 +251,15 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
}
|
||||
match host.with(|h| h.take_by_id::<HostedParamDialog>(id)).map(DialogResult::ok) {
|
||||
Some(Some(result)) => {
|
||||
app.addon_dialogs.open = None;
|
||||
let preview = mem::take(&mut app.addon_dialogs.preview);
|
||||
// The dialog is closed already, so a refusal can only go to the status line.
|
||||
if open.reverted(app) {
|
||||
app.status("The document was reverted. Reopen this dialog to continue.");
|
||||
} else if !on_document {
|
||||
app.status("The add-on settings apply only to the drawing where the dialog opened.");
|
||||
} else if missing_artboard {
|
||||
preview.cancel(app);
|
||||
app.status(tl!("The opening artboard was deleted. Reopen this dialog to continue."));
|
||||
} else {
|
||||
let answer = match spec.params(app, &result.fields) {
|
||||
Ok(params) if spec.command == super::select::points_only::COMMAND => preview.commit_selection(app, spec.command, params),
|
||||
@@ -205,6 +275,7 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
clear_preview_error(app);
|
||||
}
|
||||
}
|
||||
app.addon_dialogs.open = None;
|
||||
app.addon_dialogs.preview_error = None;
|
||||
}
|
||||
Some(None) => {
|
||||
|
||||
@@ -229,6 +229,28 @@ fn rows() -> Vec<Row> {
|
||||
assert!(label.contains("#123456") && label.contains("C="), "{label}");
|
||||
},
|
||||
},
|
||||
Row {
|
||||
group: "Type Tools",
|
||||
label: "Create Font Sheet…",
|
||||
setup: new_app,
|
||||
refused: || vec![("text", json!(" "))],
|
||||
values: || vec![("text", json!("Sample")), ("filter", json!("JetBrains Mono"))],
|
||||
check: |app| {
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
let sheet = doc.layers[0].children().unwrap().last().unwrap();
|
||||
assert_eq!(sheet.name.as_deref(), Some("Font Sheet"));
|
||||
let texts: Vec<String> = sheet
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|c| match &c.kind {
|
||||
NodeKind::Text(t) => Some(t.plain_text()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(texts.contains(&"JetBrains Mono\nSample".to_string()), "{texts:?}");
|
||||
},
|
||||
},
|
||||
Row {
|
||||
group: "Color Effects",
|
||||
label: "Randomize Fill Colors…",
|
||||
@@ -318,6 +340,154 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview()
|
||||
assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_a_dialog_preview_uses_only_the_shown_base_objects() {
|
||||
for include_base_object in [false, true] {
|
||||
let mut app = two_rects_filled();
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let selected = app.session.active().unwrap().selection.objects.clone();
|
||||
let undo = undo_len(&app);
|
||||
let mut preview = crate::dialogs::preview::LivePreview::default();
|
||||
let params = json!({});
|
||||
assert!(preview.run(&mut app, true, "Flood Fill Artboards", "addon.document.floodFillArtboards", ¶ms).unwrap().is_ok());
|
||||
preview.keep_outside_edits(&mut app);
|
||||
assert!(!app.session.active().unwrap().selection.objects.is_empty());
|
||||
assert!(app.session.active().unwrap().selection.objects.iter().all(|id| original.node(*id).is_none()));
|
||||
if include_base_object {
|
||||
app.session.active_mut().unwrap().selection.add(selected[0]);
|
||||
}
|
||||
|
||||
let result = app.run("edit.clear", json!({}));
|
||||
if include_base_object {
|
||||
result.unwrap();
|
||||
}
|
||||
preview.cancel(&mut app);
|
||||
let state = app.session.active().unwrap();
|
||||
assert!(state.doc.node(selected[1]).is_some(), "Clear must keep hidden selected artwork");
|
||||
if include_base_object {
|
||||
assert!(state.doc.node(selected[0]).is_none(), "Clear deletes a shown object present in the base document");
|
||||
assert_eq!(undo_len(&app), undo + 1);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc, original);
|
||||
} else {
|
||||
assert_eq!(state.doc, original, "Cancel keeps all artwork when only preview objects were selected");
|
||||
assert_eq!(undo_len(&app), undo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_anchors_of_a_path_the_preview_recut_keeps_the_base_path() {
|
||||
let mut app = two_rects_filled();
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let ids = app.session.active().unwrap().selection.objects.clone();
|
||||
app.run("select.anchors", json!({"id": ids[0].0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
let mut preview = crate::dialogs::preview::LivePreview::default();
|
||||
assert!(preview.run(&mut app, true, "Set Corners", "addon.pathtools.cornerSet", &json!({"radius": 2, "kind": "chamfer"})).unwrap().is_ok());
|
||||
preview.keep_outside_edits(&mut app);
|
||||
assert!(!app.session.active().unwrap().selection.anchors.is_empty(), "anchors on the recut path are on show");
|
||||
let _refused = app.run("edit.clear", json!({}));
|
||||
preview.cancel(&mut app);
|
||||
assert_eq!(app.session.active().unwrap().doc, original, "Clear deletes no anchor of the base path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_outside_command_keeps_the_dialog_selection() {
|
||||
let mut app = two_rects_filled();
|
||||
let selected = app.session.active().unwrap().selection.objects.clone();
|
||||
let mut preview = crate::dialogs::preview::LivePreview::default();
|
||||
assert!(preview.run(&mut app, true, "Flood Fill Artboards", "addon.document.floodFillArtboards", &json!({})).unwrap().is_ok());
|
||||
preview.keep_outside_edits(&mut app);
|
||||
let shown = app.session.active().unwrap().selection.clone();
|
||||
assert!(app.run("edit.clear", json!({})).is_err(), "only preview objects are selected");
|
||||
let state = app.session.active().unwrap();
|
||||
assert_eq!(state.interaction.as_ref().unwrap().selection.objects, selected, "the dialog keeps its own selection");
|
||||
assert_eq!(state.selection, shown, "the preview's selection is on show again");
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert!(app.session.active().unwrap().interaction.as_ref().unwrap().selection.objects.is_empty(), "Deselect still deselects");
|
||||
preview.cancel(&mut app);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outside_command_journals_the_selection_it_acts_on() {
|
||||
let mut app = two_rects_filled();
|
||||
let selected = app.session.active().unwrap().selection.objects.clone();
|
||||
let mut preview = crate::dialogs::preview::LivePreview::default();
|
||||
assert!(preview.run(&mut app, true, "Flood Fill Artboards", "addon.document.floodFillArtboards", &json!({})).unwrap().is_ok());
|
||||
preview.keep_outside_edits(&mut app);
|
||||
app.session.active_mut().unwrap().selection.add(selected[0]);
|
||||
let start = app.session.journal_for_action(0).len();
|
||||
app.run("edit.clear", json!({})).unwrap();
|
||||
let action = app.session.journal_for_action(start);
|
||||
let clear = action.iter().position(|(id, _)| id == "edit.clear").unwrap();
|
||||
assert!(action[..clear].iter().any(|(id, _)| id.starts_with("select.")), "Clear replays on the shown selection: {action:?}");
|
||||
preview.cancel(&mut app);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_dialog_preview_retries_after_an_outside_selection_change() {
|
||||
let mut app = two_rects();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let mut preview = crate::dialogs::preview::LivePreview::default();
|
||||
let params = json!({"offset": 5});
|
||||
assert!(preview.run(&mut app, true, "Contour", "addon.contour.set", ¶ms).unwrap().is_err());
|
||||
preview.keep_outside_edits(&mut app);
|
||||
assert!(preview.run(&mut app, true, "Contour", "addon.contour.set", ¶ms).is_none());
|
||||
let document = app.session.active().unwrap().doc.clone();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &document));
|
||||
assert!(preview.run(&mut app, true, "Contour", "addon.contour.set", ¶ms).unwrap().is_ok());
|
||||
assert!(count(&app) > 2);
|
||||
preview.cancel(&mut app);
|
||||
assert_eq!(app.session.active().unwrap().doc, document);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outside_dialog_selection_keeps_its_paints_after_cancel() {
|
||||
let mut app = two_rects();
|
||||
let ids = app.session.active().unwrap().selection.objects.clone();
|
||||
app.run("select.set", json!({"ids": [ids[0].0]})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
|
||||
app.run("select.set", json!({"ids": [ids[1].0]})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
|
||||
let expected = app.session.paint.clone();
|
||||
app.run("select.set", json!({"ids": [ids[0].0]})).unwrap();
|
||||
assert_ne!(app.session.paint, expected);
|
||||
|
||||
let mut preview = crate::dialogs::preview::LivePreview::default();
|
||||
assert!(preview.run(&mut app, true, "Move", "object.move", &json!({"dx": 10, "dy": 0})).unwrap().is_ok());
|
||||
preview.keep_outside_edits(&mut app);
|
||||
app.run("select.set", json!({"ids": [ids[1].0]})).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().selection.objects, vec![ids[1]]);
|
||||
assert_eq!(app.session.paint, expected);
|
||||
preview.cancel(&mut app);
|
||||
assert_eq!(app.session.active().unwrap().selection.objects, vec![ids[1]]);
|
||||
assert_eq!(app.session.paint, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_preview_keeps_an_edit_made_outside_the_dialog() {
|
||||
let mut app = two_rects();
|
||||
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
|
||||
let id = dialog_id(&app);
|
||||
set(&app, id, "layout", json!("row"));
|
||||
set(&app, id, "preview", json!(true));
|
||||
frame(&mut app);
|
||||
assert_eq!(x0(&app, 1), 30.0, "previewed");
|
||||
let undo = undo_len(&app);
|
||||
app.run("shape.rectangle", json!({"x": 300, "y": 300, "width": 10, "height": 10})).unwrap();
|
||||
assert_eq!(undo_len(&app), undo + 1, "the rectangle is a step of its own");
|
||||
set(&app, id, "layout", json!("column"));
|
||||
frame(&mut app);
|
||||
assert_eq!(count(&app), 3, "the next preview keeps the rectangle");
|
||||
cancel(&app, id);
|
||||
frame(&mut app);
|
||||
assert!(!app.session.in_interaction());
|
||||
assert_eq!(count(&app), 3, "Cancel keeps the rectangle");
|
||||
assert_eq!(x0(&app, 1), 100.0, "Cancel rolls the preview back");
|
||||
assert_eq!(undo_len(&app), undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_preview_waits_for_its_opening_drawing() {
|
||||
let mut app = two_drawings();
|
||||
|
||||
@@ -33,7 +33,7 @@ const FLOOD_LAYER: &str = "Flood Fill";
|
||||
/// The color the Flood Fill Artboards dialog opens with when the current fill is not a solid color.
|
||||
const GRAY: [f32; 3] = [0.5, 0.5, 0.5];
|
||||
|
||||
static FLOOD_SPEC: Spec = Spec { command: FLOOD_FILL, params: flood_params, found: None };
|
||||
static FLOOD_SPEC: Spec = Spec { command: FLOOD_FILL, params: flood_params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// Object › Plug-ins › Document Tools.
|
||||
pub fn menu() -> Vec<Node> {
|
||||
|
||||
@@ -134,7 +134,7 @@ mod tests {
|
||||
let undo = panel.app().session.active().unwrap().history.undo.len();
|
||||
panel.click_role(label, Role::SPIN_BUTTON);
|
||||
panel.key(Key::A, Modifiers::COMMAND);
|
||||
panel.type_text(typed);
|
||||
panel.type_text(&crate::tests::regional_text(typed));
|
||||
panel.frame();
|
||||
let proposed = panel.app().session.tool_options_of(tool);
|
||||
assert_ne!(proposed[key], before[key], "{label} changes while typing");
|
||||
|
||||
@@ -16,7 +16,7 @@ const DASHES: std::ops::RangeInclusive<f64> = 0.01..=1e6;
|
||||
const GAPS: std::ops::RangeInclusive<f64> = 0.0..=1e6;
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The command's parameters from the dialog's fields.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
|
||||
@@ -23,7 +23,7 @@ const EVERY: [(&str, &str); 3] = [("all", "All Anchors"), ("odd", "Odd-Numbered
|
||||
const ANGLES: std::ops::RangeInclusive<f64> = 0.0..=180.0;
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The command's parameters from the dialog's fields.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
|
||||
@@ -20,7 +20,7 @@ const MAX_CIRCLES: u64 = 64;
|
||||
const RADIUS: f64 = 36.0;
|
||||
|
||||
/// How the dialog's values reach the command; the preview's answer says how many circles were found.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: Some(found) };
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: Some(found), pin_opening_artboard: false };
|
||||
|
||||
/// The circle number the choice holds (an option id): 0 is every circle, `k` the k-th, counted from 1.
|
||||
fn circle(fields: &DialogFields) -> u64 {
|
||||
|
||||
@@ -36,7 +36,7 @@ const REACHES: std::ops::RangeInclusive<f64> = 0.0..=10000.0;
|
||||
const REACH: f64 = 10.0;
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMON_TANGENTS, params, found: None };
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMON_TANGENTS, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// Whether the fields ask for a curved bridge: External with Curved.
|
||||
fn curved(fields: &DialogFields) -> bool {
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::menus::c;
|
||||
/// Edit Points Only: the dialog's key and the command its OK runs.
|
||||
pub const COMMAND: &str = "addon.select.editPointsOnly";
|
||||
|
||||
static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The menu item.
|
||||
pub fn menu() -> Vec<Node> {
|
||||
|
||||
@@ -663,7 +663,7 @@ mod cancel_tests {
|
||||
panel.frame();
|
||||
panel.click_role("TL", Role::SPIN_BUTTON);
|
||||
panel.key(Key::A, Modifiers::COMMAND);
|
||||
panel.type_text("4.125");
|
||||
panel.type_text(&crate::tests::regional_text("4.125"));
|
||||
panel.frame();
|
||||
let proposed = panel.app().session.tool_options();
|
||||
assert_ne!(proposed["cornerRadii"], before["cornerRadii"]);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Type Tools in the interface: its submenu (Object › Plug-ins › Type Tools) and Text Tweaker's
|
||||
//! dialog, which picks an attribute, its start and end values and a shape, previews on the canvas
|
||||
//! and runs `addon.type.textTweaker` on OK.
|
||||
//! and runs `addon.type.textTweaker` on OK. Create Font Sheet's dialog is [`font_sheet`]'s.
|
||||
|
||||
pub mod font_sheet;
|
||||
|
||||
use craft::menu::Node;
|
||||
use craft::ui::contract::Bind;
|
||||
@@ -45,6 +47,7 @@ pub fn menu() -> Vec<Node> {
|
||||
vec![
|
||||
c("Text Tweaker…", COMMAND),
|
||||
cp("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})),
|
||||
c("Create Font Sheet…", font_sheet::COMMAND),
|
||||
c("Make Numbers Sequence…", numbers::COMMAND),
|
||||
]
|
||||
}
|
||||
@@ -55,7 +58,7 @@ fn attribute(key: &str) -> &'static Attribute {
|
||||
}
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The command's parameters from the dialog's fields; an end of the ramp not set yet is the attribute's own.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Create Font Sheet in the interface (Object › Plug-ins › Type Tools › Create Font Sheet…): a
|
||||
//! dialog for the sample text, its size, a filter on the family names, whether each style gets an
|
||||
//! entry and a label, and the columns, gap and margin of the pages. Its Preview box starts off;
|
||||
//! switched on, it previews on the canvas. It runs `addon.type.fontSheet` on OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::{self, Spec};
|
||||
use crate::canvas::rulers::general_lengths;
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.type.fontSheet";
|
||||
/// The sample text the dialog opens on.
|
||||
const SAMPLE: &str = "The quick brown fox jumps over the lazy dog";
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: true };
|
||||
|
||||
/// The command's parameters from the dialog's fields; an empty filter sets every family.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
let mut p = json!({
|
||||
"text": fields.text("text").unwrap_or(SAMPLE),
|
||||
"size": fields.number("size").unwrap_or(12.0),
|
||||
"allStyles": fields.bool("allStyles").unwrap_or(false),
|
||||
"labels": fields.bool("labels").unwrap_or(true),
|
||||
"columns": fields.int("columns").unwrap_or(2),
|
||||
"gap": fields.number("gap").unwrap_or(12.0),
|
||||
"margin": fields.number("margin").unwrap_or(36.0),
|
||||
"newArtboards": fields.bool("newArtboards").unwrap_or(true),
|
||||
});
|
||||
if let Some(filter) = fields.text("filter").map(str::trim).filter(|f| !f.is_empty()) {
|
||||
p["filter"] = json!(filter);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Opens Create Font Sheet's dialog on the command's defaults, with Preview off: each preview sets
|
||||
/// the whole sheet again.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let fields = DialogFields::from_pairs([
|
||||
("text", FieldValue::Text(SAMPLE.into())),
|
||||
("size", FieldValue::Number(12.0)),
|
||||
("filter", FieldValue::Text(String::new())),
|
||||
("allStyles", FieldValue::Bool(false)),
|
||||
("labels", FieldValue::Bool(true)),
|
||||
("columns", FieldValue::Int(2)),
|
||||
("gap", FieldValue::Number(12.0)),
|
||||
("margin", FieldValue::Number(36.0)),
|
||||
("newArtboards", FieldValue::Bool(true)),
|
||||
]);
|
||||
let lengths = general_lengths(app);
|
||||
dialogs::open_with(
|
||||
app,
|
||||
&SPEC,
|
||||
fields,
|
||||
move |fields| {
|
||||
let written = fields.text("text").is_some_and(|t| !t.trim().is_empty());
|
||||
let rows = vec![
|
||||
Param::new("text", tl!("Sample Text:"), ParamKind::text(SAMPLE)),
|
||||
Param::number("size", tl!("Size:"), 12.0, 1.0, 1).unit(UnitKind::Points).bounds(Some(1.0), Some(1296.0)),
|
||||
Param::new("filter", tl!("Font Names Containing:"), ParamKind::text("")),
|
||||
Param::new("allStyles", tl!("Every Style"), ParamKind::bool(false)),
|
||||
Param::new("labels", tl!("Label Each Font"), ParamKind::bool(true)),
|
||||
Param::new("columns", tl!("Columns:"), ParamKind::int(Some(1), Some(50), 2)),
|
||||
Param::number("gap", tl!("Gap:"), 12.0, 1.0, 2).length(lengths).bounds(Some(0.0), Some(1000.0)),
|
||||
Param::number("margin", tl!("Margin:"), 36.0, 1.0, 2).length(lengths).bounds(Some(0.0), Some(1000.0)),
|
||||
Param::new("newArtboards", tl!("Add Artboards When Full"), ParamKind::bool(true)),
|
||||
];
|
||||
ParamDialog::new(COMMAND, tl!("Create Font Sheet"), rows)
|
||||
.ok_enabled(written)
|
||||
.ok_reason(tl!("Type a sample text.").into())
|
||||
.values(Bind::bound(fields))
|
||||
.previews(true)
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,457 @@
|
||||
use craft::behavior::Mixed;
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{NodeKind, TextObject};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
/// The entries of the selected font sheet.
|
||||
fn sheet(app: &VectorcraftApp) -> Vec<TextObject> {
|
||||
let state = app.session.active().unwrap();
|
||||
let group = state.doc.node(state.selection.objects[0]).unwrap();
|
||||
assert_eq!(group.name.as_deref(), Some("Font Sheet"));
|
||||
group
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|node| match &node.kind {
|
||||
NodeKind::Text(text) => (**text).clone(),
|
||||
_ => panic!("a font sheet holds only type"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn assert_typed_sheet(app: &VectorcraftApp) {
|
||||
let entries = sheet(app);
|
||||
assert_eq!(entries.len(), 1, "the typed filter picks one family");
|
||||
let entry = &entries[0];
|
||||
assert_eq!(entry.plain_text(), "Hamburg", "the typed text, with the label switched off");
|
||||
assert_eq!(entry.runs[0].style.font_family, "Source Serif 4");
|
||||
assert!((entry.runs[0].style.size - 20.0).abs() < 1e-9, "the typed size reaches the sample");
|
||||
}
|
||||
|
||||
/// The dialog opens with Preview off. The keyboard and checkbox edits reach the preview once it is
|
||||
/// switched on, and OK; Cancel restores the drawing, while OK with Preview left off applies the
|
||||
/// same fields in one undo step.
|
||||
#[test]
|
||||
fn keyboard_and_checkbox_edits_reach_font_sheet_preview_ok_and_cancel() {
|
||||
for commit in [false, true] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
|
||||
let before = app.session.active().unwrap().doc.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(false)), "Preview starts off");
|
||||
assert!(!panel.app().session.in_interaction(), "the opening sheet is not previewed");
|
||||
assert!(panel.app().session.active().unwrap().doc == before);
|
||||
if !commit {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert!(panel.app().session.in_interaction(), "switched on, Preview shows the sheet");
|
||||
}
|
||||
for (label, input) in [("Sample Text", "Hamburg"), ("Font Names Containing", "Source Serif 4")] {
|
||||
panel.click_role(label, Role::TEXT_INPUT);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(input);
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
}
|
||||
for (label, input) in [("Size", "20"), ("Columns", "1")] {
|
||||
panel.click_role(label, Role::SPIN_BUTTON);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(input);
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
}
|
||||
panel.click_role("Label Each Font", Role::CHECK_BOX);
|
||||
if commit {
|
||||
assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone");
|
||||
panel.click("OK");
|
||||
assert_typed_sheet(&panel.app());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
} else {
|
||||
assert_typed_sheet(&panel.app());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step");
|
||||
panel.click("Cancel");
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing");
|
||||
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts that every entry of the selected font sheet starts on artboard `index`.
|
||||
fn assert_on_artboard(app: &VectorcraftApp, index: usize, case: &str) {
|
||||
let board = app.session.active().unwrap().doc.artboards[index].rect;
|
||||
let entries = sheet(app);
|
||||
assert!(!entries.is_empty(), "{case}");
|
||||
for entry in &entries {
|
||||
let [.., x, _] = entry.xf.as_coeffs();
|
||||
assert!(x >= board.x0 && x <= board.x1, "{case}: entry at {x} lies outside artboard {index} {board:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview and OK with Preview off use the artboard picked in the view before the dialog opens.
|
||||
#[test]
|
||||
fn font_sheet_preview_and_ok_use_the_views_current_artboard() {
|
||||
for preview in [false, true] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
|
||||
app.sync_views();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
panel.click_role("Font Names Containing", Role::TEXT_INPUT);
|
||||
panel.type_text("Source Serif 4");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
panel.app().view_mut().unwrap().artboard = 0;
|
||||
if preview {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert!(panel.app().session.in_interaction());
|
||||
assert_on_artboard(&panel.app(), 1, "the preview on the opening artboard");
|
||||
}
|
||||
panel.click("OK");
|
||||
assert_on_artboard(&panel.app(), 1, if preview { "OK after Preview" } else { "OK with Preview off" });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_opening_artboard_refuses_font_sheet_preview_and_ok() {
|
||||
for preview in [false, true] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
|
||||
app.sync_views();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
panel.click_role("Font Names Containing", Role::TEXT_INPUT);
|
||||
panel.type_text("Source Serif 4");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
panel.app().session.execute("artboard.delete", &json!({"index": 1})).unwrap();
|
||||
let before = panel.app().session.active().unwrap().doc.clone();
|
||||
let undo = panel.app().session.active().unwrap().history.undo.len();
|
||||
if preview {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, before);
|
||||
assert_eq!(panel.app().ui.status, "The opening artboard was deleted. Reopen this dialog to continue.");
|
||||
assert_eq!(panel.app().ui.status, tl!("The opening artboard was deleted. Reopen this dialog to continue."));
|
||||
}
|
||||
panel.click("OK");
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, before, "OK creates no sheet entries after the opening artboard is deleted");
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
assert_eq!(panel.app().ui.status, "The opening artboard was deleted. Reopen this dialog to continue.");
|
||||
assert_eq!(panel.app().ui.status, tl!("The opening artboard was deleted. Reopen this dialog to continue."));
|
||||
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_opening_artboard_is_refused_before_it_changes_a_font_sheet_preview() {
|
||||
for preview in [false, true] {
|
||||
for commit in [false, true] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap();
|
||||
app.sync_views();
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
panel.click_role("Font Names Containing", Role::TEXT_INPUT);
|
||||
panel.type_text("Source Serif 4");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
if preview {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
}
|
||||
let before = panel.app().session.active().unwrap().doc.clone();
|
||||
let selection = panel.app().session.active().unwrap().selection.clone();
|
||||
for params in [json!({"index": 1}), json!({"indices": [2, 1, 1]})] {
|
||||
let (request, _) = craft::automation::ControlRequest::new("engine.execute", json!({"command": "artboard.delete", "params": params}));
|
||||
let craft::automation::Reply::Done(answer) = crate::control::handle(&mut panel.app(), &egui::Context::default(), &request) else {
|
||||
panic!("the deletion did not finish");
|
||||
};
|
||||
assert_eq!(answer["ok"], false, "{answer}");
|
||||
assert!(answer.to_string().contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{answer}");
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, before);
|
||||
assert_eq!(panel.app().session.active().unwrap().selection, selection);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(panel.app().session.in_interaction(), preview);
|
||||
assert!(panel.app().session.artboard_deletion_guard.is_none());
|
||||
}
|
||||
panel.click(if commit { "OK" } else { "Cancel" });
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
if commit {
|
||||
assert_on_artboard(&panel.app(), 1, "OK after a refused deletion");
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, original);
|
||||
panel.app().run("artboard.delete", json!({"index": 1})).unwrap();
|
||||
assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_cannot_delete_the_font_sheet_dialogs_opening_artboard() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap();
|
||||
app.sync_views();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
let before = panel.app().session.active().unwrap().doc.clone();
|
||||
let undo = panel.app().session.active().unwrap().history.undo.len();
|
||||
let error = panel
|
||||
.app()
|
||||
.run(
|
||||
"command.batch",
|
||||
json!({"commands": [
|
||||
{"command": "artboard.delete", "params": {"index": 0}},
|
||||
{"command": "artboard.delete", "params": {"index": 0}}
|
||||
]}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{error}");
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, before, "the earlier deletion is rolled back");
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
assert!(panel.app().session.artboard_deletion_guard.is_none());
|
||||
panel.click("Cancel");
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_slice_cannot_delete_the_font_sheet_dialogs_opening_artboard() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
|
||||
app.sync_views();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
let before = panel.app().session.active().unwrap().doc.clone();
|
||||
panel.app().session.script_frames = true;
|
||||
let started = panel.app().run("script.run", json!({"source": "vc.run('artboard.delete', {index: 1});", "name": "t.js"}));
|
||||
assert_eq!(started.map(|v| v["running"].clone()), Ok(json!(true)), "the run goes on in the frames");
|
||||
for _ in 0..1_000 {
|
||||
if !panel.app().session.script_running() {
|
||||
break;
|
||||
}
|
||||
crate::script_runs::poll(&mut panel.app());
|
||||
}
|
||||
assert!(!panel.app().session.script_running());
|
||||
let status = panel.app().ui.status.clone();
|
||||
assert!(status.contains(tl!("Close Create Font Sheet before deleting its opening artboard.")), "{status}");
|
||||
assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 2, "the opening artboard is kept");
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, before);
|
||||
assert!(panel.app().session.artboard_deletion_guard.is_none());
|
||||
panel.click("Cancel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_sheet_allows_deleting_another_artboard() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 3})).unwrap();
|
||||
app.sync_views();
|
||||
let opening = app.session.active().unwrap().doc.artboards[1].id;
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
panel.app().run("artboard.delete", json!({"index": 0})).unwrap();
|
||||
assert_eq!(panel.app().session.active().unwrap().doc.artboards[0].id, opening);
|
||||
assert!(panel.app().run("artboard.delete", json!({"index": 0})).is_err(), "the protection follows the artboard ID");
|
||||
let before = panel.app().session.active().unwrap().doc.clone();
|
||||
panel.click("Cancel");
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_addon_uses_the_current_artboard_and_survives_deleting_its_opening_artboard() {
|
||||
use crate::addons::dialogs::tests as host;
|
||||
|
||||
for commit in [false, true] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.sync_views();
|
||||
let current = app.session.active().unwrap().doc.artboards[0].id;
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
let command = "addon.arrange.randomizeOpacity";
|
||||
crate::menus::invoke(&mut panel.app(), command, json!({}));
|
||||
panel.frame();
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
panel.app().view_mut().unwrap().artboard = 0;
|
||||
crate::io::remember_active_artboard(&mut panel.app());
|
||||
let active = crate::addons::dialogs::with_opening_artboard(&mut panel.app(), command, |app| app.session.active().unwrap().active_artboard);
|
||||
assert_eq!(active, Some(current), "the other dialog does not pin the opening artboard");
|
||||
panel.app().run("artboard.delete", json!({"index": 1})).unwrap();
|
||||
let before = panel.app().session.active().unwrap().doc.clone();
|
||||
let undo = panel.app().session.active().unwrap().history.undo.len();
|
||||
let dialog = host::dialog_id(&panel.app());
|
||||
host::set(&panel.app(), dialog, "min", json!(37));
|
||||
host::set(&panel.app(), dialog, "max", json!(37));
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert!(panel.app().session.in_interaction());
|
||||
assert!((panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().opacity - 0.37).abs() < 1e-6);
|
||||
panel.click(if commit { "OK" } else { "Cancel" });
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), 1);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + usize::from(commit));
|
||||
if commit {
|
||||
assert!((panel.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().opacity - 0.37).abs() < 1e-6);
|
||||
} else {
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_sheet_frames_restore_the_active_artboard_after_preview_and_commit() {
|
||||
for commit in [false, true] {
|
||||
for preview_at_close in [false, true] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
|
||||
app.sync_views();
|
||||
let current = app.session.active().unwrap().doc.artboards[0].id;
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
panel.click_role("Font Names Containing", Role::TEXT_INPUT);
|
||||
panel.type_text("Source Serif 4");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
panel.app().view_mut().unwrap().artboard = 0;
|
||||
crate::io::remember_active_artboard(&mut panel.app());
|
||||
for _ in 0..2 {
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "Preview off preserves the active artboard");
|
||||
}
|
||||
for preview in [true, false, true, false] {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "toggling Preview preserves the active artboard");
|
||||
for _ in 0..2 {
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "idle frames preserve the active artboard");
|
||||
}
|
||||
assert_eq!(panel.app().session.in_interaction(), preview);
|
||||
if preview {
|
||||
assert_on_artboard(&panel.app(), 1, "Preview uses the opening artboard");
|
||||
}
|
||||
}
|
||||
if preview_at_close {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current));
|
||||
}
|
||||
panel.click(if commit { "OK" } else { "Cancel" });
|
||||
assert_eq!(panel.app().session.active().unwrap().active_artboard, Some(current), "closing the dialog preserves the active artboard");
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
if commit {
|
||||
assert_on_artboard(&panel.app(), 1, "OK uses the opening artboard");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_standalone_font_sheet_uses_the_current_artboard_with_its_dialog_open() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
|
||||
app.sync_views();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
panel.app().view_mut().unwrap().artboard = 1;
|
||||
let (request, _) = craft::automation::ControlRequest::new(
|
||||
"engine.execute",
|
||||
json!({"command": super::COMMAND, "params": {"families": ["Inter"], "labels": false}}),
|
||||
);
|
||||
let craft::automation::Reply::Done(answer) = crate::control::handle(&mut panel.app(), &egui::Context::default(), &request) else {
|
||||
panic!("the font sheet command did not finish");
|
||||
};
|
||||
assert_eq!(answer["ok"], true, "{answer}");
|
||||
assert_on_artboard(&panel.app(), 1, "a standalone command while Preview is off");
|
||||
panel.click("Cancel");
|
||||
assert_on_artboard(&panel.app(), 1, "Cancel keeps the standalone sheet");
|
||||
}
|
||||
|
||||
/// The sheet stays on its opening artboard when a preview removes the page shown in the view.
|
||||
#[test]
|
||||
fn going_to_a_page_the_font_sheet_preview_added_keeps_its_start() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400, "artboards": 2})).unwrap();
|
||||
app.sync_views();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
let original_artboards = panel.app().session.active().unwrap().doc.artboards.len();
|
||||
// Each page holds one 100 pt entry.
|
||||
let edits = [("Font Names Containing", Role::TEXT_INPUT, "Source S"), ("Size", Role::SPIN_BUTTON, "100"), ("Columns", Role::SPIN_BUTTON, "1")];
|
||||
for (label, role, input) in edits {
|
||||
panel.click_role(label, role);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(input);
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
}
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert!(panel.app().session.active().unwrap().doc.artboards.len() > original_artboards, "the preview adds a page");
|
||||
panel.app().view_mut().unwrap().artboard = original_artboards;
|
||||
panel.frame();
|
||||
let first_on_opening_artboard = |panel: &Panel| {
|
||||
let app = panel.app();
|
||||
let [.., x, _] = sheet(&app)[0].xf.as_coeffs();
|
||||
let board = app.session.active().unwrap().doc.artboards[0].rect;
|
||||
assert!(x >= board.x0 && x <= board.x1, "the first entry stays on the opening artboard: {x}, {board:?}");
|
||||
};
|
||||
first_on_opening_artboard(&panel);
|
||||
panel.click_role("Add Artboards When Full", Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().doc.artboards.len(), original_artboards);
|
||||
panel.app().sync_views();
|
||||
assert_eq!(panel.app().view().unwrap().artboard, original_artboards - 1, "the view clamps to the last original artboard");
|
||||
panel.frame();
|
||||
first_on_opening_artboard(&panel);
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
panel.frame();
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
panel.click("OK");
|
||||
first_on_opening_artboard(&panel);
|
||||
}
|
||||
|
||||
/// An empty filter sends none, so the sheet sets every family; a filter is sent trimmed.
|
||||
#[test]
|
||||
fn params_sends_a_filter_only_when_one_is_typed() {
|
||||
let mut fields = DialogFields::from_pairs([("text", FieldValue::Text("Abc".into())), ("filter", FieldValue::Text(" ".into()))]);
|
||||
let p = super::params(&fields);
|
||||
assert!(p.get("filter").is_none(), "{p}");
|
||||
assert_eq!((&p["text"], &p["columns"], &p["labels"], &p["newArtboards"]), (&json!("Abc"), &json!(2), &json!(true), &json!(true)));
|
||||
fields.set("filter", FieldValue::Text(" Inter ".into()));
|
||||
assert_eq!(super::params(&fields)["filter"], json!("Inter"));
|
||||
}
|
||||
@@ -19,7 +19,7 @@ const SEEDS: u64 = 1_000_000;
|
||||
const MAX_VALUE: f64 = 1e12;
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None };
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The command's parameters from the dialog's fields.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
|
||||
@@ -88,7 +88,10 @@ impl VectorcraftApp {
|
||||
let touch_workspace = self.session.prefs.touch_workspace;
|
||||
// A `prefs.reset` that ran straight on the session applies before this command can switch workspaces.
|
||||
crate::prefs_dialog::apply_prefs_resets(self);
|
||||
let guard = crate::addons::dialogs::artboard_deletion_guard(self);
|
||||
let previous_guard = std::mem::replace(&mut self.session.artboard_deletion_guard, guard);
|
||||
let result = self.run_now(id, params);
|
||||
self.session.artboard_deletion_guard = previous_guard;
|
||||
crate::prefs_dialog::apply_prefs_resets(self);
|
||||
if id == "prefs.import" && result.is_ok() {
|
||||
crate::prefs_dialog::imported(self, touch_workspace);
|
||||
@@ -162,7 +165,9 @@ impl VectorcraftApp {
|
||||
self.wait_for_tool_edit(id);
|
||||
// A `.ai` file a command writes (a save, an export, a timestamped copy, a batch's save) names
|
||||
// the view's active artboard.
|
||||
io::remember_active_artboard(self);
|
||||
if !self.addon_dialogs.using_opening_artboard {
|
||||
io::remember_active_artboard(self);
|
||||
}
|
||||
let artboards = self.artboard_tool_state();
|
||||
if let Some(r) = menus::run_ui_command(self, id, ¶ms) {
|
||||
self.ui.recording_base = None;
|
||||
|
||||
@@ -11,7 +11,8 @@ pub(crate) fn navigation(p: &Prefs) -> NavigationOptions {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.wheel = if p.zoom_with_mouse_wheel { WheelScheme::Zoom } else { WheelScheme::Scroll };
|
||||
options.animated_zoom = crate::canvas::animated_zoom(p);
|
||||
options.scrubby_zoom = crate::canvas::animated_zoom(p);
|
||||
options.eased_wheel_zoom = p.zoom_with_mouse_wheel && options.animated_zoom;
|
||||
options.scrubby_zoom = options.animated_zoom;
|
||||
options.trackpad_rotate = p.trackpad_rotate_view;
|
||||
options.touch_gestures = p.touch_gestures;
|
||||
options.overscroll = true;
|
||||
|
||||
@@ -257,6 +257,6 @@ fn ruler_labels_carry_the_sign_and_the_steps_decimals() {
|
||||
(1.0, 0.0625, "1"),
|
||||
(1.1875, 0.0625, "1.1875"),
|
||||
] {
|
||||
assert_eq!(x.tick_label(&units, value, step), want, "the tick at {value} of a {step} step");
|
||||
assert_eq!(x.tick_label(&units, value, step), crate::tests::regional_text(want), "the tick at {value} of a {step} step");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7039,6 +7039,33 @@ fn a_wheel_pan_under_a_resting_pointer_keeps_the_tool_cursor() {
|
||||
assert!(asks() > before, "once the view is still, the tool gives the cursor again");
|
||||
}
|
||||
|
||||
/// Artboards made with no spacing touch, and the canvas paints every artboard's drop shadow before any artboard's
|
||||
/// paper, so the lower artboard's shadow does not darken the upper one along the shared edge.
|
||||
#[test]
|
||||
fn touching_artboards_cast_no_shadow_on_each_other() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200, "artboards": 2, "artboardLayout": {"layout": "column", "spacing": 0}})).unwrap();
|
||||
let boards: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|ab| ab.rect).collect();
|
||||
assert_eq!(boards[0].y1, boards[1].y0, "the artboards touch");
|
||||
app.ui.task_bar = false;
|
||||
app.ui.view.rulers = false;
|
||||
app.canvas.worker_started = true;
|
||||
let ctx = crate::testing::ui_context();
|
||||
let _ = shapes(&mut app, &ctx);
|
||||
let view = app.view_mut().unwrap();
|
||||
(view.zoom, view.center) = (1.0, Point::new(100.0, 200.0));
|
||||
let all = shapes(&mut app, &ctx);
|
||||
let papers: Vec<usize> = all
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, s)| matches!(s, Shape::Mesh(m) if m.texture_id == egui::TextureId::default() && m.vertices.first().is_some_and(|v| v.color == Color32::WHITE)))
|
||||
.map(|(at, _)| at)
|
||||
.collect();
|
||||
let shadows: Vec<usize> = all.iter().enumerate().filter(|(_, s)| matches!(s, Shape::Rect(r) if r.blur_width > 0.0)).map(|(at, _)| at).collect();
|
||||
assert_eq!((papers.len(), shadows.len()), (2, 2), "each artboard paints its paper and casts a shadow");
|
||||
assert!(shadows.iter().all(|s| papers.iter().all(|p| s < p)), "every shadow lies under both papers: shadows {shadows:?}, papers {papers:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_worker_s_frame_reaches_its_texture_image_in_the_buffer_it_was_rendered_into() {
|
||||
let (doc, key) = pan_doc();
|
||||
|
||||
@@ -825,7 +825,7 @@ mod tests {
|
||||
assert_eq!(pending.size_choice, Some(ArtboardSizeChoice::Orientation(true)));
|
||||
panel.click_role(label, Role::SPIN_BUTTON);
|
||||
panel.key(Key::A, Modifiers::COMMAND);
|
||||
panel.type_text(typed);
|
||||
panel.type_text(&crate::tests::regional_text(typed));
|
||||
assert_eq!(actual_value(&panel), pending, "typing must not discard the pending orientation or reference-point policy");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
assert!(!is_open(&panel.app()), "Escape discards the modal for {label}");
|
||||
@@ -875,7 +875,7 @@ mod tests {
|
||||
panel.frame();
|
||||
panel.click_role(label, Role::SPIN_BUTTON);
|
||||
panel.key(Key::A, Modifiers::COMMAND);
|
||||
panel.type_text(typed);
|
||||
panel.type_text(&crate::tests::regional_text(typed));
|
||||
if blur {
|
||||
panel.key(Key::Tab, Modifiers::NONE);
|
||||
}
|
||||
|
||||
@@ -51,8 +51,9 @@ pub(crate) enum Target {
|
||||
/// A colour row `key` of the open dialog `parent`.
|
||||
Answer { parent: DialogId, key: String },
|
||||
/// The answer to a running script's `app.showColorPicker`, which opened it on `color`; `cmyk`:
|
||||
/// the run's active document is in CMYK.
|
||||
Script { color: Color, cmyk: bool },
|
||||
/// the run's active document is in CMYK; `profiles`: the RGB and CMYK profiles that document is
|
||||
/// assigned, which the pick converts through.
|
||||
Script { color: Color, cmyk: bool, profiles: (Option<String>, Option<String>) },
|
||||
}
|
||||
|
||||
impl Target {
|
||||
@@ -242,6 +243,28 @@ fn working_cmyk() -> Option<CmykConverter> {
|
||||
CmykConverter::new(Arc::new(Profile::parse(&bytes).ok()?)).ok()
|
||||
}
|
||||
|
||||
/// The color a script's picker gives for `picked` in the script's document assigned `profiles`
|
||||
/// (`cmyk`: a CMYK document), which separates through that document's CMYK profile. A pick in
|
||||
/// display sRGB (a hex value, a sample, HSB) is that sRGB color in the document's RGB space; RGB
|
||||
/// values typed into the picker are in the active RGB space, and convert from it to the document's
|
||||
/// RGB space when the two differ. CMYK, gray and Lab values stay as they are.
|
||||
fn script_pick(picked: &PickedColor, cmyk: bool, profiles: &(Option<String>, Option<String>)) -> Color {
|
||||
let shown = cms::active();
|
||||
let own = cms::for_document(profiles.0.as_deref(), profiles.1.as_deref());
|
||||
let c = match picked.model.as_ref().map(|v| v.model) {
|
||||
None | Some("hsb") => screen_color::sampled(&own, [picked.color.r, picked.color.g, picked.color.b]),
|
||||
Some(_) => {
|
||||
let c = color_of(picked);
|
||||
if matches!(c, Color::Rgb { .. }) && shown.settings().rgb != own.settings().rgb {
|
||||
shown.convert_into(&own, &c, own.settings().intent)
|
||||
} else {
|
||||
c
|
||||
}
|
||||
}
|
||||
};
|
||||
cms::with_active(own, || in_model(cmyk, c))
|
||||
}
|
||||
|
||||
/// `ui.colorPicker {stroke?, artboard?, color?}`: open the picker for the fill (or stroke) proxy,
|
||||
/// or for artboard `artboard`'s background color, starting from `color`, else the proxy's color
|
||||
/// or the artboard's color (white when it has none).
|
||||
@@ -322,16 +345,17 @@ fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPi
|
||||
}
|
||||
|
||||
/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`:
|
||||
/// the run's own active document is in CMYK, which the session does not show between slices. It
|
||||
/// the run's own active document is in CMYK, which the session does not show between slices;
|
||||
/// `profiles`: the RGB and CMYK profiles that document is assigned, which OK converts the pick through. It
|
||||
/// previews nothing; its OK and Cancel answer the run ([`finish`]).
|
||||
pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool) {
|
||||
pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool, profiles: (Option<String>, Option<String>)) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
// The given colour's own values, so that OK can tell an untouched pick from another model's.
|
||||
// The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given.
|
||||
let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false);
|
||||
let id = dialogs.with(|h| h.open(dialog));
|
||||
app.color_dialogs.pickers.retain(|o| o.id != id);
|
||||
let target = Target::Script { color, cmyk };
|
||||
let target = Target::Script { color, cmyk, profiles };
|
||||
app.color_dialogs.pickers.push(Open {
|
||||
id,
|
||||
target,
|
||||
@@ -503,9 +527,11 @@ fn finish(
|
||||
}
|
||||
}
|
||||
// OK on the colour it opened with, in the model it opened with, gives that colour back.
|
||||
(Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk }) => {
|
||||
// Between slices the window's front document sets the active profiles; the pick converts
|
||||
// through the profiles of the script's document instead.
|
||||
(Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk, profiles }) => {
|
||||
let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given));
|
||||
let picked = if untouched { *given } else { in_model(*cmyk, color_of(&r.picked)) };
|
||||
let picked = if untouched { *given } else { script_pick(&r.picked, *cmyk, profiles) };
|
||||
app.session.script_answer(DialogAnswer::ColorPicker(Some(picked)));
|
||||
}
|
||||
(_, Target::Script { .. }) => {
|
||||
|
||||
@@ -358,7 +358,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
|
||||
/// drawing is converted on a job of its own ([`crate::opening::convert_drawing`]) and its dialog
|
||||
/// opens once that is done ([`converted`]) → true; false when `bytes` aren't a DWG drawing.
|
||||
pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, place: Option<&Value>) -> bool {
|
||||
if !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| !fileio::reads_as_dwg(f.id)) {
|
||||
if !vectorcraft_cad::dwg::DECODES || !vectorcraft_cad::is_dwg(bytes) || fileio::detect(name, bytes).is_none_or(|f| !fileio::reads_as_dwg(f.id)) {
|
||||
return false;
|
||||
}
|
||||
crate::opening::convert_drawing(app, name, bytes.to_vec(), path, place.cloned());
|
||||
@@ -372,7 +372,7 @@ pub fn convert_in_background(app: &mut VectorcraftApp, name: &str, bytes: &[u8],
|
||||
/// converted (true).
|
||||
pub fn convert_place_in_background(app: &mut VectorcraftApp, p: &Value) -> bool {
|
||||
let named = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).map(fileio::extension);
|
||||
if p.get("dxf").is_some() || !named.as_deref().is_some_and(is_dwg_ext) {
|
||||
if !vectorcraft_cad::dwg::DECODES || p.get("dxf").is_some() || !named.as_deref().is_some_and(is_dwg_ext) {
|
||||
return false;
|
||||
}
|
||||
let Some((name, bytes, path)) = place_source(app, p, is_dwg_ext) else { return false };
|
||||
@@ -532,8 +532,14 @@ fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> R
|
||||
if let Some(converted) = &source.converted {
|
||||
app.placing.keep_next = Some(Box::new(converted.held.clone()));
|
||||
}
|
||||
// The drawing placed is the one the dialog showed, not the file as it is on disk now;
|
||||
// its link and the journal keep the path.
|
||||
if let Some(path) = &source.path {
|
||||
app.placing.bytes_next = Some((path.clone(), source.file.clone()));
|
||||
}
|
||||
let r = crate::place::run_for_user(app, &p).map(|_| ());
|
||||
app.placing.keep_next = None;
|
||||
app.placing.bytes_next = None;
|
||||
if let (Some(current), Some(insertion)) = (current, restore) {
|
||||
current.restore_changed(&insertion, app);
|
||||
}
|
||||
@@ -965,6 +971,56 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
/// A DWG drawing placed through its dialog is the drawing the dialog previewed: a file written
|
||||
/// over it on disk while the dialog is open is not placed.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn ok_places_the_drawing_the_dialog_previewed() {
|
||||
fn placed_size(app: &mut VectorcraftApp) -> (f64, f64) {
|
||||
while !app.placing.pending.is_empty() {
|
||||
crate::placing::wait(app);
|
||||
crate::placing::poll(app);
|
||||
}
|
||||
let st = app.session.doc().unwrap();
|
||||
let mut out: Option<vectorcraft_geom::Rect> = None;
|
||||
st.doc.node(st.selection.objects[0]).unwrap().walk(&mut |c| {
|
||||
if let Some(b) = c.path_data().and_then(vectorcraft_geom::PathData::bounds) {
|
||||
out = Some(out.map_or(b, |o| o.union(b)));
|
||||
}
|
||||
});
|
||||
let r = out.unwrap();
|
||||
(r.width(), r.height())
|
||||
}
|
||||
vectorcraft_engine::dwg::allow_in_process();
|
||||
let (_dir, plan) = dwg_file("dxf-import-dwg-previewed");
|
||||
let flatter = String::from_utf8(drawing()).unwrap().replace(" 21\n50\n", " 21\n10\n");
|
||||
crate::opening::tests::with_threads(|| {
|
||||
let mut app = host::app();
|
||||
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
|
||||
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap();
|
||||
finish_conversions(&mut app);
|
||||
host::confirm(&mut app, KIND).unwrap();
|
||||
let previewed = placed_size(&mut app);
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan })).unwrap();
|
||||
finish_conversions(&mut app);
|
||||
assert_eq!(host::fields(&app, KIND)["mode"], "place");
|
||||
std::fs::write(&plan, craft_dwg::dxf_to_dwg_as(flatter.as_bytes(), "AC1018").unwrap()).unwrap();
|
||||
let before = app.session.doc().unwrap().selection.objects.clone();
|
||||
host::confirm(&mut app, KIND).unwrap();
|
||||
let size = placed_size(&mut app);
|
||||
assert_ne!(app.session.doc().unwrap().selection.objects, before, "OK places a new object");
|
||||
assert_eq!(size, previewed, "OK places the drawing the dialog opened on");
|
||||
assert!(app.placing.bytes_next.is_none());
|
||||
// Placed again, the file as it is on disk now is read.
|
||||
let before = app.session.doc().unwrap().selection.objects.clone();
|
||||
crate::place::run_for_user(&mut app, &json!({ "path": plan, "showImportOptions": false })).unwrap();
|
||||
let size = placed_size(&mut app);
|
||||
assert_ne!(app.session.doc().unwrap().selection.objects, before, "the place adds a new object");
|
||||
assert_ne!(size, previewed, "a later place reads the new file");
|
||||
});
|
||||
}
|
||||
|
||||
/// A DWG drawing converted off the UI thread and placed keeps its conversion until the place
|
||||
/// read off the UI thread is done.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
@@ -556,10 +556,24 @@ fn list_templates(app: &mut VectorcraftApp) -> (Vec<(String, String)>, Option<St
|
||||
|
||||
/// Save Metadata Template…: the fields as they are in the dialog, at the path a save pick answered. A name
|
||||
/// typed without `.xmp` takes it, so the templates list shows the file; a file already there under the
|
||||
/// completed name is replaced only after a question.
|
||||
/// completed name is replaced only after a question. In the document portal, which takes only the name
|
||||
/// answered, the save pick opens again with the completed name in the answer's folder.
|
||||
fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Result<(), String> {
|
||||
let picked = picked.to_string_lossy().into_owned();
|
||||
let path = if picked.to_ascii_lowercase().ends_with(&format!(".{XMP_EXT}")) { picked.clone() } else { format!("{picked}.{XMP_EXT}") };
|
||||
if let Some((name, folder)) = crate::io::save::portal_ask_again(app, &picked, &path) {
|
||||
let mut request = template_request(name);
|
||||
if let Some(folder) = folder {
|
||||
request = request.directory(folder);
|
||||
}
|
||||
file_asks::ask(app, request, file_asks::Owner::Free, move |app, picked| {
|
||||
if let Some(path) = picked.first_path() {
|
||||
save_template(app, path, fields)?;
|
||||
}
|
||||
Ok(Value::Null)
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
// The save pick does not ask about the completed name.
|
||||
app.session.execute("file.info.templates", &json!({ "create": true })).map_err(|e| e.to_string())?;
|
||||
let save = {
|
||||
@@ -573,6 +587,11 @@ fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Res
|
||||
save(app).map(|_| ())
|
||||
}
|
||||
|
||||
/// A save pick for a metadata template, suggesting `name`.
|
||||
fn template_request(name: String) -> PickRequest {
|
||||
PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT])
|
||||
}
|
||||
|
||||
/// Save the draft through the browser's file service. Serializing it changes neither drawing nor draft.
|
||||
fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), String> {
|
||||
let title = text_of(&fields, "title");
|
||||
@@ -580,8 +599,7 @@ fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), Strin
|
||||
let name = format!("{stem}.{XMP_EXT}");
|
||||
let result = app.run("file.info.saveTemplate", json!({"fields": fields}))?;
|
||||
let data = result["data"].as_str().ok_or("the metadata template contains no data")?.as_bytes().to_vec();
|
||||
let request = PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]);
|
||||
file_asks::save(app, request, data, file_asks::Owner::Free, |app, picked| {
|
||||
file_asks::save(app, template_request(name), data, file_asks::Owner::Free, |app, picked| {
|
||||
match picked {
|
||||
Picked::Downloaded(name) => app.status(format!("Saved {name}")),
|
||||
Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())),
|
||||
@@ -884,6 +902,32 @@ mod tests {
|
||||
assert!(app.session.active().unwrap().history.undo.is_empty());
|
||||
}
|
||||
|
||||
/// In the document portal, which takes only the name the save pick answered, Save Metadata
|
||||
/// Template… writes nothing under the completed name (`Card` for `Card.xmp`): the save pick opens
|
||||
/// again in the answer's folder suggesting `Card.xmp`, and its answer is written.
|
||||
#[test]
|
||||
fn a_template_save_asks_again_for_a_name_the_document_portal_did_not_grant() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("ui-file-info-portal");
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let picker = crate::tests::picks::scripted(&mut app);
|
||||
app.session.attach_metadata_templates_dir(dir.join("Metadata Templates"));
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let portal = "/run/user/1000/doc/a1b2c3d4";
|
||||
let fields = json!({"author": "Ada"}).as_object().cloned().unwrap_or_default();
|
||||
super::save_template(&mut app, format!("{portal}/Card").into(), fields).unwrap();
|
||||
let requests = picker.requests();
|
||||
let [again] = requests.as_slice() else { panic!("the save pick opens again: {requests:?}") };
|
||||
assert_eq!(again.file_name.as_deref(), Some("Card.xmp"));
|
||||
assert_eq!(again.directory.as_deref(), Some(std::path::Path::new(portal)));
|
||||
assert!(app.ui.status.contains("Card.xmp"), "{}", app.ui.status);
|
||||
let granted = dir.join("Card.xmp");
|
||||
picker.answer_saved(&granted.to_string_lossy(), None);
|
||||
let ctx = app.ui_ctx.clone().unwrap_or_default();
|
||||
crate::tests::picks::poll(&mut app, &ctx);
|
||||
assert!(std::fs::read_to_string(&granted).is_ok_and(|xmp| xmp.contains("Ada")), "the granted name is written");
|
||||
assert_eq!(picker.requests().len(), 1, "a granted name is written without asking again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template");
|
||||
|
||||
@@ -69,6 +69,13 @@ impl DialogFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's bytes, as a place given them reads them ([`vectorcraft_engine::cmd::place::GivenBytes`]).
|
||||
impl AsRef<[u8]> for DialogFile {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Equal by token: a token names one file's bytes, so a dialog's values compare without reading them.
|
||||
impl PartialEq for DialogFile {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
|
||||
@@ -148,7 +148,7 @@ impl MosaicSource {
|
||||
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
|
||||
}
|
||||
if st.history_restores != self.history_restores {
|
||||
return Err(tl!("Reopen Create Object Mosaic after Undo or Redo.").to_owned());
|
||||
return Err(tl!("Reopen Create Object Mosaic after Undo, Redo or a canceled edit.").to_owned());
|
||||
}
|
||||
match selected_image(app) {
|
||||
Some((source, size)) if source == self => Ok(size),
|
||||
|
||||
@@ -75,7 +75,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
|
||||
}
|
||||
if Some(active.history_restores) != opening["historyRestores"].as_u64() {
|
||||
return Err(tl!("Reopen Placement Options after Undo or Redo.").to_owned());
|
||||
return Err(tl!("Reopen Placement Options after Undo, Redo or a canceled edit.").to_owned());
|
||||
}
|
||||
let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]);
|
||||
let params = json!({ "ids": opening["ids"], "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) });
|
||||
|
||||
@@ -93,8 +93,10 @@ pub(crate) fn open_with(app: &mut VectorcraftApp, f: &Format, mut params: Value,
|
||||
let initial = fields_of(&raster_rows(id, false, size, &DialogFields::new()), &map);
|
||||
let dialog = HostedParamDialog::new(&ctx, key.clone(), initial, move |fields| {
|
||||
normalize_colors(fields);
|
||||
if id == "bmp" {
|
||||
tiff_bmp_tga::normalize_bmp(fields);
|
||||
match id {
|
||||
"bmp" => tiff_bmp_tga::normalize_bmp(fields),
|
||||
"tga" => tiff_bmp_tga::normalize_tga(fields),
|
||||
_ => {}
|
||||
}
|
||||
ParamDialog::new(key.clone(), heading(label), raster_rows(id, false, size, fields)).values(Bind::bound(fields)).ok_label(tl!("Export").into())
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::Selection;
|
||||
use vectorcraft_doc::{Document, Selection};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
@@ -13,15 +13,22 @@ use crate::VectorcraftApp;
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct LivePreview {
|
||||
previewed: Option<(String, Value)>,
|
||||
/// The last preview ran without an error, so its result is on show.
|
||||
shown: bool,
|
||||
/// The document the last preview ran on. A change to it or the owner's selection snapshot
|
||||
/// reruns the preview, including one that failed.
|
||||
snapshot: Weak<Document>,
|
||||
owner: Option<Owner>,
|
||||
}
|
||||
|
||||
/// The interaction a preview ran in: its document's `uid` and `reverts`, and the selection snapshot the interaction
|
||||
/// began with, which no other interaction shares.
|
||||
/// began with, which no other interaction shares. A marked interaction ([`LivePreview::keep_outside_edits`]) is
|
||||
/// known by its mark instead, since a command from outside the dialog can give it a new selection.
|
||||
#[derive(Clone)]
|
||||
struct Owner {
|
||||
document: (u64, u64),
|
||||
selection: Weak<Selection>,
|
||||
marked: bool,
|
||||
}
|
||||
|
||||
impl LivePreview {
|
||||
@@ -30,7 +37,9 @@ impl LivePreview {
|
||||
let Some(owner) = &self.owner else { return false };
|
||||
app.session.active().is_some_and(|state| {
|
||||
(state.uid, state.reverts) == owner.document
|
||||
&& state.interaction.as_ref().is_some_and(|interaction| owner.selection.as_ptr() == Arc::as_ptr(&interaction.selection))
|
||||
&& state.interaction.as_ref().is_some_and(|interaction| {
|
||||
owner.selection.as_ptr() == Arc::as_ptr(&interaction.selection) || (owner.marked && interaction.dialog)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -43,8 +52,9 @@ impl LivePreview {
|
||||
}
|
||||
|
||||
/// While `on`, runs `cmd` with `params` on the interaction's snapshot whenever they differ from the last preview
|
||||
/// or its interaction has ended; `label` names the undo step. Returns the command's answer when this call ran a
|
||||
/// preview, and `None` when nothing ran: the same values again (a pass reruns nothing), a preview that could not
|
||||
/// or its interaction has ended or changed its document or selection snapshot; `label` names the undo step.
|
||||
/// Returns the command's answer when this call ran a preview, and `None` when nothing ran:
|
||||
/// the same values and snapshots again, a preview that could not
|
||||
/// begin, another edit in progress, or `on` off, which rolls a shown preview back. Typing in progress is kept as
|
||||
/// its own step first. A refusal's text is written for the user, without the command's id.
|
||||
pub(crate) fn run(&mut self, app: &mut VectorcraftApp, on: bool, label: &str, cmd: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
@@ -56,8 +66,14 @@ impl LivePreview {
|
||||
self.owner = None;
|
||||
return None;
|
||||
}
|
||||
// A command from outside the dialog took a shown preview off its interaction: it runs again.
|
||||
let taken_off = app.session.active().and_then(|state| state.interaction.as_ref()).is_some_and(|it| {
|
||||
(self.shown && it.preview.is_none())
|
||||
|| self.snapshot.as_ptr() != Arc::as_ptr(&it.doc)
|
||||
|| self.owner.as_ref().is_some_and(|owner| owner.selection.as_ptr() != Arc::as_ptr(&it.selection))
|
||||
});
|
||||
let same = self.previewed.as_ref().is_some_and(|(c, p)| c == cmd && p == params);
|
||||
if same {
|
||||
if same && !taken_off {
|
||||
return None;
|
||||
}
|
||||
// Another dialog's, a panel's or a tool's edit in progress gets no preview of this one.
|
||||
@@ -76,7 +92,7 @@ impl LivePreview {
|
||||
app.status(e);
|
||||
return None;
|
||||
}
|
||||
let answer = match app.session.preview(cmd, params) {
|
||||
let answer = match crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.session.preview(cmd, params)) {
|
||||
Ok(v) => Ok(v),
|
||||
Err(e) => {
|
||||
app.status(e.to_string());
|
||||
@@ -87,9 +103,11 @@ impl LivePreview {
|
||||
}
|
||||
};
|
||||
self.previewed = Some((cmd.to_string(), params.clone()));
|
||||
self.shown = answer.is_ok();
|
||||
self.owner = app.session.active().and_then(|state| {
|
||||
let interaction = state.interaction.as_ref()?;
|
||||
Some(Owner { document: (state.uid, state.reverts), selection: Arc::downgrade(&interaction.selection) })
|
||||
self.snapshot = Arc::downgrade(&interaction.doc);
|
||||
Some(Owner { document: (state.uid, state.reverts), selection: Arc::downgrade(&interaction.selection), marked: interaction.dialog })
|
||||
});
|
||||
Some(answer)
|
||||
}
|
||||
@@ -105,9 +123,9 @@ impl LivePreview {
|
||||
if app.session.in_interaction() {
|
||||
return Err(tl!("Finish the active edit first.").to_owned());
|
||||
}
|
||||
return app.run(cmd, params);
|
||||
return crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.run(cmd, params));
|
||||
}
|
||||
let result = app.session.preview(cmd, ¶ms).and_then(|answer| {
|
||||
let result = crate::addons::dialogs::with_opening_artboard(app, cmd, |app| app.session.preview(cmd, ¶ms)).and_then(|answer| {
|
||||
app.session.commit_interaction()?;
|
||||
Ok(answer)
|
||||
});
|
||||
@@ -131,6 +149,18 @@ impl LivePreview {
|
||||
Self::default().commit(app, cmd, params)
|
||||
}
|
||||
|
||||
/// Has a command from outside the dialog (a panel's Delete) run as an undo step of its own while this preview
|
||||
/// shows, so that the next preview, OK and Cancel keep its edit.
|
||||
pub(crate) fn keep_outside_edits(&mut self, app: &mut VectorcraftApp) {
|
||||
if self.owns(app)
|
||||
&& let Some(interaction) = app.session.active_mut().and_then(|state| state.interaction.as_mut())
|
||||
&& let Some(owner) = &mut self.owner
|
||||
{
|
||||
interaction.dialog = true;
|
||||
owner.marked = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel: rolls a shown preview back, and leaves any other edit in progress as it is.
|
||||
pub(crate) fn cancel(self, app: &mut VectorcraftApp) {
|
||||
if self.previewed.is_some() && self.owns(app) {
|
||||
|
||||
@@ -1222,6 +1222,7 @@ mod tests {
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
profiles: (None, None),
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
// A script's own confirm with the same text takes Yes.
|
||||
|
||||
@@ -381,16 +381,22 @@ fn two_pages(editing_data: bool, password: Option<&str>) -> Vec<u8> {
|
||||
|
||||
/// Two 100 pt pages and, on the first, editing data with two artboards to match and a layer of its
|
||||
/// own, which draws the square the first page draws.
|
||||
fn two_pages_with_a_layer_in_the_editing_data(layer: &str) -> Vec<u8> {
|
||||
fn two_pages_with_a_layer_in_the_editing_data(layer: &str, with_trim_box: bool) -> Vec<u8> {
|
||||
let point = |x: i32, y: i32, n: u8| format!("%_{x} {y} /RealPointRelToROrigin\n%_ (PositionPoint{n}) ,\n");
|
||||
let board = |top: i32| format!("%_/Dictionary :\n{}{}%_; ,\n", point(0, top, 1), point(100, top - 100, 2));
|
||||
let boards = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n", board(100), board(-50));
|
||||
let art = format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 10.0, 30.0, 30.0));
|
||||
let data = ai::editing_data(100.0, 100.0, &format!("{boards}{}", ai::layer(layer, &art)));
|
||||
let mut first = PdfPage::new(100.0, 100.0, "0 0 0 1 k 10 10 20 20 re f");
|
||||
let page = |content| {
|
||||
let edge = if with_trim_box { 120.0 } else { 100.0 };
|
||||
let mut page = PdfPage::new(edge, edge, content);
|
||||
page.trim = with_trim_box.then_some([10.0, 10.0, 110.0, 110.0]);
|
||||
page
|
||||
};
|
||||
let mut first = page("0 0 0 1 k 10 10 20 20 re f");
|
||||
first.entries = format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(2));
|
||||
let stream = format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len());
|
||||
pdf_with(&[first, PdfPage::new(100.0, 100.0, "")], &[&stream], None)
|
||||
pdf_with(&[first, page("")], &[&stream], None)
|
||||
}
|
||||
|
||||
/// #6135: the editing data of a `.ai` holds every artboard, so opening one asks nothing, opens
|
||||
@@ -398,7 +404,7 @@ fn two_pages_with_a_layer_in_the_editing_data(layer: &str) -> Vec<u8> {
|
||||
#[test]
|
||||
fn opening_an_ai_with_editing_data_reads_it_without_asking() {
|
||||
let mut app = app();
|
||||
let bytes = two_pages_with_a_layer_in_the_editing_data("Only in the editing data");
|
||||
let bytes = two_pages_with_a_layer_in_the_editing_data("Only in the editing data", false);
|
||||
io::open_bytes(&mut app, "two.ai", &bytes, Some("/tmp/two.ai".into())).unwrap();
|
||||
assert!(!is_open(&app), "no Import PDF dialog");
|
||||
assert_eq!(app.session.documents().len(), 2);
|
||||
@@ -435,6 +441,17 @@ fn opening_a_pdf_with_editing_data_keeps_its_trim_boxes_unless_a_box_is_picked()
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(artboard_widths(&app), [100.0, 200.0], "an explicit crop box");
|
||||
|
||||
let bytes = two_pages_with_a_layer_in_the_editing_data("An editable layer", true);
|
||||
let mut app = self::app();
|
||||
assert!(import_pdf::offer(&mut app, "readable.pdf", &bytes, None, None));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(artboard_widths(&app), [100.0, 100.0], "the trim boxes match the artboards in the editing data");
|
||||
let mut app = self::app();
|
||||
assert!(import_pdf::offer(&mut app, "readable.pdf", &bytes, None, None));
|
||||
set(&mut app, "cropTo", json!("crop"));
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(artboard_widths(&app), [120.0, 120.0], "the crop boxes override the artboards in the editing data");
|
||||
|
||||
let mut app = self::app();
|
||||
assert!(import_pdf::offer(&mut app, "locked.pdf", &trimmed(Some("pw")), None, None));
|
||||
set(&mut app, "password", json!("pw"));
|
||||
|
||||
@@ -39,9 +39,32 @@ fn bmp_options_keep_their_choices_writable() {
|
||||
assert_eq!((&bmp[..2], bmp[28], bmp[30]), (&b"BM"[..], 8, 1), "8-bit RLE8");
|
||||
}
|
||||
|
||||
/// Targa at 24 bits is flattened on white; its other depths keep transparency.
|
||||
/// Targa at 24 bits, and grayscale at 8, is flattened on white; 16 and 32 bits keep transparency.
|
||||
#[test]
|
||||
fn targa_keeps_transparency_above_24_bits() {
|
||||
fn targa_keeps_transparency_at_16_and_32_bits() {
|
||||
assert!(!tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("depth", "24")])));
|
||||
assert!(tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("depth", "32")])));
|
||||
assert!(!tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("colorModel", "gray"), ("depth", "8")])));
|
||||
assert!(tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("colorModel", "gray"), ("depth", "16")])));
|
||||
}
|
||||
|
||||
/// Targa Options' Color Model writes a grayscale file, and a change of model moves the depth to
|
||||
/// one that model has.
|
||||
#[test]
|
||||
fn targa_color_model_reaches_the_file() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "tga"})).unwrap();
|
||||
confirm(&mut app);
|
||||
assert_eq!(kind(&app).as_deref(), Some("tgaOptions"));
|
||||
let f = fields(&app);
|
||||
assert_eq!((f.text("colorModel"), f.text("depth")), (Some("rgb"), Some("24")));
|
||||
frame(&mut app);
|
||||
// Grayscale has no 24 bits: the depth moves to 8.
|
||||
set(&mut app, "colorModel", json!("gray"));
|
||||
frame(&mut app);
|
||||
assert_eq!(fields(&app).text("depth"), Some("8"));
|
||||
confirm(&mut app);
|
||||
let (path, tga) = written.borrow()[0].clone();
|
||||
assert_eq!(path, "/out/Untitled-1.tga");
|
||||
assert_eq!((tga[2], tga[16]), (3, 8), "8-bit grayscale");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The options of TIFF (colour model, byte order, LZW, profile), BMP (colour model, layout, depth,
|
||||
//! palette, RLE, row order) and Targa (depth), after the raster export rows they share with PNG
|
||||
//! palette, RLE, row order) and Targa (colour model, depth), after the raster export rows they share with PNG
|
||||
//! Options ([`super::png_options`]): the `tiffOptions`, `bmpOptions` and `tgaOptions` dialogs.
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, Param};
|
||||
@@ -12,14 +12,15 @@ use vectorcraft_render::encode::tiff::{ByteOrder, TiffOptions};
|
||||
|
||||
use super::png_options::{check, choice};
|
||||
|
||||
/// BMP colour models and layouts: param values and labels.
|
||||
/// BMP and Targa colour models and BMP layouts: param values and labels.
|
||||
const BMP_MODELS: [&str; 2] = ["rgb", "gray"];
|
||||
const BMP_MODEL_LABELS: [&str; 2] = ["RGB", "Grayscale"];
|
||||
const LAYOUTS: [&str; 2] = ["windows", "os2"];
|
||||
const LAYOUT_LABELS: [&str; 2] = ["Windows", "OS/2"];
|
||||
/// Labels of [`bmp::DEPTHS`] and [`tga::DEPTHS`].
|
||||
/// Labels of [`bmp::DEPTHS`], [`tga::DEPTHS`] and [`tga::GRAY_DEPTHS`].
|
||||
const BMP_DEPTH_LABELS: [&str; 6] = ["1 bit", "4 bit", "8 bit", "16 bit", "24 bit", "32 bit"];
|
||||
const TGA_DEPTH_LABELS: [&str; 3] = ["16 bits/pixel", "24 bits/pixel", "32 bits/pixel"];
|
||||
const TGA_GRAY_DEPTH_LABELS: [&str; 2] = ["8 bits/pixel", "16 bits/pixel"];
|
||||
|
||||
/// The options format `id` starts with (`cmyk`: a CMYK document exports CMYK TIFFs).
|
||||
pub(super) fn defaults(id: &str, cmyk: bool, o: &mut Map<String, Value>) {
|
||||
@@ -47,7 +48,8 @@ pub(super) fn defaults(id: &str, cmyk: bool, o: &mut Map<String, Value>) {
|
||||
]);
|
||||
}
|
||||
"tga" => {
|
||||
o.insert("depth".into(), json!(TgaOptions::default().depth.to_string()));
|
||||
let t = TgaOptions::default();
|
||||
o.extend([("colorModel".into(), json!(BMP_MODELS[usize::from(t.gray)])), ("depth".into(), json!(t.depth.to_string()))]);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -64,7 +66,7 @@ pub(super) fn keeps_alpha(id: &str, f: &DialogFields) -> bool {
|
||||
"jpg" => false,
|
||||
"tiff" => ColorModel::from_id(f.text("colorModel").unwrap_or_default()).unwrap_or_default() == ColorModel::Rgb,
|
||||
"bmp" => depth(f) == 32.0,
|
||||
"tga" => depth(f) != 24.0,
|
||||
"tga" => matches!(depth(f) as u8, 16 | 32),
|
||||
// A flat PSD is flattened; its layers keep transparency.
|
||||
"psd" => f.text("layers") == Some("true"),
|
||||
_ => true,
|
||||
@@ -81,11 +83,33 @@ pub(super) fn params(id: &str, fields: &DialogFields) -> Vec<Param> {
|
||||
check("embedIcc", tl!("Embed ICC Profile"), true),
|
||||
],
|
||||
"bmp" => bmp_params(fields),
|
||||
"tga" => vec![choice("depth", tl!("Depth:"), &tga::DEPTHS.map(|d| d.to_string()), &TGA_DEPTH_LABELS)],
|
||||
"tga" => {
|
||||
let depth = if tga_gray(fields) {
|
||||
choice("depth", tl!("Depth:"), &tga::GRAY_DEPTHS.map(|d| d.to_string()), &TGA_GRAY_DEPTH_LABELS)
|
||||
} else {
|
||||
choice("depth", tl!("Depth:"), &tga::DEPTHS.map(|d| d.to_string()), &TGA_DEPTH_LABELS)
|
||||
};
|
||||
vec![choice("colorModel", tl!("Color Model:"), &BMP_MODELS, &BMP_MODEL_LABELS), depth]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the Targa dialog hold the grayscale colour model?
|
||||
fn tga_gray(f: &DialogFields) -> bool {
|
||||
f.text("colorModel") == Some(BMP_MODELS[1])
|
||||
}
|
||||
|
||||
/// Keep the Targa depth one the colour model has: a change of model starts the depth at that
|
||||
/// model's default (24 bits for RGB, 8 for grayscale).
|
||||
pub(super) fn normalize_tga(f: &mut DialogFields) {
|
||||
let gray = tga_gray(f);
|
||||
let bits = depth(f);
|
||||
if !TgaOptions::depths(gray).iter().any(|d| f64::from(*d) == bits) {
|
||||
f.set("depth", TgaOptions::default_depth(gray).to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn bmp_params(fields: &DialogFields) -> Vec<Param> {
|
||||
let os2 = fields.text("fileFormat") == Some(LAYOUTS[1]);
|
||||
let depths = bmp::DEPTHS.map(|d| d.to_string());
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user