Merge main into feat/ai-editing-data

This commit is contained in:
dotCooCoo committed 2026-11-03 19:47:02 -08:00
commit 46bb91275d
126 files changed
+4564 -803

No files matched your search

+3 -2
View File
@@ -56,8 +56,9 @@ pollster = "1"
# `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down.
# Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the
# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which
# src/caps_lock.rs uses to read whether Caps Lock is on.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`,
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# The renderer's worker count follows those cores (src/windows_cores.rs).
vectorcraft-render = { workspace = true }
+3 -1
View File
@@ -334,7 +334,9 @@ fn tcp_connection_is_closed_after_junk() {
});
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(WAIT)).unwrap();
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
// Nothing after the junk line: on Windows, closing a socket with unread input resets the
// connection, and the reset can discard the reply before the client reads it.
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap();
let mut text = String::new();
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
server.join().unwrap();
+61 -28
View File
@@ -461,24 +461,13 @@ pub(crate) fn windows_candidates(
}
/// The paths PhotoCraft's installer registers under App Paths, for the current user and then for
/// everyone (`reg query`, so no extra dependency; a hidden console window).
/// everyone.
#[cfg(windows)]
fn registered_photocraft() -> Vec<std::path::PathBuf> {
use std::os::windows::process::CommandExt as _;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
// reg.exe by its full path, so nothing named `reg` in the app's folder or on PATH runs instead.
let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into());
["HKCU", "HKLM"]
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
[HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]
.into_iter()
.filter_map(|hive| {
let key = format!(r"{hive}\Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe");
let out = std::process::Command::new(root.join("System32").join("reg.exe"))
.args(["query", &key, "/ve"])
.creation_flags(CREATE_NO_WINDOW)
.output()
.ok()?;
registered_path(&String::from_utf8_lossy(&out.stdout))
})
.filter_map(|hive| registry_default_path(hive, r"Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe"))
.collect()
}
@@ -487,11 +476,35 @@ fn registered_photocraft() -> Vec<std::path::PathBuf> {
Vec::new()
}
/// The path in `reg query … /ve` output like
/// ` (Default) REG_SZ C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`.
/// The default `REG_SZ` value of `subkey` under `hive` as a path ([`registered_path`]), or `None`
/// when the key or the value is missing. The value is read as UTF-16, so a folder name in any
/// script comes back as stored.
#[cfg(windows)]
#[allow(unsafe_code)]
fn registry_default_path(hive: windows::Win32::System::Registry::HKEY, subkey: &str) -> Option<std::path::PathBuf> {
use windows::Win32::System::Registry::{RRF_RT_REG_SZ, RegGetValueW};
use windows::core::PCWSTR;
let subkey: Vec<u16> = subkey.encode_utf16().chain([0]).collect();
let mut size = 0u32;
// SAFETY: `subkey` is a NUL-terminated UTF-16 string that outlives the call, a null value name
// reads the default value, and with no buffer the call only writes the value's size to `size`.
unsafe { RegGetValueW(hive, PCWSTR(subkey.as_ptr()), PCWSTR::null(), RRF_RT_REG_SZ, None, None, Some(&mut size)) }.ok().ok()?;
let mut value = vec![0u16; (size as usize).div_ceil(2)];
let mut size = u32::try_from(value.len() * 2).ok()?;
// SAFETY: as above, and `value` holds the `size` bytes the call may write.
unsafe { RegGetValueW(hive, PCWSTR(subkey.as_ptr()), PCWSTR::null(), RRF_RT_REG_SZ, None, Some(value.as_mut_ptr().cast()), Some(&mut size)) }
.ok()
.ok()?;
registered_path(&value)
}
/// The path in a registry string value read as UTF-16, up to its first NUL, without surrounding
/// spaces or quotes, like `C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`.
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
pub(crate) fn registered_path(text: &str) -> Option<std::path::PathBuf> {
text.lines().find_map(|l| l.split_once("REG_SZ")).map(|(_, v)| v.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from)
pub(crate) fn registered_path(value: &[u16]) -> Option<std::path::PathBuf> {
let end = value.iter().position(|&c| c == 0).unwrap_or(value.len());
let text = String::from_utf16(&value[..end]).ok()?;
Some(text.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from)
}
/// Is `app` an application Edit Original may start: an `.app` bundle on macOS, an `.exe` on
@@ -616,17 +629,37 @@ mod open_with_tests {
);
}
/// The registered path is read from `reg query … /ve` output, spaces and quotes included;
/// no value, no path.
/// The registered path is read from the UTF-16 value up to its NUL, spaces, quotes and
/// characters outside ASCII included; an empty value or one that is not UTF-16 gives no path.
#[test]
fn the_registered_path_is_read_from_reg_query() {
let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\photocraft.exe\r\n (Default) REG_SZ C:\\Program Files\\ArtCraft\\PhotoCraft\\photocraft.exe\r\n";
assert_eq!(registered_path(out), Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe")));
fn the_registered_path_is_read_from_the_utf16_value() {
let wide = |s: &str| s.encode_utf16().chain([0, 0]).collect::<Vec<u16>>();
assert_eq!(
registered_path(" (Standard) REG_SZ \"C:\\A B\\photocraft.exe\""),
Some(std::path::PathBuf::from(r"C:\A B\photocraft.exe"))
registered_path(&wide(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe")),
Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe"))
);
assert_eq!(registered_path("ERROR: The system was unable to find the specified registry key or value."), None);
assert_eq!(registered_path(" (Default) REG_SZ "), None);
assert_eq!(
registered_path(&wide(" \"C:\\Prögram Fïles\\Тест\\写真\\photocraft.exe\" ")),
Some(std::path::PathBuf::from(r"C:\Prögram Fïles\Тест\写真\photocraft.exe"))
);
assert_eq!(registered_path(&wide("")), None);
assert_eq!(registered_path(&[0xD800, 0]), None);
}
/// On Windows a registered path with characters outside the console's code page is read as
/// stored, from a scratch key under the current user's hive.
#[cfg(windows)]
#[test]
fn a_registered_path_outside_ascii_is_read_as_stored() {
let key = format!(r"Software\VectorCraftTest-app-paths-{}", std::process::id());
let path = r"C:\Prögram Fïles\Тест\写真\photocraft.exe";
let reg = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()).join(r"System32\reg.exe");
let full = format!(r"HKCU\{key}");
let added = std::process::Command::new(&reg).args(["add", &full, "/ve", "/t", "REG_SZ", "/d", path, "/f"]).output().unwrap();
assert!(added.status.success(), "{added:?}");
let read = super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key);
let _ = std::process::Command::new(&reg).args(["delete", &full, "/f"]).output();
assert_eq!(read, Some(std::path::PathBuf::from(path)));
assert_eq!(super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key), None, "deleted");
}
}
+8
View File
@@ -193,3 +193,11 @@ sync_github_name = true
[people.JonRC]
real_name = "Jonathan Cardoso"
display_name = "Jonathan Cardoso"
[people.vangel76]
real_name = "Valentin Klein"
display_name = "vangel76"
sync_github_name = false
[people.FrancoJacquet]
real_name = "Franco Jacquet"
+2 -1
View File
@@ -236,7 +236,8 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
return out;
}
let mut els = vec![];
kurbo::flatten(bp.iter(), tol.max(1e-4), |el| {
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
if els.len() < MAX_FLATTENED {
els.push(el);
}
+1 -1
View File
@@ -103,7 +103,7 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
let mut bp = BezPath::new();
sp.to_bezpath_into(&mut bp);
let mut pts = vec![];
kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| {
vectorcraft_geom::flatten(bp.iter(), flat_tol.max(1e-4), |e| {
if let PathEl::MoveTo(q) | PathEl::LineTo(q) = e {
pts.push(q);
}
+106 -15
View File
@@ -1,7 +1,7 @@
//! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint
//! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes
//! polylines and cubic splines with a lineweight and dashes, or filled outlines where the look
//! needs them.
//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or
//! filled outlines where the look needs them.
use std::collections::HashMap;
use std::io::Cursor;
@@ -66,6 +66,8 @@ struct CircularSub {
centre: Point,
radius: f64,
samples: Vec<Point>,
/// The signed angle (radians) the curve turns through about `centre` in document space.
turn: f64,
}
fn cubic_point(p0: Point, p1: Point, p2: Point, p3: Point, t: f64) -> Point {
@@ -122,7 +124,12 @@ fn circular_subpath(sub: &Sub) -> Option<CircularSub> {
if !centre.x.is_finite() || !centre.y.is_finite() || !radius.is_finite() || radius <= 1e-9 {
return None;
}
let tolerance = (radius * 5e-4).max(1e-6);
// The tolerance is a fraction of the smaller of the radius and the curve's extent, so the large
// radius of a shallow curve does not loosen it.
let (lo, hi) = samples
.iter()
.fold((samples[0], samples[0]), |(lo, hi), p| (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))));
let tolerance = (radius.min(lo.distance(hi)) * 5e-4).max(1e-6);
if samples.iter().any(|p| (centre.distance(*p) - radius).abs() > tolerance) {
return None;
}
@@ -181,7 +188,76 @@ fn circular_subpath(sub: &Sub) -> Option<CircularSub> {
} else if total_turn.abs() < 1e-6 || total_turn.abs() >= std::f64::consts::TAU - 1e-3 {
return None;
}
Some(CircularSub { centre, radius, samples })
Some(CircularSub { centre, radius, samples, turn: total_turn })
}
/// The points of the circle about `centre` of `radius` furthest left, right, up and down that lie on
/// its arc from `from` through `turn` radians, for the drawing extents.
fn arc_extrema(centre: Point, radius: f64, from: Point, turn: f64) -> Vec<Point> {
let start = (from.y - centre.y).atan2(from.x - centre.x);
(0..4)
.map(|k| f64::from(k) * std::f64::consts::FRAC_PI_2)
.filter(|a| ((a - start) * turn.signum()).rem_euclid(std::f64::consts::TAU) <= turn.abs())
.map(|a| Point::new(centre.x + radius * a.cos(), centre.y + radius * a.sin()))
.collect()
}
/// The most cubics one bulge arc is fitted to; the cubics after them start the next arc.
const MAX_ARC_RUN: usize = 64;
/// A subpath of straight segments and circular arcs as polyline vertices, in document space.
struct BulgedSub {
/// The anchors, without a closed subpath's repeated start.
pts: Vec<Point>,
/// For each anchor, the angle (radians, document space) the segment that starts there turns
/// through: 0 for a straight segment.
turns: Vec<f64>,
/// The arcs' extreme points ([`arc_extrema`]), for the drawing extents.
extrema: Vec<Point>,
}
/// Fit a subpath with curves to straight segments and circular arcs: each run of cubics on one
/// circle, turning one way and less than a whole turn, becomes one arc ([`circular_subpath`]'s
/// tolerance). `None` when the subpath has no curves or a curve that is not a circular arc.
fn bulged_subpath(sub: &Sub) -> Option<BulgedSub> {
if !sub.segs.iter().any(|s| matches!(s, Seg::Cubic(..))) {
return None;
}
let mut pts = vec![sub.start];
let mut turns = vec![];
let mut extrema = vec![];
let mut from = sub.start;
let mut i = 0;
while let Some(seg) = sub.segs.get(i) {
if let Seg::Line(p) = *seg {
turns.push(0.0);
pts.push(p);
from = p;
i += 1;
continue;
}
let mut best = None;
let mut j = i;
while j < sub.segs.len() && j - i < MAX_ARC_RUN && matches!(sub.segs[j], Seg::Cubic(..)) {
let run = Sub { start: from, segs: sub.segs[i..=j].to_vec(), closed: false };
let Some(arc) = circular_subpath(&run) else { break };
best = Some((j, arc));
j += 1;
}
let (j, arc) = best?;
turns.push(arc.turn);
extrema.extend(arc_extrema(arc.centre, arc.radius, from, arc.turn));
from = sub.segs[j].end();
pts.push(from);
i = j + 1;
}
if sub.closed && pts.last().is_some_and(|p| p.distance(sub.start) <= 1e-9) {
pts.pop();
} else {
// The segment from the last anchor: the straight closing edge, or none for an open subpath.
turns.push(0.0);
}
(pts.len() >= 2).then_some(BulgedSub { pts, turns, extrema })
}
/// A closed subpath that is the four-cubic circle under an affine map: an ellipse, or a circle
@@ -846,7 +922,9 @@ impl<'a> Scene<'a> {
}
/// Path `bp` as lines: a line for an open subpath of one straight segment, polylines for
/// other straight subpaths (and for curves in R12, flattened), cubic splines for curved ones.
/// other straight subpaths, circles, arcs and ellipses where the curves are one, polylines
/// with bulges for subpaths of straight segments and circular arcs, and cubic splines for
/// other curved ones (flattened polylines in R12).
/// `width`: the stroke weight, which DXF before 2000 gives polylines as a width.
fn lines(&mut self, bp: &BezPath, style: &EntityStyle, width: f64) {
let v = self.o.version;
@@ -863,7 +941,7 @@ impl<'a> Scene<'a> {
// A LINE has no width, so a stroke before 2000 keeps its polyline width.
match (sub.closed, width, pts.as_slice()) {
(false, None, &[a, b]) => self.line(a, b, style),
_ => self.polyline(&pts, sub.closed, style, width),
_ => self.polyline(&pts, &[], sub.closed, style, width),
}
} else if (v.handles() || width.is_none()) && self.circular(&sub, style) {
// Native circles/arcs are preferred by CAD/CAM software. In R12, however, a
@@ -871,6 +949,12 @@ impl<'a> Scene<'a> {
// its width. Non-circular curves continue through the existing fallback.
} else if v.handles() && self.elliptical(&sub, style) {
// R13 and later write an ellipse as a native ELLIPSE.
} else if let Some(b) = bulged_subpath(&sub) {
// Straight segments and circular arcs: one polyline whose bulges draw the arcs.
b.extrema.iter().for_each(|p| _ = self.pt(*p));
let flip = if self.to_dxf.determinant() < 0.0 { -1.0 } else { 1.0 };
let bulges: Vec<f64> = b.turns.iter().map(|t| flip * (t / 4.0).tan()).collect();
self.polyline(&b.pts, &bulges, sub.closed, style, width);
} else if v.handles() {
self.spline(&sub, style);
} else {
@@ -883,7 +967,7 @@ impl<'a> Scene<'a> {
}
}
for pts in polygons(&path) {
self.polyline(&pts, sub.closed, style, width);
self.polyline(&pts, &[], sub.closed, style, width);
}
}
}
@@ -900,8 +984,9 @@ impl<'a> Scene<'a> {
}
/// A polyline through `pts` (document space): lightweight from R14, else a polyline with a
/// vertex entity per point.
fn polyline(&mut self, pts: &[Point], closed: bool, style: &EntityStyle, width: Option<f64>) {
/// vertex entity per point. `bulges`: the bulge (group 42) of the segment that starts at each
/// point, in drawing space; empty for straight segments only.
fn polyline(&mut self, pts: &[Point], bulges: &[f64], closed: bool, style: &EntityStyle, width: Option<f64>) {
if pts.len() < 2 {
return;
}
@@ -917,8 +1002,11 @@ impl<'a> Scene<'a> {
if let Some(w) = width {
self.e.num(43, w);
}
for p in &pts {
for (i, p) in pts.iter().enumerate() {
self.e.xy(10, p.x, p.y);
if let Some(&b) = bulges.get(i).filter(|b| **b != 0.0) {
self.e.num(42, b);
}
}
return;
}
@@ -930,13 +1018,16 @@ impl<'a> Scene<'a> {
self.e.num(40, w);
self.e.num(41, w);
}
for p in &pts {
for (i, p) in pts.iter().enumerate() {
let vh = self.handle();
self.e.entity("VERTEX", vh, h, &layer, style, "AcDbVertex");
if self.o.version.handles() {
self.e.raw(100, "AcDb2dVertex");
}
self.e.xyz(10, p.x, p.y);
if let Some(&b) = bulges.get(i).filter(|b| **b != 0.0) {
self.e.num(42, b);
}
}
let end = self.handle();
self.e.entity("SEQEND", end, h, &layer, style, "");
@@ -960,8 +1051,8 @@ impl<'a> Scene<'a> {
return false;
}
// Count sampled points in the drawing extents. For a full circle include all cardinal
// points exactly; for an arc, the dense samples conservatively cover its visible span.
// Count the curve's extreme points in the drawing extents: all four cardinal points of a
// full circle; an arc's ends and the cardinal points on it.
if sub.closed {
let r = circle.radius;
for p in [
@@ -973,8 +1064,8 @@ impl<'a> Scene<'a> {
self.pt(p);
}
} else {
for p in &circle.samples {
self.pt(*p);
for p in [sub.start, last].into_iter().chain(arc_extrema(circle.centre, circle.radius, sub.start, circle.turn)) {
self.pt(p);
}
}
+204 -4
View File
@@ -275,6 +275,197 @@ fn circles_and_circular_arcs_are_native_dxf_entities() {
}
}
/// A cubic arc about `c` of radius `r` from `deg0` to `deg1` (degrees, y down), from the current
/// point, which is the arc's start.
fn arc_cubic(b: &mut vectorcraft_geom::BezPath, c: Point, r: f64, deg0: f64, deg1: f64) {
let (a0, a1) = (deg0.to_radians(), deg1.to_radians());
let k = 4.0 / 3.0 * ((a1 - a0) / 4.0).tan() * r;
let (p0, p3) = (Point::new(c.x + r * a0.cos(), c.y + r * a0.sin()), Point::new(c.x + r * a1.cos(), c.y + r * a1.sin()));
b.curve_to(Point::new(p0.x - k * a0.sin(), p0.y + k * a0.cos()), Point::new(p3.x + k * a1.sin(), p3.y - k * a1.cos()), p3);
}
/// A slot (two lines, two half circles) about y = 50, a D shape (a half circle closed by its
/// diameter) and a rounded rectangle with 10 pt corners.
fn lines_and_arcs() -> [PathData; 3] {
let mut slot = vectorcraft_geom::BezPath::new();
slot.move_to((60.0, 30.0));
slot.line_to((140.0, 30.0));
arc_cubic(&mut slot, Point::new(140.0, 50.0), 20.0, -90.0, 0.0);
arc_cubic(&mut slot, Point::new(140.0, 50.0), 20.0, 0.0, 90.0);
slot.line_to((60.0, 70.0));
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 90.0, 180.0);
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 180.0, 270.0);
slot.close_path();
let mut d = vectorcraft_geom::BezPath::new();
d.move_to((150.0, 20.0));
arc_cubic(&mut d, Point::new(150.0, 50.0), 30.0, -90.0, 0.0);
arc_cubic(&mut d, Point::new(150.0, 50.0), 30.0, 0.0, 90.0);
d.close_path();
[PathData::from_bezpath(&slot), PathData::from_bezpath(&d), shapes::rounded_rectangle(Rect::new(20.0, 20.0, 100.0, 80.0), 10.0)]
}
/// A polyline entity's vertices as (x, y, bulge): an LWPOLYLINE's, or those of the VERTEX
/// entities that follow a POLYLINE at `e[i]`.
fn vertices(e: &[Pairs], i: usize) -> Vec<(f64, f64, f64)> {
let mut out = vec![];
let mut read = |o: &Pairs| {
for (code, value) in o {
let v: f64 = value.trim().parse().unwrap_or(0.0);
match code {
10 => out.push((v, 0.0, 0.0)),
20 => out.last_mut().expect("x before y").1 = v,
42 => out.last_mut().expect("a vertex before its bulge").2 = v,
_ => {}
}
}
};
if kind(&e[i]) == "LWPOLYLINE" {
read(&e[i]);
} else {
e[i + 1..].iter().take_while(|o| kind(o) == "VERTEX").for_each(&mut read);
}
out
}
#[test]
fn paths_of_lines_and_circular_arcs_are_polylines_with_bulges() {
let [slot, d_shape, rounded] = lines_and_arcs();
let d = doc_with(|d| {
let black = || Paint::solid(Color::BLACK);
let mut open = vectorcraft_geom::BezPath::new();
open.move_to((10.0, 90.0));
open.line_to((30.0, 90.0));
arc_cubic(&mut open, Point::new(30.0, 80.0), 10.0, 90.0, 0.0);
vec![
path(d, slot, Paint::None, black(), 1.0),
path(d, d_shape, Paint::None, black(), 1.0),
path(d, rounded, Paint::None, black(), 1.0),
path(d, PathData::from_bezpath(&open), Paint::None, black(), 1.0),
]
});
let b = (std::f64::consts::PI / 8.0).tan();
for version in DxfVersion::ALL {
let out = export(&d, &DxfOptions { version, ..opts(&d) }).unwrap();
let e = entities(&out);
let polys: Vec<usize> = (0..e.len()).filter(|i| matches!(kind(&e[*i]), "LWPOLYLINE" | "POLYLINE")).collect();
let k = kinds(&out);
assert_eq!(polys.len(), 4, "{version:?}: {k:?}");
assert!(!k.iter().any(|k| matches!(k.as_str(), "SPLINE" | "ARC" | "CIRCLE")), "{version:?}: {k:?}");
let want = if version.lwpolyline() { "LWPOLYLINE" } else { "POLYLINE" };
assert!(polys.iter().all(|i| kind(&e[*i]) == want), "{version:?}: {k:?}");
let flags: Vec<i64> = polys.iter().map(|i| get(&e[*i], 70).unwrap().parse::<i64>().unwrap() & 1).collect();
assert_eq!(flags, [1, 1, 1, 0], "{version:?}: closed, closed, closed, open");
// The slot's half circles turn clockwise with y up: a bulge of -1 after each long side.
assert_eq!(vertices(&e, polys[0]), [(60.0, 70.0, 0.0), (140.0, 70.0, -1.0), (140.0, 30.0, 0.0), (60.0, 30.0, -1.0)], "{version:?}");
// The D shape: the half circle, then the straight closing edge.
assert_eq!(vertices(&e, polys[1]), [(150.0, 80.0, -1.0), (150.0, 20.0, 0.0)], "{version:?}");
// The rounded rectangle: eight anchors, a quarter circle (bulge tan 22.5°) at each corner.
let r = vertices(&e, polys[2]);
assert_eq!(r.len(), 8, "{version:?}: {r:?}");
let bulges: Vec<f64> = r.iter().map(|v| v.2).filter(|b| *b != 0.0).collect();
assert!(close_to(&bulges, &[-b; 4], 1e-6), "{version:?}: {r:?}");
// An open line then a quarter circle turning counterclockwise with y up.
let o = vertices(&e, polys[3]);
assert!(
close_to(&o.iter().flat_map(|v| [v.0, v.1, v.2]).collect::<Vec<_>>(), &[10.0, 10.0, 0.0, 30.0, 10.0, b, 40.0, 20.0, 0.0], 1e-6),
"{version:?}: {o:?}"
);
}
}
#[test]
fn polylines_with_bulges_read_back_as_the_same_outline() {
for (i, shape) in lines_and_arcs().into_iter().enumerate() {
let original = shape.to_bezpath();
let d = doc_with(|d| vec![path(d, shape, Paint::None, Paint::solid(Color::BLACK), 1.0)]);
let out = export(&d, &opts(&d)).unwrap();
assert_eq!(kinds(&out), ["LWPOLYLINE"], "shape {i}");
let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() };
let back = import(&out.bytes, &o).unwrap().document;
let mut paths = vec![];
back.walk(|n| {
if let NodeKind::Path { path, .. } = &n.kind {
paths.push(path.to_bezpath());
}
});
assert_eq!(paths.len(), 1, "shape {i}");
assert!(paths[0].elements().last().is_some_and(|el| matches!(el, kurbo::PathEl::ClosePath)), "shape {i} reads back closed");
let (a, b) = (original.bounding_box(), paths[0].bounding_box());
assert!(close_to(&[a.width(), a.height()], &[b.width(), b.height()], 1e-2), "shape {i}: {a:?} against {b:?}");
// Every point read back lies on the original outline, once both are centered.
let shift = a.center() - b.center();
let outline: Vec<Point> = original.segments().flat_map(|s| (0..=64).map(move |t| s.eval(f64::from(t) / 64.0))).collect();
for seg in paths[0].segments() {
for t in 0..=16 {
let p = seg.eval(f64::from(t) / 16.0) + shift;
let near = outline
.windows(2)
.map(|w| {
let (u, v) = (w[1] - w[0], p - w[0]);
let s = if u.hypot2() > 0.0 { (v.dot(u) / u.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
(v - u * s).hypot()
})
.fold(f64::INFINITY, f64::min);
assert!(near < 1e-2, "shape {i}: {p:?} is {near} pt off the outline");
}
}
}
}
#[test]
fn a_path_with_a_curve_that_is_not_a_circular_arc_stays_a_spline() {
// The slot with one end drawn by a longer-handled curve.
let mut slot = vectorcraft_geom::BezPath::new();
slot.move_to((60.0, 30.0));
slot.line_to((140.0, 30.0));
slot.curve_to((165.0, 30.0), (165.0, 70.0), (140.0, 70.0));
slot.line_to((60.0, 70.0));
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 90.0, 180.0);
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 180.0, 270.0);
slot.close_path();
let d = doc_with(|d| {
vec![
path(d, PathData::from_bezpath(&slot), Paint::None, Paint::solid(Color::BLACK), 1.0),
path(d, shapes::ellipse(Rect::new(150.0, 20.0, 190.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0),
]
});
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "CIRCLE"]);
}
#[test]
fn drawing_extents_reach_the_extreme_points_of_arcs() {
// An arc about (100, 50) of radius 40 from -60° to 30° passes x = 140 at 0°, between the points
// along it that recognition samples.
let arc = |closed: bool| {
let mut b = vectorcraft_geom::BezPath::new();
let start = Point::new(100.0 + 40.0 * 60f64.to_radians().cos(), 50.0 - 40.0 * 60f64.to_radians().sin());
b.move_to(start);
arc_cubic(&mut b, Point::new(100.0, 50.0), 40.0, -60.0, 30.0);
if closed {
b.close_path();
}
PathData::from_bezpath(&b)
};
for (closed, entity) in [(false, "ARC"), (true, "LWPOLYLINE")] {
let d = doc_with(|d| vec![path(d, arc(closed), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
let out = export(&d, &opts(&d)).unwrap();
assert_eq!(kinds(&out), [entity]);
let x: f64 = header(&pairs(&out.bytes), "$EXTMAX").unwrap().trim().parse().unwrap();
assert!((x - 140.0).abs() < 1e-6, "{entity}: $EXTMAX x {x}");
}
}
#[test]
fn a_shallow_curve_that_is_not_circular_is_not_an_arc() {
// 100 pt across and 1.5 pt deep: the circle through its ends and middle has a radius of about
// 834 pt, and the curve is 0.12 pt off it a quarter of the way along.
let mut b = vectorcraft_geom::BezPath::new();
b.move_to((0.0, 50.0));
b.curve_to((20.0, 48.0), (80.0, 48.0), (100.0, 50.0));
let d = doc_with(|d| vec![path(d, PathData::from_bezpath(&b), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE"]);
}
/// The path `p` with `xf` applied.
fn transformed(p: &PathData, xf: Affine) -> PathData {
PathData::from_bezpath(&(xf * p.to_bezpath()))
@@ -391,11 +582,12 @@ fn closed_four_cubic_shapes_that_are_not_writable_ellipses_stay_splines() {
vec![
path(d, PathData::from_bezpath(&squircle), Paint::None, Paint::solid(Color::BLACK), 1.0),
path(d, PathData::from_bezpath(&kurbo::BezPath::from_vec(els)), Paint::None, Paint::solid(Color::BLACK), 1.0),
// An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6).
// An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6). Its
// quarters fit shallow circular arcs within the tolerance, so it is a polyline with bulges.
path(d, shapes::ellipse(Rect::new(0.0, 90.0, 200.0, 90.0001)), Paint::None, Paint::solid(Color::BLACK), 1.0),
]
});
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "SPLINE"]);
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "LWPOLYLINE"]);
}
#[test]
@@ -462,8 +654,12 @@ fn closed_circular_arc_with_a_closing_chord_is_not_a_circle() {
vec![path(d, PathData::from_bezpath(&arc), Paint::None, Paint::solid(Color::BLACK), 1.0)]
});
// The three quarters turn counterclockwise with y up (bulge tan 67.5°), then the chord closes it.
let modern = export(&d, &opts(&d)).unwrap();
assert_eq!(kinds(&modern), ["SPLINE"]);
assert_eq!(kinds(&modern), ["LWPOLYLINE"]);
let v = vertices(&entities(&modern), 0);
let flat: Vec<f64> = v.iter().flat_map(|v| [v.0, v.1, v.2]).collect();
assert!(close_to(&flat, &[80.0, 50.0, 67.5f64.to_radians().tan(), 50.0, 20.0, 0.0], 1e-6), "{v:?}");
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap();
assert!(kinds(&r12).iter().any(|k| k == "POLYLINE"));
assert!(!kinds(&r12).iter().any(|k| k == "CIRCLE"));
@@ -497,9 +693,13 @@ fn a_closed_sliver_along_a_circle_is_not_a_circle() {
vec![path(d, PathData::from_bezpath(&sliver), Paint::None, Paint::solid(Color::BLACK), 1.0)]
});
// Two arcs, out along the circle and back: one polyline with a bulge each way.
let modern = export(&d, &opts(&d)).unwrap();
assert_ne!(kinds(&modern), ["CIRCLE"]);
assert_eq!(kinds(&modern), ["SPLINE"]);
assert_eq!(kinds(&modern), ["LWPOLYLINE"]);
let bulges: Vec<f64> = vertices(&entities(&modern), 0).iter().map(|v| v.2).collect();
let b = 10f64.to_radians().tan();
assert!(close_to(&bulges, &[-b, b], 1e-6) || close_to(&bulges, &[b, -b], 1e-6), "{bulges:?}");
}
#[test]
+33 -8
View File
@@ -34,11 +34,11 @@ impl WidthProfile {
if t <= p[0].0 {
return (p[0].1, p[0].2);
}
for w in p.windows(2) {
if t <= w[1].0 {
let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9);
return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u);
}
// (Positions go forward; found in log time, so a long profile read from a file is cheap to ask.)
let i = p.partition_point(|q| q.0 < t);
if let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) {
let u = (t - a.0) / (b.0 - a.0).max(1e-9);
return (a.1 + (b.1 - a.1) * u, a.2 + (b.2 - a.2) * u);
}
p.last().map_or((1.0, 1.0), |l| (l.1, l.2))
}
@@ -90,10 +90,12 @@ impl WidthProfile {
/// discontinuous point (two points at `t`, within `1e-7`).
pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) {
let p = &self.points;
if let Some(i) = p.iter().position(|q| (q.0 - t).abs() <= 1e-7) {
let j = i + p[i..].iter().take_while(|q| (q.0 - p[i].0).abs() <= 1e-9).count() - 1;
// The same distance test below, so a point exactly 1e-7 before `t` is never skipped by rounding.
let i = p.partition_point(|q| q.0 < t && (q.0 - t).abs() > 1e-7);
if let Some(first) = p.get(i).filter(|q| (q.0 - t).abs() <= 1e-7) {
let j = i + p[i..].partition_point(|q| q.0 - first.0 <= 1e-9) - 1;
if j > i {
return ((p[i].1, p[i].2), (p[j].1, p[j].2));
return ((first.1, first.2), (p[j].1, p[j].2));
}
}
let v = self.at(t);
@@ -334,3 +336,26 @@ pub struct SavedProfile {
pub name: String,
pub profile: WidthProfile,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn width_profile_lookups_by_search() {
let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25), (1.0, 0.0, 0.0)] };
assert_eq!(p.at(-1.0), (0.0, 0.0));
assert_eq!(p.at(0.25), (0.5, 0.5));
assert_eq!(p.at(0.75), (0.25, 0.125));
assert_eq!(p.at(2.0), (0.0, 0.0));
// A step: the widths just before and just after it.
assert_eq!(p.around(0.5), ((1.0, 1.0), (0.5, 0.25)));
assert_eq!(p.around(0.25), ((0.5, 0.5), (0.5, 0.5)));
// Many points at one position are one step, found without a pass over them all.
let many = WidthProfile { points: (0..1000).map(|i| (0.5, i as f64, i as f64)).collect() };
assert_eq!(many.around(0.5), ((0.0, 0.0), (999.0, 999.0)));
// 0.4999999 == 0.5 - 1e-7, yet its distance from 0.5 rounds above 1e-7: it is not part of the step.
let near = WidthProfile { points: vec![(0.4999999, 2.0, 2.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25)] };
assert_eq!(near.around(0.5), ((1.0, 1.0), (0.5, 0.25)));
}
}
+10 -1
View File
@@ -390,10 +390,19 @@ fn a_projection_follows_the_transform_or_is_removed() {
let mut n = instance(far);
n.transform(Affine::scale(1e150), false);
assert_eq!(projection(&n), None);
// A transform that is not invertible leaves the projection as it is.
// A transform that is not invertible leaves the projection as it is, at any scale.
let mut n = instance(far);
n.transform(Affine::scale(0.0), false);
assert_eq!(projection(&n), Some(far.to_array()));
let mut n = instance(far);
n.transform(Affine::new([1e-8, 2e-8, 2e-8, 4e-8, 0.0, 0.0]), false);
assert_eq!(projection(&n), Some(far.to_array()));
// A scale by 1e-8 is invertible: a move by 10 becomes a move by 1e-7.
let ten = Homography::from_affine(Affine::translate((10.0, 0.0)));
let mut n = instance(ten);
n.transform(Affine::scale(1e-8), false);
let q = n.projection().unwrap().apply(Point::new(3e-8, 7e-8)).unwrap();
assert!(q.distance(Point::new(1.3e-7, 7e-8)) < 1e-20, "{q:?}");
}
#[test]
+1 -1
View File
@@ -63,7 +63,7 @@ impl Node {
pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) {
if let Some(p) = self.extras_if_any().and_then(|e| e.perspective.as_deref_mut())
&& let Some(h) = p.homography()
&& a.determinant().abs() >= 1e-15
&& Homography::affine_is_invertible(a)
{
p.projection = h.conjugated(a).map(|h| h.to_array());
}
+5 -2
View File
@@ -114,13 +114,16 @@ pub(super) fn split_at(pts: &[Point], corner: &[bool], closed: bool, marks: &[f6
let seg_count = if closed { n } else { n.saturating_sub(1) };
let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len()));
let mut acc = 0.0;
// Sorted once, so each segment finds its marks by search, not by a pass over all of them.
let mut marks = marks.to_vec();
marks.sort_by(f64::total_cmp);
for i in 0..seg_count {
let (a, b) = (pts[i], pts[(i + 1) % n]);
let len = a.distance(b);
out.0.push(a);
out.1.push(corner[i]);
let mut inner: Vec<f64> = marks.iter().copied().filter(|d| *d > acc + 1e-9 && *d < acc + len - 1e-9).collect();
inner.sort_by(f64::total_cmp);
let from = marks.partition_point(|d| *d <= acc + 1e-9);
let mut inner: Vec<f64> = marks.iter().skip(from).copied().take_while(|d| *d < acc + len - 1e-9).collect();
inner.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
for d in inner {
out.0.push(a.lerp(b, (d - acc) / len));
+17
View File
@@ -178,6 +178,23 @@ pub(crate) struct ActiveItem {
}
impl Session {
/// The method returns explicit target parameters and the selected appearance effect list.
pub fn appearance_effect_target(&self, params: &Value) -> Option<(Value, &[vectorcraft_doc::Effect])> {
let mut ids = appearance_targets(self, params).ok()?;
let item = item_target(self, params, "effect.apply").ok()?;
let anchor = item.anchor(self, &ids);
let node = self.active()?.doc.node(*ids.get(anchor)?)?;
let at = item.effects_item(&node.appearance, "effect.apply").ok()?;
let effects = node.appearance.effects_at(at)?;
ids.swap(0, anchor);
let ids: Vec<u64> = ids.into_iter().map(|id| id.0).collect();
let aligned = match item {
ItemTarget::Item { aligned, .. } => aligned,
ItemTarget::Top => aligned(params),
};
Some((json!({"ids": ids, "item": at, "aligned": aligned}), effects.as_slice()))
}
/// The Appearance panel's active fill/stroke: a paint-order index into the first selected
/// object's stack, while the selection it was chosen for is unchanged.
pub fn appearance_item(&self) -> Option<usize> {
+71 -31
View File
@@ -138,8 +138,12 @@ fn cut_targets(s: &Session) -> Result<Vec<NodeId>> {
/// What a cut does to one object: its new pieces (none deletes it).
type Plan = Vec<(NodeId, Vec<PathData>)>;
/// Run `cut` on every target's geometry (`None`: unchanged) and apply the result as one undo step.
fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, FillRule) -> Option<Vec<PathData>>) -> Result<Value> {
/// What a cut makes of one object: its pieces (`None`: unchanged), or the pathops refusal.
type Cut = std::result::Result<Option<Vec<PathData>>, po::PathOpsError>;
/// Run `cut` on every target's geometry (`None`: unchanged) and apply the result as one undo step. A shape the
/// booleans refuse (too complex, too far out) fails the command with the art untouched: it is not "nothing on that side".
fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, FillRule) -> Cut) -> Result<Value> {
let targets = cut_targets(s)?;
if targets.is_empty() {
return Err(bad(cmd, "select paths or compound paths"));
@@ -151,7 +155,8 @@ fn run_cut(s: &mut Session, cmd: &str, label: &str, cut: &dyn Fn(&PathData, Fill
if pd.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())) {
return Err(bad(cmd, "paths contain invalid coordinates"));
}
if let Some(pieces) = cut(&pd, rule) {
let pieces = cut(&pd, rule).map_err(|e| bad(cmd, format!("the cut cannot be made on this art: {e}")))?;
if let Some(pieces) = pieces {
plan.push((id, pieces));
}
}
@@ -184,9 +189,9 @@ fn reach(pd: &PathData) -> Rect {
}
/// `pd ∩ region`, dropping slivers.
fn intersect(pd: &PathData, rule: FillRule, region: &PathData) -> PathData {
let r = po::boolean(pd, rule, region, FillRule::NonZero, BoolOp::Intersect);
if po::area(&r, FillRule::NonZero) <= 1e-6 { PathData::default() } else { r }
fn intersect(pd: &PathData, rule: FillRule, region: &PathData) -> std::result::Result<PathData, po::PathOpsError> {
let r = po::try_boolean(pd, rule, region, FillRule::NonZero, BoolOp::Intersect, po::DEFAULT_PRECISION)?;
Ok(if po::try_area(&r, FillRule::NonZero)? <= 1e-6 { PathData::default() } else { r })
}
// ---------- Line Cut ----------
@@ -198,24 +203,26 @@ fn line_cut(s: &mut Session, p: &Value) -> Result<Value> {
}
/// `pd` split by the line: the pieces on both sides, `None` when the line misses it.
fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Option<Vec<PathData>> {
fn split_by_line(pd: &PathData, rule: FillRule, axis: &Axis) -> Cut {
if pd.is_closed() {
let around = reach(pd);
let a = intersect(pd, rule, &axis.half_plane(1.0, around));
let b = intersect(pd, rule, &axis.half_plane(-1.0, around));
let a = intersect(pd, rule, &axis.half_plane(1.0, around))?;
let b = intersect(pd, rule, &axis.half_plane(-1.0, around))?;
if a.is_empty() || b.is_empty() {
return None;
return Ok(None);
}
return Some(components(&a).into_iter().chain(components(&b)).collect());
return Ok(Some(components(&a).into_iter().chain(components(&b)).collect()));
}
// Open paths: the parts on each side (each pass removes the other side).
let a = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0)?;
let b = erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0)?;
Some(if pd.subpaths.len() == 1 {
let (Some(a), Some(b)) = (erase_outline(pd, f64::INFINITY, &|q| axis.side(q) < 0.0), erase_outline(pd, f64::INFINITY, &|q| axis.side(q) >= 0.0))
else {
return Ok(None);
};
Ok(Some(if pd.subpaths.len() == 1 {
a.into_iter().chain(b).collect()
} else {
vec![PathData::new(a.into_iter().chain(b).flat_map(|p| p.subpaths).collect())]
})
}))
}
// ---------- Rectangle Cut ----------
@@ -238,25 +245,34 @@ fn rect_cut(s: &mut Session, p: &Value) -> Result<Value> {
}
/// `pd` cropped to `rect`: `None` when it lies inside, no pieces when it lies outside.
fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Option<Vec<PathData>> {
let b = pd.bounds()?;
fn crop(pd: &PathData, rule: FillRule, rect: Rect) -> Cut {
let Some(b) = pd.bounds() else { return Ok(None) };
if rect.inflate(1e-9, 1e-9).contains_rect(b) {
return None;
return Ok(None);
}
if pd.is_closed() {
let r =
intersect(pd, rule, &polygon(&[rect.origin(), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]));
return Some(if r.is_empty() { vec![] } else { vec![r] });
// Wholly outside: nothing is left, whatever the booleans would make of the rectangle's coordinates.
if rect.intersect(b).is_zero_area() {
return Ok(Some(vec![]));
}
let r = intersect(
pd,
rule,
&polygon(&[rect.origin(), Point::new(rect.x1, rect.y0), Point::new(rect.x1, rect.y1), Point::new(rect.x0, rect.y1)]),
)?;
return Ok(Some(if r.is_empty() { vec![] } else { vec![r] }));
}
let inside = rect.inflate(1e-9, 1e-9);
// Sampled at least every half of the rectangle's shorter side, so a line through it is found.
let step = rect.width().min(rect.height()) / 2.0;
let pieces = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1))?;
Some(if pd.subpaths.len() == 1 || pieces.is_empty() {
let Some(pieces) = erase_outline(pd, step, &|q| !(q.x >= inside.x0 && q.x <= inside.x1 && q.y >= inside.y0 && q.y <= inside.y1)) else {
return Ok(None);
};
Ok(Some(if pd.subpaths.len() == 1 || pieces.is_empty() {
pieces
} else {
vec![PathData::new(pieces.into_iter().flat_map(|p| p.subpaths).collect())]
})
}))
}
// ---------- Mirror & Cut ----------
@@ -287,7 +303,7 @@ fn mirror_cut(s: &mut Session, p: &Value) -> Result<Value> {
other => return Err(bad(C, format!("unknown axis `{other}` (vertical|horizontal|free)"))),
};
let sign = keep_sign(&axis, str_param(p, "keep")).map_err(|e| bad(C, e))?;
run_cut(s, C, "Mirror & Cut", &|pd, rule| Some(mirror(pd, rule, &axis, sign)))
run_cut(s, C, "Mirror & Cut", &|pd, rule| mirror(pd, rule, &axis, sign).map(Some))
}
/// The sign of [`Axis::side`] on the side `keep` names (default: left, or top when the axis runs
@@ -309,22 +325,22 @@ fn keep_sign(axis: &Axis, keep: Option<&str>) -> std::result::Result<f64, String
}
/// The kept half of `pd` and its reflection, joined (no pieces when nothing is on the kept side).
fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> Vec<PathData> {
fn mirror(pd: &PathData, rule: FillRule, axis: &Axis, sign: f64) -> std::result::Result<Vec<PathData>, po::PathOpsError> {
let m = axis.reflection();
if pd.is_closed() {
let kept = intersect(pd, rule, &axis.half_plane(sign, reach(pd)));
let kept = intersect(pd, rule, &axis.half_plane(sign, reach(pd)))?;
if kept.is_empty() {
return vec![];
return Ok(vec![]);
}
let joined = po::boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union);
return if joined.is_empty() { vec![] } else { vec![joined] };
let joined = po::try_boolean(&kept, FillRule::NonZero, &kept.transformed(m), FillRule::NonZero, BoolOp::Union, po::DEFAULT_PRECISION)?;
return Ok(if joined.is_empty() { vec![] } else { vec![joined] });
}
let kept = match erase_outline(pd, f64::INFINITY, &|q| axis.side(q) * sign < 0.0) {
Some(pieces) => pieces.into_iter().flat_map(|p| p.subpaths).collect(),
None => pd.subpaths.clone(),
};
let subs: Vec<SubPath> = kept.iter().flat_map(|sp| mirror_open(sp, axis, m)).collect();
if subs.is_empty() { vec![] } else { vec![PathData::new(subs)] }
Ok(if subs.is_empty() { vec![] } else { vec![PathData::new(subs)] })
}
/// An open run and its reflection, joined where its ends touch the axis (closed when both do);
@@ -399,4 +415,28 @@ mod tests {
let out = mirror_open(&sp, &axis, axis.reflection());
assert_eq!((out.len(), out[0].closed, out[0].anchors.len()), (1, false, 3));
}
/// A shape the booleans refuse (here: so far from the origin that the sweep tolerance exceeds the precision) is an error,
/// not "no pieces": that would make Mirror & Cut delete it and Rectangle Cut crop it to nothing.
#[test]
fn a_shape_the_booleans_refuse_is_an_error_not_no_pieces() {
let far = polygon(&[
Point::new(1e15, 1e15),
Point::new(1e15 + 100.0, 1e15),
Point::new(1e15 + 100.0, 1e15 + 100.0),
Point::new(1e15, 1e15 + 100.0),
]);
let axis = Axis { p: Point::ZERO, d: Vec2::new(0.0, 1.0) };
let refused = Some(po::PathOpsError::Degenerate);
assert_eq!(mirror(&far, FillRule::NonZero, &axis, 1.0).err(), refused);
assert_eq!(split_by_line(&far, FillRule::NonZero, &axis).err(), refused);
// A rectangle that far out, against art near the origin, still crops it to nothing.
let far_rect = Rect::new(1e15, 1e15, 1e15 + 100.0, 1e15 + 100.0);
let near_art = polygon(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]);
assert_eq!(crop(&near_art, FillRule::NonZero, far_rect).unwrap(), Some(vec![]));
// Near the origin the same cuts work.
let near = polygon(&[Point::new(-50.0, 0.0), Point::new(50.0, 0.0), Point::new(50.0, 100.0), Point::new(-50.0, 100.0)]);
assert_eq!(mirror(&near, FillRule::NonZero, &axis, 1.0).unwrap().len(), 1);
assert_eq!(split_by_line(&near, FillRule::NonZero, &axis).unwrap().map(|p| p.len()), Some(2));
}
}
+6 -11
View File
@@ -304,21 +304,16 @@ fn same(s: &mut Session, cmd: &str, eq: fn(&Node, &Node) -> bool) -> Result<Valu
finish_same(s, cmd, ids)
}
/// The first character style of the first type object [`each_selected_text`] gives.
fn first_text_style(s: &Session) -> Option<CharStyle> {
let st = s.active()?;
let mut out = None;
for id in &st.selection.objects {
st.doc.node(*id)?.walk(&mut |n| {
if out.is_none()
&& let NodeKind::Text(t) = &n.kind
{
out = Some(t.first_style());
}
});
if out.is_some() {
break;
each_selected_text(s, |id| {
if let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) {
out = Some(t.first_style());
}
}
out.is_none()
});
out
}
+4 -1
View File
@@ -420,7 +420,10 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result<Vec<u8>> {
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame).
pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
let f = super::writable(C, Some(format), None)?;
encode_all(doc, f.id, p)?.single(f)
let enc = encode_all(doc, f.id, p)?;
// The error for a version 7 .ai of several artboards names the legacy .ai.
let legacy = f.id == "ai" && super::legacy_ai::wanted(C, f, p)?;
enc.single(&if legacy { super::legacy_ai::named(f) } else { *f })
}
/// [`encode`], with every file the export writes.
+9 -3
View File
@@ -41,7 +41,7 @@ use super::super::{Affine, EngineError, NodeId, Result, bad};
use super::{ArtboardPick, Encoded, Format};
/// Does `p` ask a save in `f` for a legacy `.ai` file of version 7 (`aiVersion: "7"`)? An unknown
/// version is an error, and so is version 7 for a `.ait` template, which is PDF-compatible only.
/// version is an error, and so is version 7 for a `.ait` template, which is never a legacy file.
pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result<bool> {
let legacy = match p.get("aiVersion") {
None | Some(Value::Null) => false,
@@ -51,11 +51,17 @@ pub(super) fn wanted(cmd: &str, f: &Format, p: &Value) -> Result<bool> {
Some(v) => return Err(bad(cmd, format!("aiVersion {v}: \"pdf\" (PDF-compatible, the default) or \"7\" (legacy .ai, version 7)"))),
};
if legacy && f.id == "ait" {
return Err(bad(cmd, "aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible"));
return Err(bad(cmd, "aiVersion 7 writes legacy .ai files, not .ait templates"));
}
Ok(legacy)
}
/// `f` (the `.ai` format, whose label names the PDF-compatible file) named, in its errors, as the
/// legacy `.ai` file.
pub(super) fn named(f: &Format) -> Format {
Format { label: "legacy .ai (version 7)", ..*f }
}
/// What a legacy `.ai` does with the images it can't hold (`transparentImages`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SeeThrough {
@@ -109,7 +115,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
}
let mode = see_through(cmd, p)?;
let (hidden, outline_text) = (hidden_objects(cmd, p)?, outline_text(cmd, p)?);
let picked: ArtboardPick = super::encode::options(f, p)?;
let picked: ArtboardPick = super::encode::options(&named(f), p)?;
let boards = picked.resolve(n).map_err(|e| bad(cmd, e))?.unwrap_or_else(|| (0..n).collect());
let mut enc = Encoded { warnings: vec![FIDELITY.to_string()], ..Encoded::default() };
if boards.len() > 1 {
+30 -8
View File
@@ -249,11 +249,6 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
if let Some((key, top, inner)) = disagreeing_option(p, is_svg(format)).map_err(|e| bad(cmd, e))? {
return Err(bad(cmd, format!("`{key}: {top}` and `options.{key}: {inner}` disagree: give the option once")));
}
let notes = NATIVE_OPTIONS
.iter()
.filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k))
.map(|k| format!("`{k}` was not used: {} files don't read it", format.label))
.collect();
let mut given: Map<String, Value> = match p.get("options") {
Some(Value::Object(o)) => o.iter().filter(|(k, _)| reads_option(format, k)).map(|(k, v)| (k.clone(), v.clone())).collect(),
None | Some(Value::Null) => Map::new(),
@@ -293,6 +288,12 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
if let Some(path) = &path {
super::check_not_lossy_overwrite(st, path, p, cmd)?;
}
let written = written_as(cmd, format, &Value::Object(options.clone()));
let notes = NATIVE_OPTIONS
.iter()
.filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k))
.map(|k| format!("`{k}` was not used: {} files don't read it", written.label))
.collect();
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes })
}
@@ -579,6 +580,25 @@ const NOT_PDF_COMPATIBLE: &str = "saved without PDF content: VectorCraft opens i
const NOT_PDF_COMPATIBLE_EDITING: &str =
"saved without PDF content: VectorCraft and apps that read its editing data open it, other apps show empty pages";
/// `f` (`.ai` or `.ait`) named, in its option errors, as a file saved without PDF content.
fn without_pdf(f: &Format) -> Format {
let label = if f.id == "ait" { "non-PDF-compatible .ait template" } else { "non-PDF-compatible .ai" };
Format { label, ..*f }
}
/// `f` named, in its errors and notes, as the file a save with options `p` writes: a version 7
/// `.ai` as the legacy `.ai`, and a `.ai` or `.ait` with `pdfCompatible: false` as one saved
/// without PDF content.
fn written_as(cmd: &str, f: &Format, p: &Value) -> Format {
if f.id == "ai" && super::legacy_ai::wanted(cmd, f, p).unwrap_or(false) {
super::legacy_ai::named(f)
} else if matches!(f.id, "ai" | "ait") && !bool_or(p, "pdfCompatible", true) {
without_pdf(f)
} else {
*f
}
}
/// `e`, an error of the export encoders, under the save command `cmd` instead of
/// `document.export`.
fn named_for_save(cmd: &str, e: crate::EngineError) -> crate::EngineError {
@@ -596,8 +616,9 @@ struct AiEditingData {
editing_data: Option<bool>,
}
/// The shared Save and Export encoder for PDF-compatible `.ai` files (and `.ait` templates, the
/// same file).
/// The shared Save and Export encoder for `.ai` files (and `.ait` templates, the same file):
/// PDF-compatible by default, without PDF content (`pdfCompatible: false`), or legacy version 7
/// `.ai` files (`aiVersion: "7"`).
pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Encoded> {
if super::legacy_ai::wanted(cmd, f, p)? {
return super::legacy_ai::encode(cmd, f, doc, p);
@@ -616,8 +637,9 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
}
}
}
let native_options = super::native::ai_options(cmd, f, doc, &params)?;
let pdf_compatible = bool_or(&params, "pdfCompatible", true);
let f = &if pdf_compatible { *f } else { without_pdf(f) };
let native_options = super::native::ai_options(cmd, f, doc, &params)?;
if !pdf_compatible {
let picked: ArtboardPick = super::encode::options(f, &params)?;
let picked = picked.resolve(doc.artboards.len()).map_err(|e| bad(cmd, e))?;
@@ -127,6 +127,45 @@ fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() {
assert!(result["warnings"].to_string().contains("`ZZ` (1)"), "{result}");
}
#[test]
fn a_differing_object_keeps_the_layers_with_a_note() {
let square = |cmyk: &str, x: f64| format!("{cmyk} k\n{}f\n", ai::rect(x, 40.0, x + 16.0, 56.0));
let front = square("0 0 0 1", 90.0) + &square("0 0 1 0", 160.0);
let data = ai::editing_data(200.0, 100.0, &(ai::layer("Back", &square("0 0 1 0", 20.0)) + &ai::layer("Front", &front)));
let page = "0 0 1 0 k 20 40 16 16 re f 1 0 0 0 k 90 40 16 16 re f 0 0 1 0 k 160 40 16 16 re f";
let mut session = Session::new();
let result = open(&mut session, "differs.ai", &ai::ai(&compressed(data.as_bytes()), page), json!({})).unwrap();
let doc = &session.doc().unwrap().doc;
assert_eq!(names(&doc.layers), ["Back", "Front"], "{result}");
let front = doc.layers[1].children().unwrap();
assert!(matches!(front[0].kind, NodeKind::Group { .. }) && matches!(front[1].kind, NodeKind::Path { .. }), "{result}");
let replacement = &front[0].children().unwrap()[0];
assert!(
matches!(replacement.appearance.items.first(), Some(vectorcraft_doc::AppearanceItem::Fill(fill))
if fill.paint == vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0))),
"{result}"
);
assert!(
result["warnings"].to_string().contains("objects that drew differently from the file's own page came in as its art: Front (1)"),
"{result}"
);
// An export to the file's own path is refused unless it is given `acknowledgeLoss`.
let d = std::env::temp_dir().join(format!("vc-aidiffers-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let path = d.join("differs.ai");
let file = ai::ai(&compressed(data.as_bytes()), page);
std::fs::write(&path, &file).unwrap();
let path = path.to_string_lossy().to_string();
let mut s = Session::new();
s.execute("document.open", &json!({"path": path})).unwrap();
let e = s.execute("document.export", &json!({"path": path})).unwrap_err().to_string();
assert!(e.contains("left things out") && e.contains("objects that drew differently"), "{e}");
assert_eq!(std::fs::read(&path).unwrap(), file);
s.execute("document.export", &json!({"path": path, "acknowledgeLoss": true})).unwrap();
assert_ne!(std::fs::read(&path).unwrap(), file);
std::fs::remove_dir_all(d).ok();
}
/// A palette of three swatches and a color group `Inks` holding a fourth.
const INKS_PALETTE: &str = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\n0.04 0.3 0 0 81.96 21 -8 (Pink ink) 0 2 Xx\n(Pink ink)\nPc\n\
0.06 0.98 1 0 (Red ink) 0 x\n(Red ink)\nPc\n1 (Inks) 1 Pg\n0.02 0.1 1 0 (Yellow ink) 0 x\n(Yellow ink)\nPc\nPB\n%AI5_EndPalette\n";
-1
View File
@@ -439,7 +439,6 @@ pub const UNCHECKED: &[&str] = &[
"shape.flare",
"shape.polarGrid",
"shape.rectangularGrid",
"stroke.set",
"stroke.setAdvanced",
"swatch.edit",
"swatch.library.load",
+2 -1
View File
@@ -338,8 +338,9 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
Cow::Owned(doc) => doc,
};
let mut need: Vec<PlacedDocument> = vec![];
let mut seen = std::collections::HashSet::new();
doc.visit_placed(|_, p| {
if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && !need.iter().any(|n| n.key == p.key) {
if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && seen.insert(p.key.clone()) {
need.push(p.clone());
}
});
+1 -1
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\"} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
+35 -4
View File
@@ -13,6 +13,7 @@ use serde_json::{Value, json};
use vectorcraft_color::libraries::{BuiltinLibrary, GRADIENT_LIBRARIES, SWATCH_LIBRARIES, builtin_library};
use vectorcraft_color::palette_io::{self, PaletteFormat};
use vectorcraft_color::recolor::Palette;
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
use vectorcraft_doc::pattern::pattern_paint;
@@ -587,8 +588,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> {
/// ungrouped): a group's name brings the group, a swatch's name the swatch alone; no names, all.
fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec<(Option<&'a str>, &'a Swatch)>> {
let mut out: Vec<(Option<&str>, &Swatch)> = vec![];
let mut seen: HashSet<&str> = HashSet::new();
let mut push = |g: Option<&'a str>, w: &'a Swatch| {
if !out.iter().any(|(_, x)| x.name == w.name) {
if seen.insert(w.name.as_str()) {
out.push((g, w));
}
};
@@ -606,6 +608,23 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result<Vec
Ok(out)
}
/// Every name a swatch or colour group of `d` uses (they share one namespace, with the registration swatch).
fn taken_names(d: &vectorcraft_doc::Document) -> HashSet<String> {
let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name));
names.cloned().chain([REGISTRATION.to_string()]).collect()
}
/// [`vectorcraft_doc::Document::free_swatch_name`] against `taken`, which takes the name returned.
fn free_in(taken: &mut HashSet<String>, base: &str) -> String {
let name = if taken.contains(base) {
(2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n)).unwrap_or_else(|| base.to_string())
} else {
base.to_string()
};
taken.insert(name.clone());
name
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.add";
let (info, lib) = library_param(s, p, C)?;
@@ -621,11 +640,21 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// same pattern) are reused, not added again.
let patterns = patternlib::library_doc(&info.id);
let d = &s.doc()?.doc;
// The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked
// up once so that a large palette takes linear time.
let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new();
for w in d.swatches_iter() {
by_name.entry(w.name.as_str()).or_insert(w);
}
let there = |w: &Swatch| match (&w.paint, &patterns) {
(Paint::Pattern { pattern, .. }, Some(src)) => {
patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &target))
}
_ => d.swatch(&w.name).is_some_and(|x| x.paint == w.paint).then(|| w.name.clone()),
_ => match by_name.get(w.name.as_str()) {
Some(x) => x.paint == w.paint,
None => w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == w.paint),
}
.then(|| w.name.clone()),
};
// Library name → the name of the document's swatch.
let mut existing: Vec<(String, String)> = vec![];
@@ -647,6 +676,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// already had, or one made here.
let before = d.swatch_groups.len();
let mut placed: Vec<(&str, usize)> = vec![];
let mut taken = taken_names(d);
for (group, w) in fresh {
if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
// The pattern comes with its swatch; a pattern the document has without one
@@ -661,9 +691,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
};
out.push((w.name.clone(), name));
taken = taken_names(d);
continue;
}
let name = d.free_swatch_name(&w.name);
let name = free_in(&mut taken, &w.name);
let sw = Swatch { name: name.clone(), ..(*w).clone() };
match group {
Some(g) => {
@@ -671,7 +702,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let i = match found.or_else(|| d.swatch_groups.iter().take(before).position(|x| x.name == *g)) {
Some(i) => i,
None => {
let name = d.free_swatch_name(g);
let name = free_in(&mut taken, g);
d.swatch_groups.push(SwatchGroup { name, swatches: vec![] });
d.swatch_groups.len() - 1
}
+15
View File
@@ -335,6 +335,21 @@ fn character_style_color_and_features_are_checked() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn text_style_rejects_doubly_signed_feature_tags() {
let (mut s, id) = session_with_text("Text");
let before = runs(&s, id);
let undo = s.doc().unwrap().history.undo.len();
for cmd in ["text.setStyle", "text.setRangeStyle"] {
for tag in ["--liga", "+-dnom", "-+ss01", "++liga"] {
let error = s.execute(cmd, &json!({"id": id, "start": 0, "end": 4, "features": [tag]})).unwrap_err().to_string();
assert!(error.contains(&format!("`{tag}`")), "{cmd}: {error}");
}
}
assert_eq!(runs(&s, id), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn style_paints_count_as_swatch_uses_and_gradient_stops_are_checked() {
let (mut s, _) = session_with_text("Text");
+6
View File
@@ -158,6 +158,12 @@ impl Session {
self.tool_set_since_reset = false;
}
/// Finish the tool's pending work and give it fresh state, as a switch to another document
/// does, while the current document stays the same (a switch to another view of it).
pub fn reset_tool(&mut self) {
self.reset_tool_for_doc_switch();
}
pub fn set_active(&mut self, index: usize) -> bool {
if index < self.docs.len() {
if self.active != Some(index) {
+25
View File
@@ -93,6 +93,31 @@ fn the_default_stays_pdf_compatible_and_other_versions_are_refused() {
assert_eq!(v["options"]["aiVersion"]["value"], "pdf", "{v}");
}
#[test]
fn errors_name_the_legacy_ai_not_the_pdf_compatible_one() {
let mut s = three_boards();
for (cmd, p) in [
("file.saveCopy", json!({"format": "ai", "aiVersion": "7", "artboard": "2"})),
("document.export", json!({"format": "ai", "aiVersion": "7", "range": 2})),
] {
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains("legacy .ai (version 7) options: invalid type") && !e.contains("PDF-compatible"), "{cmd}: {e}");
}
// Version 7 writes a legacy .ai whatever pdfCompatible says, and its errors and notes name it.
let e = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "pdfCompatible": false, "artboard": "2"})).unwrap_err().to_string();
assert!(e.contains("legacy .ai (version 7) options: invalid type"), "{e}");
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "artboard": 1, "version": 3})).unwrap();
assert!(r["warnings"].to_string().contains("`version` was not used: legacy .ai (version 7) files don't read it"), "{r}");
// Several artboards are several files, which one encoded file can't hold.
let d = &s.doc().unwrap().doc;
let e = crate::cmd::fileio::encode_with_warnings(d, "ai", &json!({"aiVersion": "7"})).unwrap_err().to_string();
assert!(e.contains("legacy .ai (version 7) writes one file per artboard here") && !e.contains("PDF-compatible"), "{e}");
assert!(crate::cmd::fileio::encode_with_warnings(d, "ai", &json!({"aiVersion": "7", "artboard": 2})).is_ok());
// The PDF-compatible file keeps its name.
let e = s.execute("document.export", &json!({"format": "ai", "includeLinked": "yes"})).unwrap_err().to_string();
assert!(e.contains("PDF-compatible .ai options: invalid type") && !e.contains("legacy"), "{e}");
}
#[test]
fn transparency_and_appearances_are_written_as_plain_art_and_type_as_text() {
let mut s = Session::new();
+47
View File
@@ -1948,6 +1948,53 @@ fn select_same_font_size_and_fill() {
assert!(s.execute("select.same.fontSize", &json!({})).is_err());
}
/// The font Same commands take their reference from the first selected type that can be selected:
/// type that is hidden or locked inside a selected group, on a template layer, or outside the
/// isolated group is passed over.
#[test]
fn select_same_font_skips_type_that_cannot_be_selected() {
let mut s = session();
let typed =
|s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap());
let hid = typed(&mut s, 20.0, "Arial");
let courier = typed(&mut s, 60.0, "Courier");
let arial = typed(&mut s, 100.0, "Arial");
let other_courier = typed(&mut s, 140.0, "Courier");
sel(&mut s, &[hid, courier]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap());
let on_template = typed(&mut s, 180.0, "Courier");
s.execute("layer.setProps", &json!({"id": l2.0, "template": true})).unwrap();
// Hidden or locked type inside the selected group is not the reference.
for (on, off) in [
(json!({"id": hid.0, "visible": false}), json!({"id": hid.0, "visible": true})),
(json!({"id": hid.0, "locked": true}), json!({"id": hid.0, "locked": false})),
] {
s.execute("layer.setProps", &on).unwrap();
sel(&mut s, &[g]);
assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2, "{on}");
assert_eq!(selected(&s), vec![courier, other_courier], "{on}");
s.execute("layer.setProps", &off).unwrap();
}
// Type on a template layer, selected by id, is not the reference.
sel(&mut s, &[on_template, arial]);
s.execute("select.same.fontFamily", &json!({})).unwrap();
assert_eq!(selected(&s), vec![hid, arial]);
// Type outside the isolated group is not the reference.
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[arial, courier]);
s.execute("select.same.fontFamily", &json!({})).unwrap();
assert_eq!(selected(&s), vec![courier]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// A selection whose only type cannot be selected has no reference.
for id in [hid, courier] {
s.execute("layer.setProps", &json!({"id": id.0, "visible": false})).unwrap();
}
sel(&mut s, &[g]);
assert!(s.execute("select.same.fontFamily", &json!({})).is_err());
assert_eq!(selected(&s), vec![g]);
}
/// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke
/// both match the first character of the selected type: the same fill with another stroke, or the
/// same stroke with another fill, is left out, and in type with several runs one run has to match
+21
View File
@@ -74,6 +74,27 @@ fn an_unknown_key_is_named_with_the_nearest_accepted_one() {
assert!(check_keys("x", "{a, …as file.new}", &json!({"b": 1})).is_err());
}
/// `stroke.set` names every key it reads (its own, `item`, and `ids`/`id`/`target`), so a
/// misnamed one is refused instead of answering `objects: 1` with nothing changed.
#[test]
fn stroke_set_refuses_an_unknown_key() {
assert!(!UNCHECKED.contains(&"stroke.set"));
let e = refusal("stroke.set", json!({"ids": [7], "width": 0.5}));
assert!(e.starts_with("unknown parameter `width`") && e.contains("weight"), "{e}");
for ok in [
json!({"ids": [7], "weight": 0.5}),
json!({"id": 7, "weight": 1, "cap": "round", "join": "bevel", "miterLimit": 4, "align": "inside"}),
json!({"dash": [6, 3], "dashOffset": 1, "alignDashes": true, "startArrow": "Arrow", "endArrow": null, "arrowAlign": "tip"}),
json!({"profile": "lens", "item": null, "target": "contents"}),
// `item_target` reads `aligned` for an explicit item.
json!({"item": 1, "aligned": true, "weight": 2}),
// What document.inspect reports in strokeOptions reads back unchanged.
json!({"widthPoints": null, "gradientMode": "within"}),
] {
assert!(check_params("stroke.set", &ok).is_ok(), "{ok}");
}
}
/// A command that takes the keys of one that isn't checked yet isn't checked either.
#[test]
fn a_reference_to_an_unchecked_command_is_unchecked() {
+27
View File
@@ -217,6 +217,33 @@ fn ai_without_pdf_content_and_compression() {
assert!(loose.len() > packed.len(), "{} vs {}", loose.len(), packed.len());
}
#[test]
fn ai_option_errors_name_a_file_saved_without_pdf_content() {
let mut s = three_boards();
for p in
[json!({"format": "ai", "pdfCompatible": false, "artboard": "2"}), json!({"format": "ai", "pdfCompatible": false, "includeLinked": "yes"})]
{
let e = s.execute("file.saveCopy", &p).unwrap_err().to_string();
assert!(e.contains("non-PDF-compatible .ai options: invalid type"), "{p}: {e}");
}
let e = s.execute("document.export", &json!({"format": "ai", "pdfCompatible": false, "artboard": "2"})).unwrap_err().to_string();
assert!(e.contains("`document.export`") && e.contains("non-PDF-compatible .ai options: invalid type"), "{e}");
let p = json!({"format": "ait", "pdfCompatible": false, "includeLinked": "yes"});
let e = s.execute("file.saveAsTemplate", &p).unwrap_err().to_string();
assert!(e.contains("non-PDF-compatible .ait template options: invalid type"), "{e}");
// A template saved without PDF content is written.
let r = s.execute("file.saveAsTemplate", &json!({"format": "ait", "pdfCompatible": false})).unwrap();
assert!(r["warnings"].to_string().contains("without PDF content"), "{r}");
// So are the notes on native options the file doesn't read.
let r = s.execute("file.saveCopy", &json!({"format": "ai", "pdfCompatible": false, "version": 3})).unwrap();
assert!(r["warnings"].to_string().contains("`version` was not used: non-PDF-compatible .ai files don't read it"), "{r}");
// A PDF-compatible file keeps its name.
let e = s.execute("file.saveCopy", &json!({"format": "ai", "includeLinked": "yes"})).unwrap_err().to_string();
assert!(e.contains("PDF-compatible .ai options: invalid type") && !e.contains("non-PDF"), "{e}");
let r = s.execute("file.saveCopy", &json!({"format": "ai", "version": 3})).unwrap();
assert!(r["warnings"].to_string().contains("`version` was not used: PDF-compatible .ai files don't read it"), "{r}");
}
#[test]
fn a_remembered_artboard_the_document_no_longer_has_is_dropped() {
let dir = Folder::new("remembered-artboards");
+148 -7
View File
@@ -1,8 +1,8 @@
use super::compare::{MAX_DIFFERENCE, PageView, compare, difference};
use super::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, compare, difference};
use super::plan::{made_only, make_slots, plan, readable_all};
use super::slots::{
ART_LEFT_OUT, Content, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, extent, few,
fill_slots, letters, text_objects, words,
ART_LEFT_OUT, Content, DREW_DIFFERENTLY, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots,
extent, few, fill_slots, letters, text_objects, words,
};
use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai};
@@ -345,10 +345,22 @@ pub(super) fn build_from(
doc = other;
notes.extend(unseen_note(unseen).into_iter().chain(note));
}
_ => {
let more = drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, &notes, unseen, trust, why, reflow)?;
notes.extend(more);
}
other => match drawn_or_trusted(&frame, &mut view, &mut doc, &envelopes_drawn, &notes, unseen, trust, why, reflow) {
Ok(more) => notes.extend(more),
// The objects that draw differently from the page come in as its art, from
// the placement that draws closer to it.
Err(why) => {
let other = other.map(|(_, other, unseen)| (other, unseen));
let placements = closer_first(&frame, &mut view, (doc, unseen), other, reflow);
let Some((kept, unseen, kept_notes)) = placements.into_iter().find_map(|(base, unseen)| {
keep_differing(&base, &frame, &mut view, &threaded_frames, &shown, reflow).map(|(kept, n)| (kept, unseen, n))
}) else {
return Err(why);
};
doc = kept;
notes.extend(unseen_note(unseen).into_iter().chain(kept_notes));
}
},
},
}
}
@@ -770,6 +782,135 @@ fn replace_unread(
Ok(counts.into_iter().map(|(kind, count)| format!("{kind} ({count})")).collect())
}
/// Most objects of the layers that come in as the page's art where they draw differently from it.
const MAX_DIFFERING: usize = 64;
/// Most pairs of a patch where the layers and the page differ and a top-level object that may hold
/// it, weighed to find the objects that come in as the page's art.
const MAX_PATCH_PAIRS: usize = 4_000_000;
/// The layers as read and at the placed files' other placement (each with its count of text
/// objects the page doesn't draw), the one that draws closer to the page first. `reflow` as in
/// [`PageView::difference`].
fn closer_first(
frame: &Frame<'_>,
view: &mut PageView,
doc: (Document, usize),
other: Option<(Document, usize)>,
reflow: bool,
) -> Vec<(Document, usize)> {
match other {
Some(other) if view.difference(&other.0, frame.rect, reflow).any < view.difference(&doc.0, frame.rect, reflow).any => vec![other, doc],
Some(other) => vec![doc, other],
None => vec![doc],
}
}
/// `doc`, whose layers draw differently from the page (an object in another color, or one that only
/// one of them draws), with each of its top-level objects that holds such a difference replaced by the
/// page's art in its bounds, when that makes the two look alike → the document and its notes: the
/// comparison's, and how many objects were replaced on each layer (by name, in the layers' order).
/// `None` when only edges or type differ, a difference lies outside every object, more than half
/// of the objects (or more than [`MAX_DIFFERING`]) hold one, one of them holds type or a wrap
/// object, the page's art can't replace one of them ([`replace_unread`]), the page's type of a text
/// object that stays is copied into a replacement, or the two still differ. `shown` is the page's
/// type of each text object that shows. `reflow` as in [`PageView::difference`].
fn keep_differing(
doc: &Document,
frame: &Frame<'_>,
view: &mut PageView,
threaded_frames: &BTreeSet<NodeId>,
shown: &[Vec<Arc<Node>>],
reflow: bool,
) -> Option<(Document, Vec<String>)> {
/// The top-level objects that show and print (the outermost objects under a layer or
/// sublayer), with the name of that layer or sublayer as the Layers panel shows it and their
/// bounds.
fn top_level(nodes: &[Arc<Node>], layer: &str, out: &mut Vec<(String, NodeId, Rect)>) {
for n in nodes.iter().filter(|n| n.visible) {
match &n.kind {
NodeKind::Layer { printable: false, .. } => {}
NodeKind::Layer { .. } => {
let name = Some(n.display_name()).filter(|name| !name.is_empty()).unwrap_or_else(|| format!("<{}>", n.kind_label()));
top_level(n.children().map_or(&[], Vec::as_slice), &name, out);
}
NodeKind::Path { guide: true, .. } => {}
_ => {
if let Some(b) = n.visual_bounds().filter(|b| b.area().is_finite() && b.area() > 0.0) {
out.push((layer.to_string(), n.id, b));
}
}
}
}
}
// Where only spread edges or type differ, or only the art around the page, no object is
// replaced.
let (diff, regions) = view.solid_regions(doc, frame.rect, reflow)?;
if diff.solid <= MAX_SOLID_DIFFERENCE {
return None;
}
let mut objects = vec![];
top_level(&doc.layers, "", &mut objects);
objects.retain(|(_, _, b)| !b.intersect(frame.rect).is_zero_area());
if regions.len().saturating_mul(objects.len()) > MAX_PATCH_PAIRS {
return None;
}
// Each patch is the smallest object's that holds it.
let most = MAX_DIFFERING.min(objects.len() / 2);
let mut targets = BTreeSet::new();
for region in regions {
let (_, id, _) = objects.iter().filter(|(_, _, b)| inside(region, *b)).min_by(|a, b| a.2.area().total_cmp(&b.2.area()))?;
targets.insert(*id);
if targets.len() > most {
return None;
}
}
if targets.is_empty() {
return None;
}
// A replaced wrap object keeps its wrap options, and the area type is wrapped around the page's
// art that replaces it. An object inside a replaced group can't keep them, so such a group isn't
// replaced. Neither is an object that holds type: the page's art that replaces it would hold
// type the page draws for other text objects too.
let mut wraps = vec![];
for id in &targets {
let node = doc.node(*id)?;
let mut held = matches!(node.kind, NodeKind::Text(_));
for child in node.children().into_iter().flatten() {
child.walk(&mut |n| held |= n.extras().wrap.is_some() || matches!(n.kind, NodeKind::Text(_)));
}
if held {
return None;
}
if let Some(wrap) = node.extras().wrap {
wraps.push((*id, wrap));
}
}
let mut kept = doc.clone();
let replace: Vec<(NodeId, Vec<String>)> = targets.iter().map(|id| (*id, vec![])).collect();
let mut copied = BTreeSet::new();
replace_unread(&mut kept, frame, &replace, &[], threaded_frames, &mut copied).ok()?;
// A text object that stays draws its page type, so a copy of that type would draw it twice.
if shown.iter().flatten().any(|n| copied.contains(&n.id)) {
return None;
}
for (id, wrap) in wraps {
kept.node_mut(id)?.extras_mut().wrap = Some(wrap);
}
resolve_text_wrap(&mut kept).ok()?;
let note = compare(frame, view, &kept, reflow).ok()?;
let mut layers: Vec<(String, usize)> = vec![];
for (layer, _, _) in objects.iter().filter(|(_, id, _)| targets.contains(id)) {
match layers.iter_mut().find(|(name, _)| name == layer) {
Some((_, count)) => *count += 1,
None => layers.push((layer.clone(), 1)),
}
}
let layers: Vec<String> = layers.into_iter().map(|(layer, count)| format!("{layer} ({count})")).collect();
Some((kept, note.into_iter().chain([format!("{DREW_DIFFERENTLY}: {}", layers.join(", "))]).collect()))
}
/// Copy page drawing IDs, including mask art outside the ordinary child tree.
fn reid_page_art(doc: &mut Document, source: &Node) -> Node {
let mut copy = doc.reid(source);
+75 -7
View File
@@ -182,6 +182,12 @@ impl PageView {
let printed = as_printed(b);
let b = printed.as_ref().unwrap_or(b);
let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples);
let areas = self.counted_type(b, rb, reflow);
compared(&self.page, &y, &areas, &self.restyled)
}
/// Where [`Self::difference`] counts `b`'s and the page's pixels as type, in the page's pixels.
fn counted_type(&self, b: &Document, rb: Rect, reflow: bool) -> Vec<Rect> {
let mut areas = vec![];
type_areas(&b.layers, rb, self.scale, &mut areas);
if reflow {
@@ -194,7 +200,7 @@ impl PageView {
} else {
areas.extend(&self.page_type);
}
compared(&self.page, &y, &areas, &self.restyled)
areas
}
/// The share (0 to 1) of the pixels where `b` on `rb` draws another colour than the page
@@ -210,6 +216,52 @@ impl PageView {
let differing = self.page.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).filter(|(p, q)| differ_in_colour(p, q)).count();
differing as f64 / (f64::from(y.width) * f64::from(y.height)).max(1.0)
}
/// How `b` on `rb` draws differently from the page ([`Self::difference`]), and the boxes (in
/// `b`'s terms) around each patch of the pixels counted in its `solid` share (they and all
/// their neighbors differ, away from type), neighbors touching corner to corner counting as one patch. `None` when the two
/// drawings aren't the same size.
pub(super) fn solid_regions(&mut self, b: &Document, rb: Rect, reflow: bool) -> Option<(Difference, Vec<Rect>)> {
let printed = as_printed(b);
let b = printed.as_ref().unwrap_or(b);
let y = comparison_render(&mut self.layers, b, rb, self.scale, self.samples);
let areas = self.counted_type(b, rb, reflow);
let (diff, mut solid) = compared_with_solid(&self.page, &y, &areas, &self.restyled);
let (w, h) = (y.width as usize, y.height as usize);
if solid.len() != w * h {
return None;
}
let mut regions = vec![];
let mut stack = vec![];
for start in 0..solid.len() {
if !solid.get(start).copied().unwrap_or(false) {
continue;
}
// The patch's pixels are cleared as they are taken, so each is taken once.
if let Some(s) = solid.get_mut(start) {
*s = false;
}
stack.push(start);
let (mut i0, mut j0, mut i1, mut j1) = (start % w, start / w, start % w, start / w);
while let Some(k) = stack.pop() {
let (i, j) = (k % w, k / w);
(i0, j0, i1, j1) = (i0.min(i), j0.min(j), i1.max(i), j1.max(j));
for n in j.saturating_sub(1)..=(j + 1).min(h - 1) {
for m in i.saturating_sub(1)..=(i + 1).min(w - 1) {
if let Some(s) = solid.get_mut(n * w + m).filter(|s| **s) {
*s = false;
stack.push(n * w + m);
}
}
}
}
let s = self.scale;
let at = |i: usize, j: usize| (rb.x0 + i as f64 / s, rb.y0 + j as f64 / s);
let ((x0, y0), (x1, y1)) = (at(i0, j0), at(i1 + 1, j1 + 1));
regions.push(Rect::new(x0, y0, x1, y1));
}
Some((diff, regions))
}
}
/// How `a` on `ra` and `b` on `rb` (rectangles of the same size) draw differently ([`compared`]),
@@ -233,8 +285,14 @@ pub(super) fn difference(a: &Document, ra: Rect, b: &Document, rb: Rect) -> Diff
/// at all ([`differ`]): the page of an RGB document is written in the colours' CMYK equivalents,
/// and what the comparison looks for is art that is missing or out of place.
pub(super) fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> Difference {
compared_with_solid(x, y, areas, skip).0
}
/// [`compared`], and which of the pixels (row by row) are counted in its `solid` share: none when
/// the drawings can't be compared.
fn compared_with_solid(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect], skip: &[Rect]) -> (Difference, Vec<bool>) {
if x.width == 0 || x.height == 0 || x.width != y.width || x.height != y.height {
return Difference { any: 1.0, art: 1.0, solid: 1.0 };
return (Difference { any: 1.0, art: 1.0, solid: 1.0 }, vec![]);
}
let (w, h) = (x.width as usize, x.height as usize);
// Pixels in `skip` count as alike.
@@ -245,12 +303,22 @@ pub(super) fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render:
let typed = in_areas(areas, w, h);
let art = differs.iter().zip(&typed).filter(|(d, t)| **d && !**t).count();
// A pixel on the region's edge has neighbours outside it, which don't count as differing.
let solid = (1..h.saturating_sub(1))
.flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j)))
.filter(|&(i, j)| !typed.get(j * w + i).copied().unwrap_or(true) && (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n))))
.count();
let mut solid = vec![false; w * h];
for (i, j) in (1..h.saturating_sub(1)).flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j))) {
if !typed.get(j * w + i).copied().unwrap_or(true)
&& (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n)))
&& let Some(s) = solid.get_mut(j * w + i)
{
*s = true;
}
}
let area = (w as f64 * h as f64).max(1.0);
Difference { any: differs.iter().filter(|d| **d).count() as f64 / area, art: art as f64 / area, solid: solid as f64 / area }
let shares = Difference {
any: differs.iter().filter(|d| **d).count() as f64 / area,
art: art as f64 / area,
solid: solid.iter().filter(|s| **s).count() as f64 / area,
};
(shares, solid)
}
/// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin
+7 -1
View File
@@ -18,6 +18,10 @@ pub(super) const PAGE_TYPE_UNCHECKED: &str =
pub(super) const LAYERS_UNREAD: &str = "the file's layers weren't read";
/// Objects of the layers replaced with the page's art where they drew differently from it,
/// followed by the layers they are on.
pub(super) const DREW_DIFFERENTLY: &str = "objects that drew differently from the file's own page came in as its art";
/// Does this import note say that the file has something the document doesn't (hidden text, art or
/// layers that could not be read, or the page's type that no text object takes or may not take)?
/// Writing the document over the file would lose it for good.
@@ -27,7 +31,9 @@ pub fn is_loss(note: &str) -> bool {
|| note.ends_with("they came in as the page's art")
|| note == PAGE_TYPE_LEFT_OUT
|| note == PAGE_TYPE_UNCHECKED
|| [ART_LEFT_OUT, LAYERS_UNREAD, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY].iter().any(|n| note.starts_with(n))
|| [ART_LEFT_OUT, LAYERS_UNREAD, DREW_DIFFERENTLY, crate::import::graphics::TOO_MUCH, crate::import::graphics::FAR_AWAY]
.iter()
.any(|n| note.starts_with(n))
}
/// Most text objects in the layers, and most pieces of type in one place on the page, that are matched
+209
View File
@@ -824,6 +824,215 @@ fn top_level_placed_file_without_page_art_falls_back() {
assert!(notes.iter().any(|n| n.contains("page art wasn't found")), "{notes:?}");
}
const BLACK: &str = "0 0 0 1";
const YELLOW: &str = "0 0 1 0";
const PAGE_CYAN: [f32; 4] = [1.0, 0.0, 0.0, 0.0];
const PAGE_YELLOW: [f32; 4] = [0.0, 0.0, 1.0, 0.0];
/// A square of 16 points at (`x`, 10) in the format's operators, painted in CMYK `cmyk`.
fn square_16(x: u32, cmyk: &str) -> String {
format!("{cmyk} k\n{x} 10 m\n{} 10 L\n{} 26 L\n{x} 26 L\nf", x + 16, x + 16)
}
/// A 100 × 100 page with a square of 16 points at each (`x`, `y`, CMYK) of `squares`: at `y` 74
/// where [`square_16`] puts the layers' squares.
fn page_16(squares: &[(f64, f64, [f32; 4])]) -> Document {
let mut d = Document::new(100.0, 100.0);
let layer = d.layers[0].id;
for (i, (x, y, [c, m, ye, k])) in squares.iter().enumerate() {
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(*x, *y, x + 16.0, y + 16.0));
let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(*c, *m, *ye, *k));
let item = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint));
let n = Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance { items: vec![item], ..Default::default() });
d.insert(Some(layer), i, n).unwrap();
}
d
}
/// Three squares on two layers, the middle one black in the layers and cyan on the page.
fn middle_differs() -> (String, Document) {
let front = format!("{}\n{}", square_16(40, BLACK), square_16(76, YELLOW));
let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("Front", true, &front)));
(art, page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_YELLOW)]))
}
#[test]
fn an_object_that_draws_differently_comes_in_as_the_page_art() {
let (art, page) = middle_differs();
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(read, "{notes:?}");
assert_eq!(names(&doc), ["Back", "Front"]);
assert_eq!(kinds(&doc.layers[0]), ["path"]);
assert_eq!(kinds(&doc.layers[1]), ["group[1]", "path"]);
replacement_is_cyan(&doc, 1, 0);
let note = "objects that drew differently from the file's own page came in as its art: Front (1)";
assert!(notes.iter().any(|n| n == note && crate::is_loss(n)), "{notes:?}");
assert!(!notes.iter().any(|n| n.contains("weren't read")), "{notes:?}");
}
#[test]
fn two_differing_objects_on_different_layers_are_both_replaced() {
let back = format!("{}\n{}", square_16(4, BLACK), square_16(28, YELLOW));
let front = format!("{}\n{}", square_16(52, YELLOW), square_16(76, BLACK));
let art = native(&(layer("Back", true, &back) + &layer("Front", true, &front)));
let page = page_16(&[(4.0, 74.0, PAGE_CYAN), (28.0, 74.0, PAGE_YELLOW), (52.0, 74.0, PAGE_YELLOW), (76.0, 74.0, PAGE_CYAN)]);
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(read, "{notes:?}");
assert_eq!(names(&doc), ["Back", "Front"]);
assert_eq!(kinds(&doc.layers[0]), ["group[1]", "path"]);
assert_eq!(kinds(&doc.layers[1]), ["path", "group[1]"]);
replacement_is_cyan(&doc, 0, 0);
replacement_is_cyan(&doc, 1, 1);
let note = "objects that drew differently from the file's own page came in as its art: Back (1), Front (1)";
assert!(notes.iter().any(|n| n == note), "{notes:?}");
}
/// The text wrap options of a 2-point offset, for the object before them.
const WRAP_OPTIONS: &str = "%_/ArtDictionary :\n%_0 /Bool (AI11TextWrapInvert) ,\n%_2 /Real (AI11TextWrapOffset) ,\n%_;\n%_\n";
#[test]
fn a_differing_wrap_object_keeps_its_wrap_options() {
let front = format!("{}\n{WRAP_OPTIONS}{}", square_16(40, BLACK), square_16(76, YELLOW));
let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("Front", true, &front)));
let page = page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_YELLOW)]);
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(read, "{notes:?}");
assert_eq!(kinds(&doc.layers[1]), ["group[1]", "path"]);
replacement_is_cyan(&doc, 1, 0);
let group = &doc.layers[1].children().unwrap()[0];
assert_eq!(group.extras().wrap, Some(vectorcraft_doc::TextWrap { offset: 2.0, invert: false }));
}
#[test]
fn a_differing_group_holding_a_wrap_object_still_falls_back() {
let group = os1_group(&format!("{}\n{WRAP_OPTIONS}", square_16(40, BLACK)));
let front = format!("{group}\n{}", square_16(76, YELLOW));
let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("Front", true, &front)));
let page = page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_YELLOW)]);
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(!read, "{notes:?}");
assert_eq!(names(&doc), ["Layer 1"]);
assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}");
}
#[test]
fn a_page_that_differs_everywhere_still_comes_in_as_its_pdf_part() {
let front = format!("{}\n{}", square_16(40, BLACK), square_16(76, BLACK));
let art = native(&(layer("Back", true, &square_16(4, BLACK)) + &layer("Front", true, &front)));
let page = page_16(&[(4.0, 74.0, PAGE_CYAN), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_CYAN)]);
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(!read, "{notes:?}");
assert_eq!(names(&doc), ["Layer 1"]);
assert!(notes.iter().any(|n| n.contains("weren't read") && n.contains("differs from the page's")), "{notes:?}");
assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}");
}
#[test]
fn a_page_object_outside_every_layer_object_still_falls_back() {
let front = format!("{}\n{}", square_16(40, YELLOW), square_16(76, YELLOW));
let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("Front", true, &front)));
let page = page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_YELLOW), (76.0, 74.0, PAGE_YELLOW), (40.0, 20.0, PAGE_CYAN)]);
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(!read, "{notes:?}");
assert_eq!(names(&doc), ["Layer 1"]);
assert!(notes.iter().any(|n| n.contains("differs from the page's")), "{notes:?}");
}
#[test]
fn a_differing_object_with_live_art_inside_falls_back() {
// The group reaches over the square between its own two.
let group = os1_group(&format!("{}\n{}", square_16(4, BLACK), square_16(40, YELLOW)));
let front = format!("{group}\n{}\n{}", square_16(22, YELLOW), square_16(76, YELLOW));
let art = native(&layer("Front", true, &front));
let page = page_16(&[(4.0, 74.0, PAGE_CYAN), (22.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_YELLOW), (76.0, 74.0, PAGE_YELLOW)]);
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(!read, "{notes:?}");
assert_eq!(names(&doc), ["Layer 1"]);
assert!(notes.iter().any(|n| n.contains("differs from the page's")), "{notes:?}");
}
#[test]
fn trusted_editing_data_keeps_a_differing_object() {
let (art, page) = middle_differs();
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, true, 1.0);
assert!(read, "{notes:?}");
assert_eq!(names(&doc), ["Back", "Front"]);
assert_eq!(kinds(&doc.layers[1]), ["path", "path"]);
assert!(notes.iter().any(|n| n.ends_with("they come from its editing data all the same")), "{notes:?}");
assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}");
}
#[test]
fn a_differing_object_on_an_unnamed_layer_is_counted_under_its_panel_name() {
let front = format!("{}\n{}", square_16(40, BLACK), square_16(76, YELLOW));
let art = native(&(layer("Back", true, &square_16(4, YELLOW)) + &layer("", true, &front)));
let page = page_16(&[(4.0, 74.0, PAGE_YELLOW), (40.0, 74.0, PAGE_CYAN), (76.0, 74.0, PAGE_YELLOW)]);
let (_, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(read, "{notes:?}");
let note = "objects that drew differently from the file's own page came in as its art: <Layer> (1)";
assert!(notes.iter().any(|n| n == note), "{notes:?}");
}
#[test]
fn at_most_64_differing_objects_come_in_as_the_page_art() {
// 130 squares of 4 points, the first `black` of them black in the layers and cyan on the page.
let grid = |black: usize| {
let at = |i: usize| (4 + 7 * (i % 13) as u32, 4 + 7 * (i / 13) as u32);
let art: String = (0..130)
.map(|i| {
let (x, y) = at(i);
if i < black { format!("{BLACK} k\n{}", square_path(x, y)) } else { square(x, y) }
})
.collect::<Vec<_>>()
.join("\n");
let mut page = Document::new(100.0, 100.0);
let layer_id = page.layers[0].id;
for i in 0..130 {
let (x, y) = at(i);
let (x, y) = (f64::from(x), 96.0 - f64::from(y));
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, y, x + 4.0, y + 4.0));
let color =
if i < black { vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0) } else { vectorcraft_color::Color::cmyk(0.0, 0.0, 1.0, 0.0) };
let item = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(vectorcraft_color::Paint::solid(color)));
let n = Node::path(page.alloc_id(), path, vectorcraft_doc::Appearance { items: vec![item], ..Default::default() });
page.insert(Some(layer_id), i, n).unwrap();
}
crate::layered_ai(&private(&native(&layer("Grid", true, &art))), page, vec![], false, false, 1.0)
};
let (_, notes, read) = grid(64);
assert!(read, "{notes:?}");
let note = "objects that drew differently from the file's own page came in as its art: Grid (64)";
assert!(notes.iter().any(|n| n == note), "{notes:?}");
let (doc, notes, read) = grid(65);
assert!(!read, "{notes:?}");
assert_eq!(names(&doc), ["Layer 1"]);
assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}");
}
#[test]
fn a_differing_object_under_the_type_of_a_text_object_that_stays_falls_back() {
// A black rectangle under area type whose frame reaches past it; the page draws the rectangle
// cyan, with the type on it.
let big = format!("{BLACK} k\n10 2 m\n60 2 L\n60 40 L\n10 40 L\nf");
let doc = document_of(&[area_frame(34.0, 26.0, 95.0, 38.0)], &[story("Hi\\r", &[0], "/0 0", "/1 8.0")]);
let art = native_with_text(&(layer("Art", true, &format!("{big}\n{}", frame_object(0, 0))) + &layer("Top", true, &square_16(76, YELLOW))), &doc);
let mut page = page_16(&[(76.0, 74.0, PAGE_YELLOW)]);
let layer_id = page.layers[0].id;
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(10.0, 60.0, 60.0, 98.0));
let paint = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(1.0, 0.0, 0.0, 0.0));
let item = vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint));
let square = Node::path(page.alloc_id(), path, vectorcraft_doc::Appearance { items: vec![item], ..Default::default() });
page.insert(Some(layer_id), 0, square).unwrap();
let style = vectorcraft_doc::CharStyle { size: 8.0, ..Default::default() };
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(34.0, 69.0), "Hi", style);
let text = Node::new(page.alloc_id(), NodeKind::Text(Box::new(text)));
page.insert(Some(layer_id), 1, text).unwrap();
let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0);
assert!(!read, "{notes:?}");
assert_eq!(names(&doc), ["Layer 1"]);
assert!(!notes.iter().any(|n| n.starts_with("objects that drew")), "{notes:?}");
}
#[test]
fn unread_object_on_second_artboard_takes_second_page_art() {
let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\
+23 -1
View File
@@ -29,6 +29,11 @@ pub const EPS: f64 = 1e-9;
/// Most line segments [`flatten`] makes of one curve, whatever its size and the tolerance.
pub const MAX_FLATTEN_PER_CURVE: f64 = 4096.0;
/// A curve whose control polygon is longer than this is drawn as a line by [`flatten`]: kurbo
/// squares and cubes coordinates when it sizes its work, and with coordinates this large that
/// overflows to infinity and it reserves a buffer no machine has. (Far beyond any drawing.)
pub const MAX_FLATTEN_LENGTH: f64 = 1e60;
/// [`kurbo::flatten`], each curve's tolerance raised so that it makes at most about
/// [`MAX_FLATTEN_PER_CURVE`] segments. kurbo sizes its work and a buffer from the curve's
/// coordinates before producing anything, so a small curve with far-out handles (from a file, or
@@ -60,7 +65,14 @@ pub fn flatten(path: impl IntoIterator<Item = PathEl>, tolerance: f64, mut callb
};
last = Some(to);
let (Some(from), Some(length)) = (from, length) else { continue };
if !length.is_finite() {
// A short polygon far from the origin still overflows kurbo's `p * (mt * 2.0)` products.
let far = |p: Point| !(p.x.abs() <= MAX_FLATTEN_LENGTH && p.y.abs() <= MAX_FLATTEN_LENGTH);
let controls_far = match el {
PathEl::QuadTo(a, _) => far(a),
PathEl::CurveTo(a, b, _) => far(a) || far(b),
_ => false,
};
if length.is_nan() || length > MAX_FLATTEN_LENGTH || far(from) || far(to) || controls_far {
callback(PathEl::LineTo(to));
continue;
}
@@ -198,6 +210,16 @@ mod tests {
assert_eq!(ours, theirs);
let nan = [PathEl::MoveTo(Point::ZERO), PathEl::QuadTo(Point::new(f64::NAN, 0.0), Point::new(1.0, 1.0))];
assert_eq!(count(&nan, 0.25), 2);
// Finite coordinates whose squares overflow are a line to the end too.
let huge = [PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::new(1e200, 0.0), Point::new(-1e200, 1e200), Point::new(1.0, 0.0))];
assert_eq!(count(&huge, 0.25), 2);
// A short polygon out near f64::MAX: a line, and every point it emits is finite.
let m = f64::MAX / 2.0;
let far = [PathEl::MoveTo(Point::new(m, m)), PathEl::CurveTo(Point::new(m, m), Point::new(m, m), Point::new(m, m))];
let mut points = vec![];
flatten(far.iter().copied(), 0.25, |e| points.push(e));
assert_eq!(points.len(), 2);
assert!(points.iter().all(|e| matches!(e, PathEl::MoveTo(p) | PathEl::LineTo(p) if p.is_finite())), "{points:?}");
}
#[test]
+186 -42
View File
@@ -93,35 +93,36 @@ impl Homography {
self.inverse().is_some()
}
/// Whether every entry is finite and the determinant's magnitude is more than 1e-15 times that
/// of the largest of the six products it sums (a test that gives the same answer at any scale
/// of the map). Each product is formed as a mantissa product and an exponent sum, and all six
/// are divided by the power of two of the largest before they are summed, so the largest is at
/// least 1/8 and below 1 and none of them overflows.
/// Whether every entry is finite and [`significant_det`] holds for the map or for its
/// adjugate (the inverse times the determinant). Both tests give the same answer at any scale
/// of the map. The adjugate of the adjugate is the map times a number, so, apart from
/// rounding, a map passes when its inverse passes and fails when its inverse fails.
fn has_significant_det(&self) -> bool {
if !self.is_finite() {
return false;
}
let terms = self.det_terms();
let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else {
return false;
};
let terms = terms.map(|(m, x)| ldexp(m, x - e));
let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs()));
let d: f64 = terms.iter().sum();
d.abs() > 1e-15 * largest
significant_det(self.det_terms()) || significant_det(split_det_terms(&self.adjugate()))
}
/// The six signed products the determinant sums, each as a mantissa product and an exponent
/// sum.
fn det_terms(&self) -> [(f64, i32); 6] {
split_det_terms(&self.0.map(|row| row.map(frexp)))
}
/// The adjugate (the transposed matrix of cofactors), each entry as a mantissa and a power of
/// two. Each cofactor's two products are formed exactly before they are subtracted, so an
/// entry is within a few units in the last place of the exact cofactor of the stored numbers.
/// The entries must be finite.
fn adjugate(&self) -> [[(f64, i32); 3]; 3] {
let f = self.0.map(|row| row.map(frexp));
// The columns each of the six products takes from rows 0, 1 and 2, and its sign.
let cols = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)];
cols.map(|(a, b, c, sign)| {
let (a, b, c) = (f[0][a], f[1][b], f[2][c]);
(sign * a.0 * b.0 * c.0, a.1 + b.1 + c.1)
})
let c = |r0: usize, c0: usize, r1: usize, c1: usize| split_minor(f[r0][c0], f[r1][c1], f[r0][c1], f[r1][c0]);
let neg = |(m, e): (f64, i32)| (-m, e);
[
[c(1, 1, 2, 2), neg(c(0, 1, 2, 2)), c(0, 1, 1, 2)],
[neg(c(1, 0, 2, 2)), c(0, 0, 2, 2), neg(c(0, 0, 1, 2))],
[c(1, 0, 2, 1), neg(c(0, 0, 2, 1)), c(0, 0, 1, 1)],
]
}
/// The same map with every entry divided by one power of two, chosen so that the largest of the
@@ -162,26 +163,17 @@ impl Homography {
}
/// The adjugate divided by the determinant; `None` when an entry is not finite, the
/// determinant is 0, or the result has an entry that is not finite or a determinant of 0 (its
/// six products, each held as a mantissa and a power of two, sum to 0, as when a row underflows
/// to 0). Every cofactor and the determinant are held as a mantissa and a power of two, so an
/// entry of the result is lost only when that entry itself is beyond the range of `f64`.
/// determinant is 0, or the result has an entry that is not finite or fails
/// [`Self::has_significant_det`] (as when a row underflows to 0). Every cofactor and the
/// determinant are held as a mantissa and a power of two, so an entry of the result is lost
/// only when that entry itself is beyond the range of `f64`.
fn adjugate_inverse(&self) -> Option<Self> {
if !self.is_finite() {
return None;
}
let f = self.0.map(|row| row.map(frexp));
let mul = |a: (f64, i32), b: (f64, i32)| (a.0 * b.0, a.1 + b.1);
let c = |r0: usize, c0: usize, r1: usize, c1: usize| {
let (a, b) = (mul(f[r0][c0], f[r1][c1]), mul(f[r0][c1], f[r1][c0]));
split_sum(&[a, (-b.0, b.1)])
};
let neg = |(m, e): (f64, i32)| (-m, e);
let adj = [
[c(1, 1, 2, 2), neg(c(0, 1, 2, 2)), c(0, 1, 1, 2)],
[neg(c(1, 0, 2, 2)), c(0, 0, 2, 2), neg(c(0, 0, 1, 2))],
[c(1, 0, 2, 1), neg(c(0, 0, 2, 1)), c(0, 0, 1, 1)],
];
let adj = self.adjugate();
// The determinant expanded along the first row, as `det` sums it.
let (dm, de) = split_sum(&[mul(f[0][0], adj[0][0]), mul(f[0][1], adj[1][0]), mul(f[0][2], adj[2][0])]);
if dm == 0.0 {
@@ -195,7 +187,7 @@ impl Homography {
}
let out = Self(out);
// H⁻¹·(x, y, 1) = (u, v, 1)/w_H, so points in front of the camera keep w > 0.
(out.is_finite() && split_sum(&out.det_terms()).0 != 0.0).then_some(out)
out.has_significant_det().then_some(out)
}
/// `self ∘ other`: `other` first.
@@ -217,19 +209,31 @@ impl Homography {
c.is_finite().then_some(c)
}
/// Whether every entry of `a` is finite and the determinant of its linear part has a magnitude
/// more than 1e-15 times the larger of the two products it sums (a test that gives the same
/// answer at any scale of `a`).
pub fn affine_is_invertible(a: Affine) -> bool {
Self::from_affine(a).has_significant_det()
}
/// `self` seen through `a`: the map `a ∘ self ∘ a⁻¹` (what `self` becomes when everything it
/// maps from and to is moved by `a`). When the product overflows, every entry is formed with
/// its powers of two kept apart, and the product is returned divided by the largest magnitude
/// in its `w` row (the same map, with a `w` row whose largest entry is 1). `None` when `a`
/// isn't invertible, or when the product overflows and the result at that scale has an entry
/// that is not finite or is not invertible.
/// maps from and to is moved by `a`). When the product overflows, or underflows to a map that
/// is not invertible, every entry is formed with its powers of two kept apart, and the product
/// is returned divided by the largest magnitude in its `w` row (the same map, with a `w` row
/// whose largest entry is 1). `None` when `a` isn't invertible
/// ([`Self::affine_is_invertible`]), or when the result at that scale has an entry that is not
/// finite or is not invertible. `a⁻¹` is
/// [`Affine::inverse`] when `a`'s determinant and that inverse are finite, and
/// [`Self::inverse`] of `a` otherwise.
pub fn conjugated(&self, a: Affine) -> Option<Self> {
if a.determinant().abs() < 1e-15 {
if !Self::affine_is_invertible(a) {
return None;
}
let (to, from) = (Self::from_affine(a), Self::from_affine(a.inverse()));
let to = Self::from_affine(a);
let inv = a.inverse();
let from = if a.determinant().is_finite() && inv.is_finite() { Self::from_affine(inv) } else { to.inverse()? };
let c = to.then_after(self).then_after(&from);
if c.is_finite() {
if c.is_finite() && c.has_significant_det() {
return Some(c);
}
// Each entry of the product is a sum of nine terms to[r][i]·self[i][j]·from[j][k]. Every
@@ -299,6 +303,53 @@ fn frexp(v: f64) -> (f64, i32) {
(f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e + bias)
}
/// The six signed products the determinant of `f` sums, each as a mantissa product and an exponent
/// sum.
fn split_det_terms(f: &[[(f64, i32); 3]; 3]) -> [(f64, i32); 6] {
// The columns each of the six products takes from rows 0, 1 and 2, and its sign.
let cols = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)];
cols.map(|(a, b, c, sign)| {
let (a, b, c) = (f[0][a], f[1][b], f[2][c]);
(sign * a.0 * b.0 * c.0, a.1 + b.1 + c.1)
})
}
/// Whether the sum of the six products in `terms` has a magnitude more than 1e-15 times that of
/// the largest of them. All six are divided by the power of two of the largest before they are
/// summed, so the largest is at least 1/8 and below 1 and none of them overflows. `false` when
/// every product is 0.
fn significant_det(terms: [(f64, i32); 6]) -> bool {
let Some(e) = terms.iter().filter(|(m, _)| *m != 0.0).map(|(_, e)| *e).max() else {
return false;
};
let terms = terms.map(|(m, x)| ldexp(m, x - e));
let largest = terms.iter().fold(0.0_f64, |k, v| k.max(v.abs()));
let d: f64 = terms.iter().sum();
d.abs() > 1e-15 * largest
}
/// `a·d − b·c` for numbers split as by [`frexp`], as a mantissa `0.5 ≤ |m| < 1` (or 0) and a power
/// of two. Each product is formed exactly as a rounded value and its rounding error, and the four
/// parts are summed with the error of the first subtraction kept, so the result is within a few
/// units in the last place of the exact value unless the two products agree to about 32 digits.
fn split_minor(a: (f64, i32), d: (f64, i32), b: (f64, i32), c: (f64, i32)) -> (f64, i32) {
let exact = |x: (f64, i32), y: (f64, i32), sign: f64| {
let hi = x.0 * y.0;
(sign * hi, sign * x.0.mul_add(y.0, -hi), x.1 + y.1)
};
let parts = [exact(a, d, 1.0), exact(b, c, -1.0)];
let Some(e) = parts.iter().filter(|p| p.0 != 0.0).map(|p| p.2).max() else {
return (0.0, 0);
};
let [(h0, l0), (h1, l1)] = parts.map(|(h, l, x)| (ldexp(h, x - e), ldexp(l, x - e)));
// Knuth's two-sum: `s + err` is exactly `h0 + h1`.
let s = h0 + h1;
let t = s - h0;
let err = (h0 - (s - t)) + (h1 - t);
let (m, x) = frexp(s + (err + (l0 + l1)));
(m, e + x)
}
/// The sum of `m·2^e` over `terms`, in order, as a mantissa `0.5 ≤ |m| < 1` (or 0) and a power of
/// two. Every term is first divided by the power of two of the largest nonzero one, so none of
/// them overflows.
@@ -566,6 +617,99 @@ mod tests {
}
}
#[test]
fn the_inverse_of_an_invertible_map_is_invertible() {
// The inverse's determinant is about 1e-16 of its largest product, but its adjugate is
// the map itself times a number.
let skew = Homography([[-1000.0, -1e-8, -1e-5], [0.0, 1e-4, -1e7], [1e-8, 0.0, 1e-8]]);
let inv = skew.inverse().unwrap();
assert_eq!(Homography::from_array(inv.to_array()), Some(inv));
let back = inv.inverse().unwrap_or_else(|| panic!("{inv:?}"));
// The same map as `skew`, to within the rounding of the stored inverse: each entry within
// 1e-6 of the largest magnitude in its row, and points map to within 1e-6 of where `skew`
// maps them.
let k = back.0[2][0] / skew.0[2][0];
assert!(k > 0.0, "{k}");
for (r, row) in back.0.iter().enumerate() {
let size = skew.0[r].iter().fold(0.0_f64, |k, v| k.max(v.abs()));
for (c, v) in row.iter().enumerate() {
assert!((v / k - skew.0[r][c]).abs() <= 1e-6 * size, "{back:?}");
}
}
for p in [Point::new(3.0, -2.0), Point::new(-0.5, 7.0)] {
let q = skew.apply(p).unwrap();
assert!(back.apply(p).unwrap().distance(q) <= 1e-6 * q.to_vec2().hypot(), "{p:?}");
}
// Maps whose determinant is 0 are refused, though the cofactors of the first one cancel
// to about 2e-12 of their products: its rows are close to parallel and the third is the sum of
// the first two.
let two = pow2(40);
let near =
Homography([[two + 1.0, two + 3.0, two + 7.0], [two + 2.0, two + 5.0, two + 11.0], [2.0 * two + 3.0, 2.0 * two + 8.0, 2.0 * two + 18.0]]);
let flat = Homography([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.25, 0.5, 1.0]]);
let times = |h: Homography, f: f64| Homography(h.0.map(|row| row.map(|v| v * f)));
for h in [near, flat] {
for f in [pow2(-900), pow2(-40), 1.0, pow2(40), pow2(900)] {
let s = times(h, f);
assert!(!s.is_invertible(), "{f} {s:?}");
assert_eq!(s.inverse(), None, "{f}");
assert_eq!(Homography::from_array(s.to_array()), None, "{f}");
}
}
}
#[test]
fn conjugating_does_not_depend_on_the_scale_of_the_affine() {
let unit = |h: Homography| {
let k = h.0[2].iter().fold(0.0_f64, |k, v| k.max(v.abs()));
Homography(h.0.map(|row| row.map(|v| v / k)))
};
let m = h().0;
for s in [1e-200, 1e-8, 1.0, 1e8, 1e200] {
let t = Affine::scale(s);
let c = h().conjugated(t).unwrap_or_else(|| panic!("{s}"));
// The scale times h() times its inverse.
let want = unit(Homography([[m[0][0], m[0][1], s * m[0][2]], [m[1][0], m[1][1], s * m[1][2]], [m[2][0] / s, m[2][1] / s, m[2][2]]]));
for (v, w) in unit(c).to_array().iter().zip(want.to_array()) {
assert!((v - w).abs() <= 1e-12 * w.abs().max(1.0), "{s}: {c:?}");
}
// At 1e-200 the w row's first two entries are about 1e197, so these points, whose w is
// about 1, count as on the horizon (see `apply`).
if s < 1e-8 {
continue;
}
for p in [Point::new(3.0, 7.0), Point::new(-40.0, 12.0)] {
let want = t * h().apply(p).unwrap();
assert!(c.apply(t * p).unwrap().distance(want) <= 1e-9 * want.to_vec2().hypot(), "{s} {p:?}");
}
}
// An affine whose columns are parallel is refused at every scale.
for s in [1e-200, 1e-8, 1.0, 1e8, 1e200] {
let flat = Affine::new([s, 2.0 * s, 2.0 * s, 4.0 * s, 5.0, 6.0]);
assert_eq!(h().conjugated(flat), None, "{s}");
assert_eq!(h().conjugated(Affine::scale(s) * Affine::scale_non_uniform(1.0, 0.0)), None, "{s}");
}
assert_eq!(h().conjugated(Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0])), None);
assert_eq!(h().conjugated(Affine::scale(f64::INFINITY)), None);
}
#[test]
fn conjugating_a_map_at_a_tiny_scale_gives_an_invertible_map() {
// Against these affines the first two rows of the direct product underflow to 0.
let tiny = Homography(Homography::IDENTITY.0.map(|row| row.map(|v| v * 5e-324)));
for s in [1e-200, 1e-8] {
let c = tiny.conjugated(Affine::scale(s)).unwrap_or_else(|| panic!("{s}"));
assert_eq!(Homography::from_array(c.to_array()), Some(c), "{s}");
let k = c.0[2][2];
for (r, row) in c.0.iter().enumerate() {
for (j, v) in row.iter().enumerate() {
let want = if r == j { k } else { 0.0 };
assert!(k != 0.0 && (v - want).abs() <= 1e-12 * k.abs(), "{s}: {c:?}");
}
}
}
}
#[test]
fn a_map_at_a_tiny_scale_maps_points_as_at_unit_scale() {
for f in [5e-324, 1e-300] {
+2 -1
View File
@@ -452,7 +452,8 @@ fn render_preview(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, String> {
let r = b.call("ui.render", p)?;
let encoded = r.get("pngBase64").and_then(Value::as_str).ok_or("renderer returned no image")?;
let png = vectorcraft_format::base64_decode(encoded).ok_or("renderer returned bad base64")?;
let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| format!("read preview: {e}"))?;
// The render was asked for at most 4096 a side.
let img = super::handlers::decode_png(&png, 8192).map_err(|e| format!("read preview: {e}"))?;
let img = if img.width() > max || img.height() > max { img.thumbnail(max, max) } else { img };
let mut out = std::io::Cursor::new(Vec::new());
img.write_to(&mut out, image::ImageFormat::Png).map_err(|e| format!("encode preview: {e}"))?;
+30 -1
View File
@@ -442,12 +442,27 @@ pub(super) fn max_side(a: &Args) -> Result<Option<u32>, String> {
}
}
/// The longest side of a window capture that is decoded (a screen is never wider).
const MAX_CAPTURE_SIDE: u32 = 16_384;
/// `png` decoded, refused when a side is longer than `side` or the decode needs more than 256 MiB:
/// the picture is the app's reply, and its header names the size it is decoded at.
pub(super) fn decode_png(png: &[u8], side: u32) -> Result<image::DynamicImage, image::ImageError> {
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(side);
limits.max_image_height = Some(side);
limits.max_alloc = Some(256 << 20);
reader.limits(limits);
reader.decode()
}
/// A window capture with `max_side`: scaled down when its longer side is larger, with its own size
/// in `capturedWidth` / `capturedHeight` and the returned image's in `width` / `height`. Without
/// `max_side` the capture and `info` stay as they are.
fn fit_capture(png: Vec<u8>, max: Option<u32>, info: &mut Value) -> Result<Vec<u8>, String> {
let Some(max) = max else { return Ok(png) };
let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| format!("read capture: {e}"))?;
let img = decode_png(&png, MAX_CAPTURE_SIDE).map_err(|e| format!("read capture: {e}"))?;
info["capturedWidth"] = json!(img.width());
info["capturedHeight"] = json!(img.height());
if img.width().max(img.height()) <= max {
@@ -472,3 +487,17 @@ pub(super) fn image_result(png: &[u8], info: Value) -> ToolResult {
is_error: false,
}
}
#[cfg(test)]
mod decode_tests {
use super::decode_png;
#[test]
fn a_picture_with_a_side_past_the_limit_is_not_decoded() {
let mut png = std::io::Cursor::new(Vec::new());
image::RgbaImage::new(200, 10).write_to(&mut png, image::ImageFormat::Png).unwrap();
let png = png.into_inner();
assert!(decode_png(&png, 100).is_err());
assert_eq!(decode_png(&png, 200).unwrap().width(), 200);
}
}
+1 -1
View File
@@ -75,7 +75,7 @@ pub(crate) fn checksum(header: &[u8]) -> u16 {
fn flatten(bp: &BezPath, tol: f64) -> Vec<(Vec<Point>, bool)> {
let mut out: Vec<(Vec<Point>, bool)> = vec![];
let mut cur: Vec<Point> = vec![];
kurbo::flatten(bp.iter(), tol, |el| match el {
vectorcraft_geom::flatten(bp.iter(), tol, |el| match el {
PathEl::MoveTo(p) => {
if cur.len() > 1 {
out.push((std::mem::take(&mut cur), false));
+92 -3
View File
@@ -143,9 +143,20 @@ pub(crate) fn eps_for<'a>(paths: impl IntoIterator<Item = &'a BezPath>) -> Resul
}
}
}
Ok((m * f64::EPSILON * 64.0).max(1e-6))
let eps = (m * f64::EPSILON * 64.0).max(1e-6);
// Past this the sweep tolerance is wider than a document unit: features thinner than it collapse and the call
// would answer `Ok` with part of the art (or all of it) gone. Refuse instead, so callers keep the original.
if eps > MAX_SWEEP_EPS {
return Err(PathOpsError::Degenerate);
}
Ok(eps)
}
/// The widest sweep tolerance [`eps_for`] accepts: one document unit, reached by coordinates of about 7e13. (The engine
/// refuses coordinates far below that, so this only guards the library's own callers; it does not follow the `precision`
/// a caller asks for.)
const MAX_SWEEP_EPS: f64 = 1.0;
fn el_points(el: &kurbo::PathEl) -> impl Iterator<Item = Point> {
use kurbo::PathEl::*;
let v: [Option<Point>; 3] = match *el {
@@ -329,6 +340,13 @@ impl Arrangement {
self.contours_where(|w| pred(&self.mask(w)))
}
/// [`Self::contours`] with a panic in the sweep's contour pass turned into an error, as `new` does for the
/// sweep itself (native builds only: on the web a panic aborts, whatever is caught here). Used by the calls that can return an error; the rest have none to return and let the engine's
/// guard report it.
pub(crate) fn try_contours(&self, pred: impl Fn(&[bool]) -> bool) -> Result<Contours, PathOpsError> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.contours(pred))).map_err(|_| PathOpsError::Degenerate)
}
/// All distinct non-empty coverage masks that occur next to some edge, sorted.
pub(crate) fn distinct_masks(&self) -> Vec<Vec<bool>> {
let mut set = BTreeSet::new();
@@ -670,7 +688,7 @@ pub fn boolean(a: &PathData, a_rule: FillRule, b: &PathData, b_rule: FillRule, o
/// Boolean operation with an explicit refit `precision`; errors on non-finite input.
pub fn try_boolean(a: &PathData, a_rule: FillRule, b: &PathData, b_rule: FillRule, op: BoolOp, precision: f64) -> Result<PathData, PathOpsError> {
let arr = Arrangement::new(vec![(fill_bezpath(a), a_rule), (fill_bezpath(b), b_rule)])?;
let c = arr.contours(|m| op.apply(m[0], m[1]));
let c = arr.try_contours(|m| op.apply(m[0], m[1]))?;
let tidy = Tidy { precision, ..arr.tidy };
Ok(all_contours_to_path(&c, &tidy))
}
@@ -680,7 +698,7 @@ pub fn try_boolean(a: &PathData, a_rule: FillRule, b: &PathData, b_rule: FillRul
pub fn try_boolean_n(paths: &[(&PathData, FillRule)], pred: impl Fn(&[bool]) -> bool) -> Result<PathData, PathOpsError> {
let bps: Vec<(BezPath, FillRule)> = paths.iter().map(|(p, r)| (fill_bezpath(p), *r)).collect();
let arr = Arrangement::new(bps)?;
Ok(all_contours_to_path(&arr.contours(pred), &arr.tidy))
Ok(all_contours_to_path(&arr.try_contours(pred)?, &arr.tidy))
}
/// N-ary boolean: the area where `pred(inside_flags)` holds, `inside_flags[i]` telling whether a
@@ -816,4 +834,75 @@ mod tests {
lens.close_path();
assert_eq!(tidy.repair(&lens), lens);
}
fn square(x: f64, y: f64, size: f64) -> PathData {
PathData::single(vectorcraft_geom::SubPath::new(
[(x, y), (x + size, y), (x + size, y + size), (x, y + size)]
.iter()
.map(|&(x, y)| vectorcraft_geom::Anchor::corner(Point::new(x, y)))
.collect(),
true,
))
}
#[test]
fn coordinates_wider_than_the_precision_are_refused_not_emptied() {
// At 1e15 the sweep tolerance is far above a 10 unit square: both squares used to vanish and the call said `Ok`.
let near = square(0.0, 0.0, 10.0);
let far = square(1e15, 1e15, 10.0);
for op in [BoolOp::Union, BoolOp::Intersect, BoolOp::Difference, BoolOp::Xor] {
assert_eq!(
try_boolean(&near, FillRule::NonZero, &far, FillRule::NonZero, op, DEFAULT_PRECISION),
Err(PathOpsError::Degenerate),
"{op:?}"
);
}
assert_eq!(try_area(&far, FillRule::NonZero), Err(PathOpsError::Degenerate));
assert_eq!(try_normalize(&far, FillRule::NonZero), Err(PathOpsError::Degenerate));
// The infallible entry points keep answering with an empty path.
assert!(boolean(&near, FillRule::NonZero, &far, FillRule::NonZero, BoolOp::Union).is_empty());
}
#[test]
fn coordinates_near_the_float_limit_do_not_reach_the_sweep() {
// A 1e308 rectangle made linesweeper panic (a caught panic here, an abort on the web).
let huge = square(0.0, 0.0, 1e308);
let small = square(0.0, 0.0, 10.0);
assert_eq!(try_area(&huge, FillRule::NonZero), Err(PathOpsError::Degenerate));
assert_eq!(try_boolean(&huge, FillRule::NonZero, &small, FillRule::NonZero, BoolOp::Union, DEFAULT_PRECISION), Err(PathOpsError::Degenerate));
assert_eq!(try_unite_all(&[(&huge, FillRule::NonZero), (&small, FillRule::NonZero)]), Err(PathOpsError::Degenerate));
}
#[test]
fn large_but_sensible_coordinates_still_work() {
// Well inside the limit: far-out but sensible offsets.
for at in [1e5, 1e7] {
let u = try_boolean(
&square(at, at, 10.0),
FillRule::NonZero,
&square(at + 5.0, at, 10.0),
FillRule::NonZero,
BoolOp::Union,
DEFAULT_PRECISION,
)
.unwrap();
let a = try_area(&u, FillRule::NonZero).unwrap();
assert!((a - 150.0).abs() < 1.0, "at {at}: area {a}");
}
}
#[test]
fn the_coordinate_limit_sits_where_the_tolerance_passes_a_unit() {
// 100 unit squares: tolerance 0.7 at 5e13 (kept), 1.4 at 1e14 (refused).
assert!(try_area(&square(5e13, 5e13, 100.0), FillRule::NonZero).is_ok());
assert_eq!(try_area(&square(1e14, 1e14, 100.0), FillRule::NonZero), Err(PathOpsError::Degenerate));
}
#[test]
#[cfg(panic = "unwind")]
fn a_panic_in_the_contour_pass_becomes_an_error() {
let arr = Arrangement::new(vec![(fill_bezpath(&square(0.0, 0.0, 10.0)), FillRule::NonZero)]).unwrap();
assert!(arr.try_contours(|m| m[0]).is_ok());
assert_eq!(arr.try_contours(|_| panic!("simulated panic in the sweep")).err(), Some(PathOpsError::Degenerate));
}
}
+26 -3
View File
@@ -3,7 +3,7 @@
use std::collections::{BTreeMap, BTreeSet};
use kurbo::{CubicBez, PathSeg, Point, Rect, Vec2};
use kurbo::{CubicBez, ParamCurve, PathSeg, Point, Rect, Vec2};
use vectorcraft_geom::path::measured_arclen;
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
@@ -628,9 +628,32 @@ fn golden_min(f: impl Fn(f64) -> (CubicBez, f64, usize), mut a: f64, mut b: f64)
pub fn add_anchor_points(path: &PathData) -> PathData {
let mut out = path.clone();
for sp in &mut out.subpaths {
for seg in (0..sp.segment_count()).rev() {
sp.insert_anchor(seg, 0.5);
let n = sp.segment_count();
if n == 0 {
continue;
}
// Built in one pass (inserting into the middle of the vector shifts the rest each time):
// anchor k lands at 2k and the new anchor of segment k at 2k + 1.
let mut v = Vec::with_capacity(sp.anchors.len() * 2);
for (k, a) in sp.anchors.iter().enumerate() {
v.push(*a);
if k < n {
v.push(*a);
}
}
for seg in 0..n {
let c = sp.segment(seg);
let (l, r) = (c.subsegment(0.0..0.5), c.subsegment(0.5..1.0));
if sp.segment_is_line(seg) {
v[2 * seg + 1] = Anchor::corner(l.p3);
} else {
let at = (2 * seg + 2) % v.len();
v[2 * seg].h_out = l.p1;
v[at].h_in = r.p2;
v[2 * seg + 1] = Anchor { p: l.p3, h_in: l.p2, h_out: r.p1, kind: AnchorKind::Smooth };
}
}
sp.anchors = v;
}
out
}
+139 -4
View File
@@ -119,10 +119,10 @@ pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) ->
// winding, leaving faces uncovered that are really within `d` of the path. Every face of the
// true offset is bounded by arrangement edges, so a contour is spurious iff a point deep inside
// it lies closer than `d`: holes when growing, islands when insetting.
let src = path.to_bezpath();
let src = std::cell::LazyCell::new(|| boxed_segments(&path.to_bezpath()));
let drop_outer = delta < 0.0;
let spurious: Vec<bool> =
c.contours().map(|k| k.outer == drop_outer && deep_point(&k.path).is_some_and(|p| dist_to(&src, p) < d * (1.0 - 1e-4) - 1e-6)).collect();
c.contours().map(|k| k.outer == drop_outer && deep_point(&k.path).is_some_and(|p| any_within(&src, p, d * (1.0 - 1e-4) - 1e-6))).collect();
if !spurious.contains(&true) {
return all_contours_to_path(&c, &Tidy::free(DEFAULT_PRECISION));
}
@@ -208,9 +208,25 @@ fn deep_point(bp: &BezPath) -> Option<kurbo::Point> {
best.map(|(_, p)| p)
}
fn dist_to(bp: &BezPath, p: kurbo::Point) -> f64 {
/// Each segment of `bp` with its bounding box.
fn boxed_segments(bp: &BezPath) -> Vec<(kurbo::Rect, kurbo::PathSeg)> {
use kurbo::ParamCurveExtrema;
bp.segments().map(|s| (s.bounding_box(), s)).collect()
}
/// Whether a segment with bounding box `b` could lie within `r` of `p`: the box is inflated by `r`
/// and by slack for rounding in the box and in the curve evaluation, which grows with the coordinates.
fn box_may_reach(b: &kurbo::Rect, p: kurbo::Point, r: f64) -> bool {
let reach = r + 1e-6 + 1e-9 * p.x.abs().max(p.y.abs());
p.x >= b.x0 - reach && p.x <= b.x1 + reach && p.y >= b.y0 - reach && p.y <= b.y1 + reach
}
/// Whether some segment lies closer than `r` to `p`. A segment whose box is too far away can't, so
/// it is skipped without the costly nearest-point search, and the search stops at the first
/// segment that does.
fn any_within(segs: &[(kurbo::Rect, kurbo::PathSeg)], p: kurbo::Point, r: f64) -> bool {
use kurbo::ParamCurveNearest;
bp.segments().map(|s| s.nearest(p, 1e-6).distance_sq).fold(f64::INFINITY, f64::min).sqrt()
r > 0.0 && segs.iter().any(|(b, s)| box_may_reach(b, p, r) && s.nearest(p, 1e-6).distance_sq.sqrt() < r)
}
#[cfg(test)]
@@ -219,6 +235,125 @@ mod tests {
use super::*;
/// The check as it was: the nearest distance over every segment, then compared.
fn dist_to(bp: &BezPath, p: kurbo::Point) -> f64 {
use kurbo::ParamCurveNearest;
bp.segments().map(|s| s.nearest(p, 1e-6).distance_sq).fold(f64::INFINITY, f64::min).sqrt()
}
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> f64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 11) as f64 / (1u64 << 53) as f64
}
/// A coordinate on a coarse grid, so segments touch, coincide and nest often.
fn grid(&mut self, n: f64) -> f64 {
(self.next() * n).floor()
}
}
#[test]
fn nearby_segment_check_agrees_with_the_full_scan() {
let mut rng = Lcg(7);
let (mut hits, mut skipped) = (0, 0);
for case in 0..400 {
let n = [3.0, 6.0, 20.0][case % 3];
let mut bp = BezPath::new();
for _ in 0..1 + (rng.next() * 12.0) as usize {
let pt = |rng: &mut Lcg| kurbo::Point::new(rng.grid(n), rng.grid(n));
let a = pt(&mut rng);
bp.move_to(a);
match (rng.next() * 5.0) as u32 {
0 => bp.line_to(a), // zero length
1 => bp.line_to(pt(&mut rng)),
2 => bp.quad_to(pt(&mut rng), pt(&mut rng)),
3 => bp.curve_to(pt(&mut rng), pt(&mut rng), pt(&mut rng)),
_ => {
// A circle, touching or nested in others.
let r = 1.0 + rng.grid(n / 2.0);
bp.extend(kurbo::Circle::new(a, r).to_path(0.01));
}
}
if rng.next() < 0.3 {
bp.close_path();
}
}
// The same geometry far from the origin too, where the rounding slack matters.
let shift = [0.0, 1e6, 1e9][case % 3];
let bp = kurbo::Affine::translate((shift, -shift)) * bp;
let segs = boxed_segments(&bp);
for _ in 0..40 {
// On the grid (on segments and their ends) and off it.
let p = if rng.next() < 0.5 {
kurbo::Point::new(rng.grid(n), rng.grid(n))
} else {
kurbo::Point::new(rng.next() * (n + 2.0) - 1.0, rng.next() * (n + 2.0) - 1.0)
};
let p = kurbo::Point::new(p.x + shift, p.y - shift);
let nearest = dist_to(&bp, p);
// Radii around the true distance (where a wrong skip would show), just outside a
// segment's box, and the usual kind.
let box_gap =
segs.iter().map(|(b, _)| (b.x0 - p.x).max(p.x - b.x1).max(b.y0 - p.y).max(p.y - b.y1).max(0.0)).fold(f64::INFINITY, f64::min);
for r in [
nearest,
nearest * (1.0 - 1e-9),
nearest * (1.0 + 1e-9),
nearest + 1e-6,
box_gap + 5e-7,
box_gap + 2e-6,
0.0,
-1.0,
1e-7,
rng.next() * 3.0,
1e6,
] {
assert_eq!(any_within(&segs, p, r), nearest < r, "case {case} p {p:?} r {r} nearest {nearest}");
hits += usize::from(nearest < r);
// Every segment the box test skips is really out of reach.
for (b, s) in &segs {
if r > 0.0 && !box_may_reach(b, p, r) {
skipped += 1;
use kurbo::ParamCurveNearest;
assert!(s.nearest(p, 1e-6).distance_sq.sqrt() >= r, "case {case} skipped a segment within {r} of {p:?}");
}
}
}
}
}
assert!(hits > 1000 && skipped > 10_000, "{hits} {skipped}");
assert!(!any_within(&[], kurbo::Point::ZERO, 1.0));
}
#[test]
fn growing_a_plate_with_many_holes_keeps_the_holes_that_stay() {
// A plate with a grid of round holes: growing by 1 closes the narrow ones (radius <= 1)
// and keeps the wide ones.
let mut plate = BezPath::new();
plate.extend(kurbo::Rect::new(0.0, 0.0, 200.0, 200.0).to_path(0.1));
for i in 0..10 {
for j in 0..10 {
let r = if (i + j) % 2 == 0 { 0.8 } else { 4.0 };
plate.extend(kurbo::Circle::new((10.0 + 20.0 * f64::from(i), 10.0 + 20.0 * f64::from(j)), r).to_path(0.01).reverse_subpaths());
}
}
let out = offset_path(&PathData::from_bezpath(&plate), 1.0, Join::Round, 4.0);
// The outer contour and the 50 wide holes; the 50 narrow ones are gone.
assert_eq!(out.subpaths.len(), 1 + 50);
// The holes left are the wide ones, shrunk to radius 3 and still centred on their grid point.
let mut holes = 0;
for sp in out.subpaths.iter().skip(1) {
let b = PathData::single(sp.clone()).to_bezpath().bounding_box();
let (cx, cy) = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0);
assert!((b.width() - 6.0).abs() < 0.05 && (b.height() - 6.0).abs() < 0.05, "{b:?}");
let (i, j) = (((cx - 10.0) / 20.0).round(), ((cy - 10.0) / 20.0).round());
assert!((cx - 10.0 - 20.0 * i).abs() < 0.05 && (cy - 10.0 - 20.0 * j).abs() < 0.05 && (i + j) % 2.0 != 0.0, "{b:?}");
holes += 1;
}
assert_eq!(holes, 50);
}
#[test]
fn stroke_region_unites_outlines_whatever_their_winding() {
// A bar, and a square ring wound the other way that the bar runs into.
+15
View File
@@ -515,6 +515,21 @@ fn add_anchor_points_doubles() {
assert!(r.anchors().any(|(_, _, a)| a.p == Point::new(5.0, 0.0)));
}
/// The one-pass build gives what inserting a midpoint into each segment (last first) gives, open or closed.
#[test]
fn add_anchor_points_matches_inserting() {
let open = PathData::single(SubPath::new(circle(0.0, 0.0, 10.0).subpaths[0].anchors.clone(), false));
for src in [circle(0.0, 0.0, 10.0), rect(0.0, 0.0, 10.0, 10.0), open] {
let mut want = src.clone();
for sp in &mut want.subpaths {
for seg in (0..sp.segment_count()).rev() {
sp.insert_anchor(seg, 0.5);
}
}
assert_eq!(add_anchor_points(&src), want);
}
}
#[test]
fn average_axes() {
let p = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 4.0), Point::new(5.0, 8.0)], false));
+11
View File
@@ -165,6 +165,10 @@ fn turns(set: &PrintSettings, (w, h): (f64, f64), flipped: bool) -> (Affine, (f6
(v, (w, h))
}
fn too_many_pages() -> PdfError {
PdfError::BadSetting(format!("the job would print more than {} pages", super::MAX_PAGES))
}
/// The pages of `doc` (whose layers are those that print) as `set` lays them out, the tiles of
/// each artboard when tiling, and warnings (art that doesn't fit the imageable area).
pub(crate) fn layout(doc: &Document, set: &PrintSettings, warnings: &mut Vec<String>) -> Result<(Vec<Layout>, Vec<TileGrid>), PdfError> {
@@ -174,6 +178,10 @@ pub(crate) fn layout(doc: &Document, set: &PrintSettings, warnings: &mut Vec<Str
let origin = set.tile_origin.placed.then_some((set.tile_origin.x, set.tile_origin.y));
let (mut pages, mut grids) = (vec![], vec![]);
for (artboard, r) in regions(doc, set)? {
// The job is refused past MAX_PAGES (copies and inks only add to it): stop making pages here.
if pages.len() > super::MAX_PAGES {
return Err(too_many_pages());
}
let what = artboard.map_or_else(|| "The art".to_string(), |i| format!("Artboard {}", i + 1));
if !(r.width() > 0.0 && r.height() > 0.0) {
warnings.push(format!("{what} has no area and was left out"));
@@ -297,6 +305,9 @@ pub(crate) fn layout(doc: &Document, set: &PrintSettings, warnings: &mut Vec<Str
let (x, y) = (grid.0 + c * step.0, grid.1 + rw * step.1);
Rect::new(x, y, x + tile.0, y + tile.1)
};
if pages.len() + pick.len() > super::MAX_PAGES {
return Err(too_many_pages());
}
for &t in &pick {
let w = window(t);
let view = turn * Affine::translate((at.0 - w.x0, at.1 - w.y0));
+8
View File
@@ -239,6 +239,14 @@ fn tiles_cover_the_artboard_with_overlap() {
assert!(preview(&d, &settings(json!({"scaling": "tileFull", "overlap": 400}))).is_err(), "overlap of half a tile");
}
#[test]
fn a_job_of_too_many_artboards_is_refused_while_laying_out() {
let mut d = doc(100.0, 100.0, &[]);
d.artboards.extend((2..=MAX_PAGES as u32 + 2).map(|i| artboard(i, 0.0)));
let e = preview(&d, &settings(json!({}))).unwrap_err().to_string();
assert!(e.contains("more than 2000 pages"), "{e}");
}
#[test]
fn artboard_range_skip_blank_and_ignore() {
let mut d =
+1
View File
@@ -49,6 +49,7 @@ pub fn default_threads() -> u16 {
/// [`default_threads`] when automatic, on `cpus` processors of which the process may use `usable`
/// (0 = all).
#[cfg(any(test, not(target_arch = "wasm32")))]
fn automatic_threads(cpus: usize, usable: usize) -> u16 {
let cores = if usable == 0 { cpus } else { cpus.min(usable) };
(cores.saturating_sub(1)).min(8) as u16
+22 -4
View File
@@ -370,14 +370,14 @@ impl<'l> Acc<'l> {
pub fn problem(&mut self, code: &'static str, line: Option<usize>, file: Option<&str>, detail: Option<&str>) {
if self.room(self.problems.len()) {
let detail = detail.map(|d| self.echo(d));
self.problems.push(Problem { code, line, file: file.map(str::to_string), detail });
self.problems.push(Problem { code, line, file: file.map(|f| self.echo(f)), detail });
}
}
pub fn directive(&mut self, name: &'static str, value: &str, line: usize, form: &'static str, file: Option<&str>) {
if self.room(self.directives.len()) {
let value = self.echo(value);
self.directives.push(Directive { name, value, line, form, file: file.map(str::to_string) });
self.directives.push(Directive { name, value, line, form, file: file.map(|f| self.echo(f)) });
}
}
@@ -394,14 +394,14 @@ impl<'l> Acc<'l> {
version: part(t.version),
locale: part(t.locale),
line,
file: file.map(str::to_string),
file: file.map(|f| self.echo(f)),
};
self.targets.push(target);
}
pub fn include(&mut self, value: &str, line: usize, file: Option<&str>, status: IncludeStatus, path: Option<&str>) {
if self.room(self.includes.len()) {
let include = Include { value: self.echo(value), line, file: file.map(str::to_string), status, path: path.map(|p| self.echo(p)) };
let include = Include { value: self.echo(value), line, file: file.map(|f| self.echo(f)), status, path: path.map(|p| self.echo(p)) };
self.includes.push(include);
}
}
@@ -461,3 +461,21 @@ fn echo_cow(s: &str, max: usize) -> Cow<'_, str> {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_file_of_a_row_is_cut_like_the_rest_of_the_echo() {
let limits = Limits::default();
let mut acc = Acc::new(&limits);
let long = "d/".repeat(5000);
acc.problem("x", Some(1), Some(&long), None);
acc.directive("include", "v", 1, "form", Some(&long));
acc.target("illustrator", 1, Some(&long));
for file in [&acc.problems[0].file, &acc.directives[0].file, &acc.targets[0].file] {
assert_eq!(file.as_deref().map(|f| f.chars().count()), Some(limits.echo));
}
}
}
+4 -1
View File
@@ -146,7 +146,7 @@ impl OtFeatures {
/// Is `tag` (optionally prefixed with `-` or `+`) one this set understands?
pub fn known_tag(tag: &str) -> bool {
let t = tag.trim_start_matches(['-', '+']);
let t = tag.strip_prefix(['-', '+']).unwrap_or(tag);
matches!(t, "liga" | "calt" | "dlig" | "smcp" | "frac" | "onum" | "tnum" | "ordn" | "swsh") || EXTRA_FEATURES.contains(&t)
}
@@ -306,6 +306,9 @@ mod tests {
assert!(OtFeatures::known_tag(t), "{t}");
}
assert!(!OtFeatures::known_tag("ss21"));
for tag in ["--liga", "+-dnom", "-+ss01", "++liga"] {
assert!(!OtFeatures::known_tag(tag), "{tag}");
}
let o = OtFeatures::from_tags(["ss03", "pnum", "sups", "-liga"]);
assert_eq!(o.to_tags(), vec!["-liga", "ss03", "pnum", "sups"]);
assert_eq!(OtFeatures::from_tags(["ss03", "-ss03"]).to_tags(), Vec::<String>::new(), "turned off again");
+85 -12
View File
@@ -3,6 +3,70 @@ use super::names::{localized, name};
use super::traits::{FaceKeys, FontTraits};
use super::{Arc, GlyphId, HashMap, Location, LocationRef, MetadataProvider, Size, StringId};
/// The most glyphs one [`outline_points`] lookup reads, composite components included.
const MAX_OUTLINE_VISITS: usize = 65_536;
/// Unhinted TrueType contour points in glyph order, including transformed composite components.
/// A point cap, a depth bound and `visits`, the number of glyphs the whole lookup may still read,
/// keep damaged fonts from making caret lookup unbounded. Callers start `visits` at
/// [`MAX_OUTLINE_VISITS`].
fn outline_points(font: &skrifa::FontRef<'_>, gid: GlyphId, depth: usize, visits: &mut usize) -> Option<Vec<(f64, f64)>> {
use skrifa::raw::TableProvider;
use skrifa::raw::tables::glyf::{Anchor, CompositeGlyphFlags, Glyph};
const MAX_DEPTH: usize = 16;
const MAX_POINTS: usize = 65_536;
if depth >= MAX_DEPTH {
return None;
}
*visits = visits.checked_sub(1)?;
let glyph = font.loca(None).ok()?.get(gid, &font.glyf().ok()?)?.into_glyph()?;
match glyph {
Glyph::Simple(simple) => {
if simple.num_points() > MAX_POINTS {
return None;
}
let points: Vec<_> = simple.points().map(|p| (f64::from(p.x), f64::from(p.y))).collect();
(points.len() == simple.num_points()).then_some(points)
}
Glyph::Composite(composite) => {
let mut points = Vec::new();
for component in composite.components() {
let child = outline_points(font, GlyphId::new(component.glyph.to_u32()), depth + 1, visits)?;
let t = component.transform;
let xx = f64::from(t.xx.to_f32());
let xy = f64::from(t.xy.to_f32());
let yx = f64::from(t.yx.to_f32());
let yy = f64::from(t.yy.to_f32());
let transformed: Vec<_> = child.into_iter().map(|(x, y)| (xx * x + xy * y, yx * x + yy * y)).collect();
let (dx, dy) = match component.anchor {
Anchor::Offset { x, y } => {
let (x, y) = (f64::from(x), f64::from(y));
// Each axis of a scaled offset scales by the length of its basis vector, as
// in skrifa's outline loader. UNSCALED_COMPONENT_OFFSET turns the scaling off.
let offset_flags = CompositeGlyphFlags::SCALED_COMPONENT_OFFSET | CompositeGlyphFlags::UNSCALED_COMPONENT_OFFSET;
if component.flags & offset_flags == CompositeGlyphFlags::SCALED_COMPONENT_OFFSET {
(x * xx.hypot(xy), y * yx.hypot(yy))
} else {
(x, y)
}
}
Anchor::Point { base, component } => {
let (bx, by) = *points.get(usize::from(base))?;
let (cx, cy) = *transformed.get(usize::from(component))?;
(bx - cx, by - cy)
}
};
if transformed.len() > MAX_POINTS.saturating_sub(points.len()) {
return None;
}
points.extend(transformed.into_iter().map(|(x, y)| (x + dx, y + dy)));
}
Some(points)
}
}
}
/// The family used when a requested family is unknown (Illustrator's Myriad Pro analogue).
pub const FALLBACK_FAMILY: &str = "Source Sans 3";
@@ -244,11 +308,11 @@ impl FontFace {
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/gdef>), one between each two
/// characters the glyph stands for, each an x in horizontal text and a y (up from the baseline)
/// in vertical text. A coordinate with a variation index (format 3 in a variable font) takes its
/// delta from the `GDEF` item variation store at the face's location; a device table's
/// adjustments for pixel sizes are not applied. `None` when the font lists no carets for the
/// glyph, lists a number other than `count`, gives one by a contour point, or gives one a
/// variation index whose delta can't be read.
fn ligature_caret_coordinates(&self, gid: u32, count: usize) -> Option<Vec<f64>> {
/// delta from the `GDEF` item variation store at the face's location. Format 2 uses the
/// unhinted outline point at the font's default variation location. Device-table adjustments
/// for pixel sizes are not applied. `None` when the font lists no carets for the glyph, lists
/// a number other than `count`, or gives a coordinate that cannot be resolved.
fn ligature_caret_coordinates(&self, gid: u32, count: usize, vertical: bool) -> Option<Vec<f64>> {
use skrifa::raw::TableProvider;
use skrifa::raw::tables::gdef::CaretValue;
use skrifa::raw::tables::layout::DeviceOrVariationIndex;
@@ -280,17 +344,26 @@ impl FontFace {
}
}
}
CaretValue::Format2(_) => None,
CaretValue::Format2(v) => {
// Raw glyf points have no variation deltas applied. Do not use one at a
// non-default location, where it could put the caret in the wrong place.
if self.location.coords().iter().any(|c| c.to_f32() != 0.0) {
return None;
}
let mut visits = MAX_OUTLINE_VISITS;
let point = outline_points(&font, GlyphId::new(gid), 0, &mut visits)?.get(usize::from(v.caret_value_point_index())).copied()?;
Some(if vertical { point.1 } else { point.0 })
}
})
.collect::<Option<Vec<f64>>>()?;
(!carets.is_empty()).then_some(carets)
}
/// The caret positions inside ligature glyph `gid` set across, in font units from its left
/// edge, left to right: the x coordinates of the font's ligature caret list. `None` when the
/// font lists no carets for the glyph, lists a number other than `count`, gives one by a contour
/// point, or gives positions that are not increasing inside the glyph's advance.
/// font lists no carets for the glyph, lists a number other than `count`, or gives positions
/// that are not increasing inside the glyph's advance.
pub fn ligature_carets(&self, gid: u32, count: usize) -> Option<Vec<f64>> {
let carets = self.ligature_caret_coordinates(gid, count)?;
let carets = self.ligature_caret_coordinates(gid, count, false)?;
let advance = self.advance(gid);
let inside = carets.iter().all(|x| *x > 0.0 && *x < advance) && carets.windows(2).all(|w| w[0] < w[1]);
inside.then_some(carets)
@@ -298,10 +371,10 @@ impl FontFace {
/// The caret positions inside ligature glyph `gid` standing upright in vertical type, in font
/// units down from the top of its cell, top to bottom: the y coordinates of the font's ligature
/// caret list, for a cell `cell` long whose top is `top` above the baseline. `None` when the
/// font lists no carets for the glyph, lists a number other than `count`, gives one by a contour
/// point, or gives positions that are not increasing inside the cell.
/// font lists no carets for the glyph, lists a number other than `count`, or gives positions
/// that are not increasing inside the cell.
pub fn vertical_ligature_carets(&self, gid: u32, count: usize, top: f64, cell: f64) -> Option<Vec<f64>> {
let carets = self.ligature_caret_coordinates(gid, count)?;
let carets = self.ligature_caret_coordinates(gid, count, true)?;
let inside = carets.iter().all(|y| *y < top && *y > top - cell) && carets.windows(2).all(|w| w[0] < w[1]);
inside.then(|| carets.iter().rev().map(|y| top - y).collect())
}
+15
View File
@@ -382,6 +382,21 @@ impl Ctx<'_> {
} else {
0.0
};
// On a path, an upright glyph turns about its pen: its cell runs along the path between
// where the glyph's transform sets the cell's foot and its top, moved by the shaper's
// placement and a baseline shift, and slanted by the path's effect.
let (width, width_start) = match (upright && self.on_path, g.sy) {
(true, sy) if sy != 0.0 => {
// In font units, with the Proportional Metrics change to its length.
let (cell, top) = upright_extent(g);
let proportional = g.vpal.filter(|_| g.face.vertical_glyph(g.gid).is_some()).map_or(0.0, |a| a.advance) / sy;
let tangent = Vec2::new(angle.cos(), angle.sin());
let along = |y: f64| (m * Point::new(0.0, y) - origin).dot(tangent);
let (start, end) = (along(cell + proportional - top), along(-top));
if start.is_finite() && end > start { (end - start, start) } else { (width, width_start) }
}
_ => (width, width_start),
};
if let Some(art) = g.inline.as_ref().and_then(|ib| ib.art) {
self.out.inlines.push(InlineGlyph { run: g.run, byte: g.byte, glyph: self.out.glyphs.len(), xf: m, bounds: m.transform_rect_bbox(art) });
}
+3 -1
View File
@@ -166,7 +166,9 @@ pub struct PositionedGlyph {
/// in text space: the font's placement of the glyph (`GPOS` x placement), less a leading space
/// taken off, plus the manual kerning of right-to-left text, which moves the glyph right so that
/// the space it adds lies on the glyph's left. 0 for a glyph standing upright or set across the
/// column in vertical type, and for an inline graphic.
/// column in vertical type, and for an inline graphic. An upright glyph in vertical type on a
/// path turns about its pen, and its cell starts one cell length before the cell's top: 0.12 em
/// before the pen without the font's vertical metrics.
pub width_start: f64,
}
+229
View File
@@ -19,6 +19,175 @@ fn db_with(font: Option<Vec<u8>>) -> FontDb {
db
}
/// Put a contour-point caret on the existing test ligature without changing its outline.
fn contour_caret_font(point_index: u16) -> Vec<u8> {
use write_fonts::FontBuilder;
use write_fonts::tables::gdef::{CaretValue, Gdef, LigCaretList, LigGlyph};
use write_fonts::tables::layout::CoverageFormat1 as WriteCoverage;
use write_fonts::types::{GlyphId16, Tag};
let base = ligature_caret_font(None).expect("test font builds");
let font = skrifa::FontRef::new(&base).expect("test font parses");
let gid = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph");
let mut builder = FontBuilder::new();
let list = LigCaretList::new(WriteCoverage::new(vec![GlyphId16::new(gid)]).into(), vec![LigGlyph::new(vec![CaretValue::format_2(point_index)])]);
builder.add_table(&Gdef::new(None, None, Some(list), None)).expect("GDEF builds");
for record in font.table_directory.table_records() {
let tag = Tag::new(&record.tag().to_be_bytes());
if !builder.contains(tag) {
builder.add_raw(tag, font.table_data(record.tag()).expect("base table reads").as_bytes());
}
}
builder.build()
}
#[test]
fn a_contour_point_caret_uses_its_unhinted_x_and_y() {
use skrifa::raw::TableProvider;
use skrifa::raw::tables::glyf::Glyph;
let base = ligature_caret_font(None).expect("test font builds");
let font = skrifa::FontRef::new(&base).expect("test font parses");
let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"));
let outline = font.loca(None).expect("loca reads").get(skrifa::GlyphId::new(gid), &font.glyf().expect("glyf reads")).expect("glyph reads");
let Glyph::Simple(simple) = outline.into_glyph().expect("glyph has an outline") else { panic!("W is simple") };
let (point_index, point) =
simple.points().enumerate().find(|(_, p)| p.x > 0 && p.x < 500 && p.y > -500 && p.y < 1000).expect("W has an interior contour point");
let db = db_with(Some(contour_caret_font(u16::try_from(point_index).unwrap())));
let face = db.face(LIGATURE_CARET_FAMILY, "Regular").unwrap();
assert_eq!(face.ligature_carets(gid, 1), Some(vec![f64::from(point.x)]));
assert_eq!(face.vertical_ligature_carets(gid, 1, 1000.0, 1500.0), Some(vec![1000.0 - f64::from(point.y)]));
let bad = db_with(Some(contour_caret_font(u16::MAX)));
assert_eq!(bad.face(LIGATURE_CARET_FAMILY, "Regular").unwrap().ligature_carets(gid, 1), None);
}
/// `count` glyph ids of [`contour_caret_font`] other than the ligature's.
fn spare_gids(count: usize) -> Vec<u16> {
let ligature = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph");
(1..).filter(|g| *g != ligature).take(count).collect()
}
/// [`contour_caret_font`], whose caret is the ligature's point 0, with its `glyf` and `loca`
/// replaced: each `(gid, data)` in `glyphs` gives that glyph's `glyf` data, and every other glyph
/// is empty.
fn glyf_caret_font(glyphs: &[(u16, Vec<u8>)]) -> Vec<u8> {
use skrifa::raw::TableProvider;
use write_fonts::FontBuilder;
use write_fonts::types::Tag;
let base = contour_caret_font(0);
let font = skrifa::FontRef::new(&base).expect("test font parses");
let num_glyphs = font.maxp().expect("maxp reads").num_glyphs();
let short_loca = font.head().expect("head reads").index_to_loc_format() == 0;
let mut glyf = Vec::new();
let mut offsets = vec![0usize];
for gid in 0..num_glyphs {
if let Some((_, data)) = glyphs.iter().find(|(g, _)| *g == gid) {
glyf.extend(data);
// Keep every offset even for the short `loca` format.
if glyf.len() % 2 == 1 {
glyf.push(0);
}
}
offsets.push(glyf.len());
}
let loca: Vec<u8> = if short_loca {
offsets.iter().flat_map(|o| u16::try_from(o / 2).expect("short offset").to_be_bytes()).collect()
} else {
offsets.iter().flat_map(|o| u32::try_from(*o).expect("long offset").to_be_bytes()).collect()
};
let mut builder = FontBuilder::new();
builder.add_raw(Tag::new(b"glyf"), glyf);
builder.add_raw(Tag::new(b"loca"), loca);
for record in font.table_directory.table_records() {
let tag = Tag::new(&record.tag().to_be_bytes());
if !builder.contains(tag) {
builder.add_raw(tag, font.table_data(record.tag()).expect("base table reads").as_bytes());
}
}
builder.build()
}
/// [`glyf_caret_font`] whose ligature is a composite of eight copies of a glyph that is itself
/// eight copies of the next, 15 levels down to a glyph with no contours.
fn composite_fan_caret_font() -> Vec<u8> {
const FAN: usize = 8;
let ligature = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph");
let levels = spare_gids(15);
let composite = |child: u16| {
let mut data = vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0];
for i in 0..FAN {
// ARGS_ARE_XY_VALUES, plus MORE_COMPONENTS on all but the last; byte offsets of 0.
let flags: u16 = if i + 1 < FAN { 0x0022 } else { 0x0002 };
data.extend(flags.to_be_bytes());
data.extend(child.to_be_bytes());
data.extend([0, 0]);
}
data
};
let mut glyphs = vec![(ligature, composite(levels[0]))];
for (level, gid) in levels.iter().enumerate() {
match levels.get(level + 1) {
Some(child) => glyphs.push((*gid, composite(*child))),
// No contours, a zero bounding box and no instructions.
None => glyphs.push((*gid, vec![0; 12])),
}
}
glyf_caret_font(&glyphs)
}
/// A contour-point caret on a composite's point uses the component offset the outline loader
/// uses. The ligature is one component, a glyph with a single point at (50, 0), turned a quarter
/// turn and scaled by 1.5 with a two-by-two matrix and placed at (100, 0). With
/// SCALED_COMPONENT_OFFSET the offset's x scales by the length of the x basis, 1.5, so the point
/// lands at x = 150; with UNSCALED_COMPONENT_OFFSET as well the offset stays (100, 0).
#[test]
fn a_contour_point_caret_on_a_composite_takes_its_scaled_offset() {
let gid = source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph");
let [leaf] = spare_gids(1)[..] else { panic!("one spare glyph") };
// One on-curve point at (50, 0) with word coordinates, and no instructions.
let mut point = vec![0, 1, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0x01];
point.extend(50i16.to_be_bytes());
point.extend(0i16.to_be_bytes());
let composite = |offset_flags: u16| {
// ARG_1_AND_2_ARE_WORDS, ARGS_ARE_XY_VALUES and WE_HAVE_A_TWO_BY_TWO.
let flags = 0x0083 | offset_flags;
let mut data = vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0];
data.extend(flags.to_be_bytes());
data.extend(leaf.to_be_bytes());
data.extend(100i16.to_be_bytes());
data.extend(0i16.to_be_bytes());
// xx = 0, yx = 1.5, xy = -1.5, yy = 0 in F2Dot14.
for f2dot14 in [0x0000u16, 0x6000, 0xa000, 0x0000] {
data.extend(f2dot14.to_be_bytes());
}
data
};
let caret = |offset_flags: u16| {
let db = db_with(Some(glyf_caret_font(&[(gid, composite(offset_flags)), (leaf, point.clone())])));
db.face(LIGATURE_CARET_FAMILY, "Regular").unwrap().ligature_carets(u32::from(gid), 1)
};
// SCALED_COMPONENT_OFFSET, then with UNSCALED_COMPONENT_OFFSET too.
assert_eq!(caret(0x0800), Some(vec![150.0]));
assert_eq!(caret(0x1800), Some(vec![100.0]));
}
/// A contour-point caret on a composite that expands to billions of glyphs with no points gives
/// no caret, and quickly, rather than reading every one of them.
#[test]
fn a_contour_point_caret_on_a_huge_empty_composite_gives_up() {
let gid = u32::from(source_sans_gid(LIGATURE_CARET_GLYPH).expect("Source Sans 3 has the glyph"));
let (send, receive) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let db = db_with(Some(composite_fan_caret_font()));
let carets = db.face(LIGATURE_CARET_FAMILY, "Regular").map(|face| face.ligature_carets(gid, 1));
let _ = send.send(carets);
});
let carets = receive.recv_timeout(std::time::Duration::from_secs(30)).expect("the caret lookup finishes");
assert_eq!(carets, Some(None));
}
fn point(text: &str, family: &str) -> TextObject {
TextObject::point(Point::ZERO, text, CharStyle { font_family: family.into(), size: 100.0, ..CharStyle::default() })
}
@@ -459,6 +628,66 @@ fn an_upright_ligature_takes_its_caret_down_its_cell() {
assert!((at(900) - 0.5).abs() < 1e-9, "{}", at(900));
}
/// On a path, an upright ligature in vertical type turns about its pen, so its cell runs from
/// 0.12 em before the pen to 0.88 em after it, with or without the font's vertical metrics. The
/// inner stop lies at the middle of that cell, and the first character's selection ends there.
#[test]
fn an_upright_ligature_on_a_path_takes_its_stop_in_its_turned_cell() {
for (font, family) in [(ligature_caret_font(None), LIGATURE_CARET_FAMILY), (vertical_ligature_caret_font(900), VERTICAL_LIGATURE_CARET_FAMILY)] {
let db = db_with(font);
let mut line = BezPath::new();
line.move_to((0.0, 0.0));
line.line_to((1000.0, 0.0));
let mut t = point("fi", family);
t.vertical = true;
t.runs[0].style.standard_vertical_roman = true;
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None };
let l = layout(&db, &t);
assert!(l.on_path);
let Some(g) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) };
assert_eq!(g.carets, vec![(1, 0.5)], "{family}");
assert!((g.width - 100.0).abs() < 1e-9 && (g.width_start + 12.0).abs() < 1e-9, "{family}: {} {}", g.width, g.width_start);
let x = |b| caret_position(&l, b).0.x - g.origin.x;
assert!((x(1) - 38.0).abs() < 1e-6, "{family}: {}", x(1));
let q = selection_quads(&l, 0, 1);
assert_eq!(q.len(), 1, "{q:?}");
assert!(((q[0][1] - q[0][0]).hypot() - 38.0).abs() < 1e-6, "{family}: {q:?}");
// A baseline shift moves the turned glyph along the path, and its stop with it.
let ink = g.outline.bounding_box().x0;
t.runs[0].style.baseline_shift = 10.0;
let l = layout(&db, &t);
let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) };
let moved = s.outline.bounding_box().x0 - ink;
assert!(moved.abs() > 1.0, "{family}: the shift moves the glyph along the path: {moved}");
let stop = caret_position(&l, 1).0.x - s.origin.x;
assert!((stop - 38.0 - moved).abs() < 1e-6, "{family}: {stop} against {}", 38.0 + moved);
// Horizontal Scale widens the glyph across the path; its stop stays inside the glyph.
t.runs[0].style.baseline_shift = 0.0;
t.runs[0].style.h_scale = 200.0;
let l = layout(&db, &t);
let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) };
let bounds = s.outline.bounding_box();
let stop = caret_position(&l, 1).0.x - s.origin.x;
assert!(bounds.x0 < stop && stop < bounds.x1 && stop > 0.0, "{family}: {stop} outside {bounds:?}");
t.runs[0].style.h_scale = 100.0;
// Skew on a slanted path: the stop stays inside the drawn glyph along the path.
let mut slant = BezPath::new();
slant.move_to((0.0, 0.0));
slant.line_to((1000.0, 1000.0));
t.runs[0].style.baseline_shift = 0.0;
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&slant), start: 0.0, end: None };
t.path_effect = vectorcraft_doc::PathEffect::Skew;
let l = layout(&db, &t);
let Some(s) = l.glyphs.iter().find(|g| g.len == 2) else { panic!("f + i is one glyph: {:?}", l.glyphs) };
let tangent = Vec2::new(s.angle.cos(), s.angle.sin());
let ink = s.outline.elements().iter().filter_map(|el| el.end_point()).map(|p| (p - s.origin).dot(tangent));
let (lo, hi) = ink.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), d| (lo.min(d), hi.max(d)));
let (a, b) = caret_position(&l, 1);
let stop = (a.midpoint(b) - s.origin).dot(tangent);
assert!(lo < stop && stop < hi, "{family}: {stop} outside {lo}..{hi}");
}
}
/// Tracking that makes an upright ligature's advance negative leaves it upright: it keeps its
/// caret down its cell, and its cell starts where it does without tracking, with or without the
/// font's vertical metrics.
+39 -4
View File
@@ -352,13 +352,16 @@ impl Tool for DimensionTool {
}
PointerKind::Down => {
if self.pending.is_some() && !self.dragging {
// The second click of a picked measurement places it.
return self.place(cx, ev.pos);
self.press = Some((ev.pos, None));
return vec![];
}
self.press = Some((ev.pos, self.target(cx, ev.pos)));
vec![]
}
PointerKind::Drag => {
if self.pending.is_some() && !self.dragging && self.press.is_some() {
return self.preview(cx, ev.pos);
}
if self.pending.is_none()
&& let Some((start, Some(target))) = self.press.clone()
&& start.distance(ev.pos) > cx.tol(3.0)
@@ -374,8 +377,11 @@ impl Tool for DimensionTool {
if self.dragging {
return self.place(cx, ev.pos);
}
if self.pending.is_some() {
return if self.press.take().is_some() { self.place(cx, ev.pos) } else { vec![] };
}
match self.press.take() {
Some((start, target)) if self.pending.is_none() => self.click(cx, start, target, ev.mods),
Some((start, target)) => self.click(cx, start, target, ev.mods),
_ => vec![],
}
}
@@ -397,7 +403,12 @@ impl Tool for DimensionTool {
return self.key(cx, ToolKey::Escape, Mods::default());
}
self.press = None;
vec![]
if self.pending.is_some() && self.began {
self.began = false;
vec![Action::Cancel]
} else {
vec![]
}
}
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
self.key(cx, ToolKey::Escape, Mods::default())
@@ -507,4 +518,28 @@ mod tests {
assert!(!t.busy());
assert!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 60.0)).is_empty(), "the release places nothing");
}
#[test]
fn a_dropped_placement_press_does_not_commit_the_dimension() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y);
let mut t = DimensionTool::default();
for (x, y) in [(400.0, 400.0), (450.0, 420.0)] {
assert!(t.pointer(&c, &ev(PointerKind::Down, x, y)).is_empty());
assert!(t.pointer(&c, &ev(PointerKind::Up, x, y)).is_empty());
}
assert!(t.pending.is_some());
assert!(matches!(t.pointer(&c, &ev(PointerKind::Move, 470.0, 450.0)).first(), Some(Action::Begin(_))));
assert!(t.pointer(&c, &ev(PointerKind::Down, 470.0, 450.0)).is_empty());
assert_eq!(t.drop_press(&c), vec![Action::Cancel]);
assert!(t.pointer(&c, &ev(PointerKind::Up, 470.0, 450.0)).is_empty());
assert!(t.pending.is_some(), "the dimension can still be placed");
assert!(t.pointer(&c, &ev(PointerKind::Down, 480.0, 460.0)).is_empty());
let dragged = t.pointer(&c, &ev(PointerKind::Drag, 490.0, 470.0));
assert!(matches!(dragged.last(), Some(Action::Preview(_, _))), "{dragged:?}");
let placed = t.pointer(&c, &ev(PointerKind::Up, 490.0, 470.0));
assert!(matches!(placed.last(), Some(Action::Commit)), "{placed:?}");
}
}
+1 -1
View File
@@ -323,7 +323,7 @@ pub(crate) const MAX_STROKE_SAMPLES: usize = 100_000;
/// `n / PREVIEW_ALL_UNTIL` samples. Each preview carries every sample so far, so previewing at
/// every sample cost the square of the stroke's length (a gesture of many drags sent at once
/// spent seconds); this way it is about `PREVIEW_ALL_UNTIL` per sample.
const PREVIEW_ALL_UNTIL: usize = 1000;
pub(crate) const PREVIEW_ALL_UNTIL: usize = 1000;
/// Whether a drag that made the stroke `n` samples long previews it ([`PREVIEW_ALL_UNTIL`]).
pub(crate) fn previews_at(n: usize) -> bool {
+25 -3
View File
@@ -90,7 +90,7 @@ impl Tool for BlendTool {
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let options = |t: &mut Self| {
(t.first, t.chained) = (None, false);
(t.first, t.chained, t.before_press) = (None, false, None);
vec![Action::Dialog(BLEND_OPTIONS.into(), json!({}))]
};
// A first pick whose object is no longer in the document (deleted, or undone away) is
@@ -157,7 +157,7 @@ impl Tool for BlendTool {
/// click picks a new first object. The document and the selection stay as they are.
fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec<Action> {
if key == crate::ToolKey::Escape {
(self.first, self.chained) = (None, false);
(self.first, self.chained, self.before_press) = (None, false, None);
}
vec![]
}
@@ -171,7 +171,7 @@ impl Tool for BlendTool {
vec![]
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
(self.first, self.chained) = (None, false);
(self.first, self.chained, self.before_press) = (None, false, None);
vec![]
}
/// Choosing the Blend tool again finishes the blend: it drops the object picked first and
@@ -382,6 +382,28 @@ mod tests {
assert!(create("mesh").unwrap().chosen_again(&c).is_empty());
}
#[test]
fn resetting_blend_during_a_press_survives_its_drop() {
let (d, a) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let c = cx(&d, &s, &p);
for reset in 0..3 {
let mut t = BlendTool { first: Some((a, None)), chained: true, ..Default::default() };
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 450.0, 450.0)).is_empty());
match reset {
0 => assert!(t.key(&c, ToolKey::Escape, Mods::default()).is_empty()),
1 => assert!(t.chosen_again(&c).is_empty()),
_ => assert_eq!(
t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 450.0, 450.0)),
vec![Action::Dialog(BLEND_OPTIONS.into(), json!({}))],
),
}
assert!(t.drop_press(&c).is_empty());
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 450.0, 450.0)).is_empty());
assert_eq!((t.first, t.chained), (None, false));
}
}
#[test]
fn blend_tool_picks_again_when_its_first_pick_is_gone() {
let (mut d, a) = doc_with_rect();
+72 -12
View File
@@ -11,7 +11,7 @@ use serde_json::{Value, json};
use vectorcraft_geom::{Point, Shape};
use crate::draw2::{FEEDBACK, GestureTool, points_json};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
use crate::{Action, Cursor, MAX_STROKE_SAMPLES, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, previews_at};
/// Create a symbolism tool or the brush-aware Paintbrush (None = not one of ours).
pub fn create(id: &str) -> Option<Box<dyn Tool>> {
@@ -26,6 +26,8 @@ pub fn create(id: &str) -> Option<Box<dyn Tool>> {
pub struct SymbolismTool {
id: &'static str,
points: Vec<Point>,
/// How many points the last preview had ([`previews_at`] thins previews of a long drag).
previewed: usize,
active: bool,
hover: Option<Point>,
alt: bool,
@@ -53,7 +55,19 @@ impl SymbolismTool {
"symbolStyler" => "symbolStyler",
_ => "symbolSprayer",
};
Self { id, points: vec![], active: false, hover: None, alt: false, diameter: 80.0, intensity: 5.0, density: 5.0, symbol: None, style: None }
Self {
id,
points: vec![],
previewed: 0,
active: false,
hover: None,
alt: false,
diameter: 80.0,
intensity: 5.0,
density: 5.0,
symbol: None,
style: None,
}
}
fn label(&self) -> &'static str {
@@ -103,6 +117,19 @@ impl SymbolismTool {
}
}
impl SymbolismTool {
/// Ends the drag: what is committed is the last preview, so the whole drag is shown first.
fn finish(&mut self, cx: &ToolContext) -> Vec<Action> {
self.active = false;
let stale = (self.previewed != self.points.len()).then(|| {
let (c, v) = self.command(cx);
Action::Preview(c, v)
});
self.points.clear();
stale.into_iter().chain([Action::Commit]).collect()
}
}
impl Tool for SymbolismTool {
fn id(&self) -> &'static str {
self.id
@@ -116,6 +143,7 @@ impl Tool for SymbolismTool {
match ev.kind {
PointerKind::Down => {
self.points = vec![p];
self.previewed = 1;
self.active = true;
self.alt = ev.mods.alt;
let (c, v) = self.command(cx);
@@ -124,18 +152,19 @@ impl Tool for SymbolismTool {
PointerKind::Drag if self.active => {
// Sprayer: thin the samples to a fraction of the brush; others: every few pixels.
let step = if self.id == "symbolSprayer" { (self.diameter * 0.15).max(cx.tol(3.0)) } else { cx.tol(3.0) };
if self.points.last().is_some_and(|l| l.distance(p) < step) {
// Each preview carries every point so far: a long drag stops growing and previews less often.
if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|l| l.distance(p) < step) {
return vec![];
}
self.points.push(p);
if !previews_at(self.points.len()) {
return vec![];
}
self.previewed = self.points.len();
let (c, v) = self.command(cx);
vec![Action::Preview(c, v)]
}
PointerKind::Up if self.active => {
self.active = false;
self.points.clear();
vec![Action::Commit]
}
PointerKind::Up if self.active => self.finish(cx),
_ => vec![],
}
}
@@ -157,11 +186,9 @@ impl Tool for SymbolismTool {
}
vec![]
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
if self.active {
self.active = false;
self.points.clear();
return vec![Action::Commit];
return self.finish(cx);
}
vec![]
}
@@ -294,6 +321,39 @@ mod tests {
assert!(!t.busy());
}
#[test]
fn a_long_drag_previews_less_often_and_commits_all_of_it() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut t = SymbolismTool::new("symbolShifter");
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
let n = 7 * crate::PREVIEW_ALL_UNTIL + 1; // not a point that previews
let previews = (1..n).filter(|&i| !t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 50.0 * i as f64, 0.0)).is_empty()).count();
assert!(previews < n * 3 / 4, "{previews} previews of {n} points");
let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 0.0, 0.0));
let last = up.iter().rev().nth(1);
assert!(matches!(last, Some(Action::Preview(_, v)) if v["points"].as_array().unwrap().len() == n), "{up:?}");
assert_eq!(up.last(), Some(&Action::Commit));
}
#[test]
fn switching_tools_mid_drag_previews_the_whole_drag_before_committing() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut t = SymbolismTool::new("symbolShifter");
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
let n = 7 * crate::PREVIEW_ALL_UNTIL + 1; // not a point that previews
for i in 1..n {
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 50.0 * i as f64, 0.0));
}
let a = t.deactivate(&cx);
assert!(matches!(a.first(), Some(Action::Preview(_, v)) if v["points"].as_array().unwrap().len() == n), "{a:?}");
assert_eq!(a.last(), Some(&Action::Commit));
assert!(!t.busy());
}
#[test]
fn adjust_tools_map_to_symbol_adjust() {
let (d, _) = doc_with_rect();
+51 -2
View File
@@ -27,7 +27,9 @@ pub fn measure(a: Point, b: Point) -> (f64, f64, f64, f64) {
/// it. With Shift held, the end stays on the 45° step from the Constrain Angle nearest the
/// pointer's direction: `p` is projected onto the step, then snapped along it as the Line Segment
/// tool snaps a Shift-drawn end. With Snap to Point alone, the point `p` snaps to (an anchor, or
/// in line with a ruler guide) is projected instead.
/// in line with a ruler guide) is projected instead. When the snapped point lies nearer another
/// step (the grid rounds it past the halfway angle) or behind the start, it is turned back onto
/// the pointer's step.
pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Point {
if !shift {
return crate::guides::snap_draw(cx, p, &[]).0;
@@ -42,7 +44,9 @@ pub(crate) fn end_point(cx: &ToolContext, a: Point, p: Point, shift: bool) -> Po
let s = if to_point { crate::guides::snap_draw(cx, p, &[]).0 } else { p };
let q = a + u * (s - a).dot(u);
let leave = crate::guides::Leave::segment(cx, a, true);
crate::guides::PointSnap::new(cx, || crate::guides::Targets::collect(cx.doc, &[], None)).snap_from(cx, q, Some(&leave)).0
let r = crate::guides::PointSnap::new(cx, || crate::guides::Targets::collect(cx.doc, &[], None)).snap_from(cx, q, Some(&leave)).0;
let v = r - a;
if v.cross(u).abs() <= 1e-9 * v.hypot().max(1.0) && v.dot(u) >= 0.0 { r } else { a + u * v.hypot() }
}
impl Tool for MeasureTool {
@@ -222,6 +226,51 @@ mod tests {
assert!((o["dy"].as_f64().unwrap() + 100.0).abs() < 1e-9, "{o}");
}
/// With a Constrain Angle of 30°, the grid point a Shift-drag's end rounds to can lie nearer
/// another step; the end stays on the step nearest the pointer's direction.
#[test]
fn shift_drag_keeps_its_step_after_the_grid_rounds_it() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let mut cx = cx(&d, &s, &p);
cx.smart_guides = false;
cx.snap_to_grid = true;
cx.constrain_angle = 30.0;
let shift = Mods { shift: true, ..Mods::default() };
let mut t = MeasureTool::default();
// (5, -3) points 31° up, so the step is 30°; the end lands at about (5.05, -2.92), which
// the 9 pt grid rounds to (9, 0), nearer the -15° step.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 5.0, -3.0).with_mods(shift));
let o = t.options();
assert!((o["angle"].as_f64().unwrap() - 30.0).abs() < 1e-9, "{o}");
}
/// With Snap to Point alone, an anchor behind the start can pull the projected end behind it;
/// the end is turned back onto the pointer's step instead of reading 180°.
#[test]
fn shift_drag_keeps_its_step_when_an_anchor_lies_behind_the_start() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let mut cx = cx(&d, &s, &p);
cx.smart_guides = false;
cx.snap_tolerance = 4.0;
cx.snapping_tolerance = 4.0;
assert!(cx.snap_to_point);
let shift = Mods { shift: true, ..Mods::default() };
let mut t = MeasureTool::default();
// From (200.3, 196.005), the pointer at (202.3, 196.805) points 0° and snaps to the anchor
// at (200, 200), which projects onto the 0° line at (200, 196.005), behind the start.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.3, 196.005));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 202.3, 196.805).with_mods(shift));
let o = t.options();
assert!(o["angle"].as_f64().unwrap().abs() < 1e-9, "{o}");
assert!((o["dx"].as_f64().unwrap() - 0.3).abs() < 1e-9, "{o}");
assert!(o["dy"].as_f64().unwrap().abs() < 1e-9, "{o}");
}
/// With Snap to Point alone, a Shift-drag's end slides along its 45° step to a ruler guide.
#[test]
fn shift_drag_meets_a_ruler_guide() {
+79 -5
View File
@@ -331,7 +331,9 @@ impl Layers<'_> {
}
}
}
for comp in comps {
// One component's paths: a pure function of its loops and the shared read-only state, so components are fitted in
// parallel and then added in order.
let fit_comp = |comp: &contour::Component| -> Option<(PathData, Option<TracedShape>)> {
// (`hard`: some of the outline has no anti-aliasing, and is known less exactly.)
let hard = std::cell::Cell::new(false);
// (Each loop fitted, and whether its own outline is hard.)
@@ -355,7 +357,7 @@ impl Layers<'_> {
hard.set(hard.get() || is_hard);
Some((sp, is_hard))
};
let Some((outer, _)) = fit(&comp.outer) else { continue };
let (outer, _) = fit(&comp.outer)?;
let mut subs = vec![outer];
for hole in &comp.holes {
if hole.area2.abs() / 2 < min_hole && params.noise > 0 {
@@ -398,9 +400,16 @@ impl Layers<'_> {
_ => None,
};
let path = shape.map_or_else(|| PathData::new(subs), |s| s.path());
if !add(path, comp.pixels, area_stroke, shape, false) {
return None;
}
Some((path, shape))
};
// In chunks, so that the anchor budget still stops the work early: a hostile image is refused after fitting at most
// the rest of one chunk, not after every component is fitted.
let accepted = fit_in_chunks(&comps, FIT_CHUNK, fit_comp, |comp, fitted| {
let Some((path, shape)) = fitted else { return true };
add(path, comp.pixels, area_stroke, shape, false)
});
if !accepted {
return None;
}
for line in lines {
if !add(line.path, line.pixels, Some(line.width), None, line.square) {
@@ -452,6 +461,24 @@ pub(crate) fn shift_probe(img: &Raster, params: &TraceParams) -> Vec<[f64; 4]> {
out
}
/// How many components of a layer are fitted at a time (see `fit_in_chunks`).
const FIT_CHUNK: usize = 256;
/// `fit` of each of `items` over the available cores, `chunk` items at a time, each result handed to `accept` in item
/// order. Stops after the chunk in which `accept` returns false, and says whether it never did.
fn fit_in_chunks<T: Sync, R: Send>(items: &[T], chunk: usize, fit: impl Fn(&T) -> R + Sync, mut accept: impl FnMut(&T, R) -> bool) -> bool {
for part in items.chunks(chunk.max(1)) {
// (A few components are not worth starting threads for.)
let fitted = if part.len() < 16 { part.iter().map(&fit).collect() } else { parallel_map(part, &fit) };
for (item, result) in part.iter().zip(fitted) {
if !accept(item, result) {
return false;
}
}
}
true
}
/// `f` of each of `items`, in order, spread over the available cores.
pub(crate) fn parallel_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
parallel_map_at_most(usize::MAX, items, f)
@@ -492,3 +519,50 @@ pub(crate) fn parallel_map_at_most<T: Sync, R: Send>(at_a_time: usize, items: &[
pub(crate) fn parallel_map_at_most<T: Sync, R: Send>(_: usize, items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
items.iter().map(f).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fit_in_chunks_keeps_the_order_and_stops_at_the_first_refusal() {
let items: Vec<usize> = (0..1000).collect();
let fitted = AtomicUsize::new(0);
let mut seen = vec![];
let all = fit_in_chunks(
&items,
16,
|&i| {
fitted.fetch_add(1, Ordering::Relaxed);
i * 2
},
|&i, r| {
assert_eq!(r, i * 2);
seen.push(i);
seen.len() <= 10
},
);
assert!(!all);
// Items come in order, up to and including the one refused.
assert_eq!(seen, (0..=10).collect::<Vec<_>>());
// The early stop is kept: only the chunk holding the refusal was fitted, not the other 984 items.
assert_eq!(fitted.load(Ordering::Relaxed), 16);
}
#[test]
fn fit_in_chunks_accepts_everything_in_order() {
let items: Vec<usize> = (0..1000).collect();
let mut out = vec![];
assert!(fit_in_chunks(
&items,
7,
|&i| i + 1,
|_, r| {
out.push(r);
true
}
));
assert_eq!(out, (1..=1000).collect::<Vec<_>>());
assert!(fit_in_chunks(&[] as &[usize], 7, |&i| i, |_, _| false));
}
}
+64 -1
View File
@@ -2,6 +2,7 @@
use kurbo::Vec2;
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use vectorcraft_geom::Point;
/// One cubic Bézier segment: start, two handles, end.
@@ -315,13 +316,39 @@ pub(crate) fn sample_cubics(cs: &[Cubic], spacing: f64) -> Vec<Point> {
out
}
/// Multiply-and-rotate hasher for the small integer cell keys of [`all_within`]. The grid is only ever looked up, never
/// iterated, so the hash cannot change a result; std's SipHash took about a quarter of the time of a noisy trace.
#[derive(Default)]
struct CellHasher(u64);
impl CellHasher {
fn add(&mut self, word: u64) {
self.0 = (self.0.rotate_left(5) ^ word).wrapping_mul(0x517c_c1b7_2722_0a95);
}
}
impl Hasher for CellHasher {
fn write(&mut self, bytes: &[u8]) {
bytes.iter().for_each(|&b| self.add(u64::from(b)));
}
fn write_i64(&mut self, word: i64) {
self.add(word as u64);
}
fn finish(&self) -> u64 {
// The table picks its bucket from the low bits, which a product leaves weak: bring the strong high bits down.
self.0.rotate_left(26)
}
}
/// True when every point of `a` has a point of `b` within `lim`.
pub(crate) fn all_within(a: &[Point], b: &[Point], lim: f64) -> bool {
if lim.is_nan() || lim <= 0.0 {
return false;
}
let key = |p: Point| ((p.x / lim).floor() as i64, (p.y / lim).floor() as i64);
let mut grid: HashMap<(i64, i64), Vec<Point>> = HashMap::new();
let mut grid: HashMap<(i64, i64), Vec<Point>, BuildHasherDefault<CellHasher>> = HashMap::default();
for &q in b {
grid.entry(key(q)).or_default().push(q);
}
@@ -426,4 +453,40 @@ mod tests {
assert!(!all_within(&a, &b, 0.1));
assert!(!all_within(&a, &b, 0.0));
}
#[test]
fn within_agrees_with_a_brute_force_search() {
let mut state = 0x9e37_79b9_7f4a_7c15_u64;
let mut rand = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 11) as f64 / (1u64 << 53) as f64
};
for round in 0..60 {
// Negative and large coordinates, clustered and sparse clouds.
let spread = [3.0, 40.0, 1.0e5][round % 3];
let cloud = |n: usize, rand: &mut dyn FnMut() -> f64| -> Vec<Point> {
(0..n).map(|_| Point::new((rand() - 0.5) * spread, (rand() - 0.5) * spread)).collect()
};
let a = cloud(1 + round % 7, &mut rand);
let mut b = cloud(200, &mut rand);
b.extend(a.iter().map(|p| Point::new(p.x + (rand() - 0.5) * 0.3, p.y + (rand() - 0.5) * 0.3)));
for lim in [0.05, 0.2, 1.5, 30.0] {
let brute = a.iter().all(|&p| b.iter().any(|q| q.distance(p) <= lim));
assert_eq!(all_within(&a, &b, lim), brute, "round {round}, lim {lim}");
assert_eq!(all_within(&b, &a, lim), b.iter().all(|&p| a.iter().any(|q| q.distance(p) <= lim)), "round {round}, lim {lim}");
}
}
}
#[test]
fn cell_hasher_spreads_keys_whose_low_bits_are_zero() {
use std::hash::BuildHasher;
// Cell indices that are all multiples of 1024 (pixel-exact points with a power-of-two limit).
let build = BuildHasherDefault::<CellHasher>::default();
let buckets: std::collections::HashSet<u64> =
(0..64i64).flat_map(|i| (0..64i64).map(move |j| (i << 10, j << 10))).map(|k| build.hash_one(k) & 1023).collect();
assert!(buckets.len() > 600, "{} of 1024 buckets used", buckets.len());
}
}
+246 -54
View File
@@ -13,94 +13,286 @@ pub fn denoise(labels: &mut [u16], w: usize, h: usize, min_area: usize) {
/// clears specks, not a colour's only regions. Smaller regions of it go as any other.
pub(crate) fn denoise_keeping(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool]) {
use std::cmp::Reverse;
use std::collections::{BTreeMap, BinaryHeap};
use std::collections::BinaryHeap;
if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) {
// Every index below is a `u32`, so a pixel costs 8 bytes and a region 18 instead of a `Vec<usize>` per region. An image
// of `u32::MAX` pixels or more (far above the decoder's cap) is left as it is.
const NONE: u32 = u32::MAX;
if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) || labels.len() >= NONE as usize {
return;
}
struct Region {
label: u16,
pixels: Vec<usize>,
}
// Region membership is kept current after every merge. In particular, no stale `seen`
// flags can exclude previously recoloured pixels from a subsequent connected component.
let mut at = vec![usize::MAX; labels.len()];
let mut regions: Vec<Region> = Vec::new();
// Region of each pixel as first found (`NONE` for transparent). A merge does not touch it: the region a pixel
// belongs to now is `find(at[i])`.
let mut at = vec![NONE; labels.len()];
// Pixels of a region form a singly linked list through `next`, so absorbing a region is one pointer write.
let mut next = vec![NONE; labels.len()];
let mut head: Vec<u32> = Vec::new();
let mut tail: Vec<u32> = Vec::new();
let mut size: Vec<u32> = Vec::new();
let mut colour: Vec<u16> = Vec::new();
// Union-find over region ids: a region absorbed into another points at it.
let mut parent: Vec<u32> = Vec::new();
let neighbours = |i: usize| {
let (x, y) = (i % w, i / w);
[(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]
};
for start in 0..labels.len() {
if at[start] != usize::MAX || labels[start] == TRANSPARENT {
if at[start] != NONE || labels[start] == TRANSPARENT {
continue;
}
let id = regions.len();
let id = head.len() as u32;
let label = labels[start];
let mut pixels = vec![start];
at[start] = id;
let mut cursor = 0;
while let Some(&i) = pixels.get(cursor) {
for j in neighbours(i).into_iter().flatten() {
if at[j] == usize::MAX && labels[j] == label {
let mut last = start;
let mut count = 1u32;
let mut cursor = start;
loop {
for j in neighbours(cursor).into_iter().flatten() {
if at[j] == NONE && labels[j] == label {
at[j] = id;
pixels.push(j);
next[last] = j as u32;
last = j;
count += 1;
}
}
cursor += 1;
match next[cursor] {
NONE => break,
n => cursor = n as usize,
}
}
regions.push(Region { label, pixels });
head.push(start as u32);
tail.push(last as u32);
size.push(count);
colour.push(label);
parent.push(id);
}
let mut pending: BinaryHeap<_> = regions.iter().enumerate().map(|(id, r)| Reverse((r.pixels.len(), id))).collect();
while let Some(Reverse((area, id))) = pending.pop() {
if area >= min_area {
break;
fn find(parent: &mut [u32], mut a: u32) -> u32 {
while parent[a as usize] != a {
let up = parent[parent[a as usize] as usize];
parent[a as usize] = up;
a = up;
}
if regions[id].pixels.len() != area {
a
}
// Only regions below `min_area` are ever taken from the queue; a larger one ends the loop.
let mut pending: BinaryHeap<_> =
(0..size.len() as u32).filter(|&id| (size[id as usize] as usize) < min_area).map(|id| Reverse((size[id as usize], id))).collect();
// Scratch for one merge: `(other region, shared pixel edges)` and `(colour, shared pixel edges)`.
let mut borders: Vec<(u32, usize)> = Vec::new();
let mut by_colour: Vec<(u16, usize)> = Vec::new();
while let Some(Reverse((area, id))) = pending.pop() {
if size[id as usize] != area {
continue; // absorbed region or an old heap entry for a region that grew
}
if area >= RARE_ISLAND && keep.get(regions[id].label as usize).copied().unwrap_or(false) {
if area as usize >= RARE_ISLAND && keep.get(colour[id as usize] as usize).copied().unwrap_or(false) {
continue;
}
let mut borders: BTreeMap<usize, usize> = BTreeMap::new();
for &i in &regions[id].pixels {
for j in neighbours(i).into_iter().flatten() {
let other = at[j];
if other != id && other != usize::MAX {
*borders.entry(other).or_default() += 1;
borders.clear();
// Pairs are folded together whenever the list doubles, so a big region keeps it short.
let mut limit = 4096;
let mut pixel = head[id as usize];
while pixel != NONE {
for j in neighbours(pixel as usize).into_iter().flatten() {
if at[j] != NONE {
let other = find(&mut parent, at[j]);
if other != id {
borders.push((other, 1));
}
}
}
pixel = next[pixel as usize];
if borders.len() >= limit {
merge_counts(&mut borders);
limit = limit.max(2 * borders.len());
}
}
let mut colours: BTreeMap<u16, usize> = BTreeMap::new();
for (&other, &border) in &borders {
*colours.entry(regions[other].label).or_default() += border;
}
let Some((&colour, _)) = colours.iter().max_by_key(|(label, border)| (**border, Reverse(**label))) else {
merge_counts(&mut borders);
by_colour.clear();
by_colour.extend(borders.iter().map(|&(other, border)| (colour[other as usize], border)));
merge_counts(&mut by_colour);
let Some(&(chosen, _)) = by_colour.iter().max_by_key(|(label, border)| (*border, Reverse(*label))) else {
continue; // an opaque island surrounded only by transparency stays intact
};
// All adjacent regions of the chosen colour become connected by this merge. Absorb
// them together, keeping the largest one's storage to avoid repeatedly moving it.
// them together, keeping the largest one as the survivor.
let Some(target) = borders
.keys()
.copied()
.filter(|&other| regions[other].label == colour)
.max_by_key(|&other| (regions[other].pixels.len(), Reverse(other)))
.iter()
.map(|&(other, _)| other)
.filter(|&other| colour[other as usize] == chosen)
.max_by_key(|&other| (size[other as usize], Reverse(other)))
else {
continue;
};
let sources: Vec<_> =
std::iter::once(id).chain(borders.keys().copied().filter(|&other| other != target && regions[other].label == colour)).collect();
for source in sources {
let pixels = std::mem::take(&mut regions[source].pixels);
for &i in &pixels {
at[i] = target;
}
regions[target].pixels.extend(pixels);
for source in
std::iter::once(id).chain(borders.iter().map(|&(other, _)| other).filter(|&other| other != target && colour[other as usize] == chosen))
{
next[tail[target as usize] as usize] = head[source as usize];
tail[target as usize] = tail[source as usize];
size[target as usize] += size[source as usize];
size[source as usize] = 0;
parent[source as usize] = target;
}
if (size[target as usize] as usize) < min_area {
pending.push(Reverse((size[target as usize], target)));
}
pending.push(Reverse((regions[target].pixels.len(), target)));
}
for region in regions {
for i in region.pixels {
labels[i] = region.label;
for (i, &region) in at.iter().enumerate() {
if region != NONE {
labels[i] = colour[find(&mut parent, region) as usize];
}
}
}
/// Sort `(key, count)` pairs and add up the counts of equal keys.
fn merge_counts<K: Ord + Copy>(pairs: &mut Vec<(K, usize)>) {
pairs.sort_unstable_by_key(|p| p.0);
pairs.dedup_by(|b, a| {
let same = a.0 == b.0;
if same {
a.1 += b.1;
}
same
});
}
#[cfg(test)]
mod tests {
use super::*;
/// The first implementation (a pixel `Vec` per region, `BTreeMap` borders), kept to check that the compact one merges
/// in exactly the same order.
fn denoise_reference(labels: &mut [u16], w: usize, h: usize, min_area: usize, keep: &[bool]) {
use std::cmp::Reverse;
use std::collections::{BTreeMap, BinaryHeap};
if min_area <= 1 || w == 0 || h == 0 || w.checked_mul(h) != Some(labels.len()) {
return;
}
struct Region {
label: u16,
pixels: Vec<usize>,
}
// Region membership is kept current after every merge. In particular, no stale `seen`
// flags can exclude previously recoloured pixels from a subsequent connected component.
let mut at = vec![usize::MAX; labels.len()];
let mut regions: Vec<Region> = Vec::new();
let neighbours = |i: usize| {
let (x, y) = (i % w, i / w);
[(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]
};
for start in 0..labels.len() {
if at[start] != usize::MAX || labels[start] == TRANSPARENT {
continue;
}
let id = regions.len();
let label = labels[start];
let mut pixels = vec![start];
at[start] = id;
let mut cursor = 0;
while let Some(&i) = pixels.get(cursor) {
for j in neighbours(i).into_iter().flatten() {
if at[j] == usize::MAX && labels[j] == label {
at[j] = id;
pixels.push(j);
}
}
cursor += 1;
}
regions.push(Region { label, pixels });
}
let mut pending: BinaryHeap<_> = regions.iter().enumerate().map(|(id, r)| Reverse((r.pixels.len(), id))).collect();
while let Some(Reverse((area, id))) = pending.pop() {
if area >= min_area {
break;
}
if regions[id].pixels.len() != area {
continue; // absorbed region or an old heap entry for a region that grew
}
if area >= RARE_ISLAND && keep.get(regions[id].label as usize).copied().unwrap_or(false) {
continue;
}
let mut borders: BTreeMap<usize, usize> = BTreeMap::new();
for &i in &regions[id].pixels {
for j in neighbours(i).into_iter().flatten() {
let other = at[j];
if other != id && other != usize::MAX {
*borders.entry(other).or_default() += 1;
}
}
}
let mut colours: BTreeMap<u16, usize> = BTreeMap::new();
for (&other, &border) in &borders {
*colours.entry(regions[other].label).or_default() += border;
}
let Some((&colour, _)) = colours.iter().max_by_key(|(label, border)| (**border, Reverse(**label))) else {
continue; // an opaque island surrounded only by transparency stays intact
};
// All adjacent regions of the chosen colour become connected by this merge. Absorb
// them together, keeping the largest one's storage to avoid repeatedly moving it.
let Some(target) = borders
.keys()
.copied()
.filter(|&other| regions[other].label == colour)
.max_by_key(|&other| (regions[other].pixels.len(), Reverse(other)))
else {
continue;
};
let sources: Vec<_> =
std::iter::once(id).chain(borders.keys().copied().filter(|&other| other != target && regions[other].label == colour)).collect();
for source in sources {
let pixels = std::mem::take(&mut regions[source].pixels);
for &i in &pixels {
at[i] = target;
}
regions[target].pixels.extend(pixels);
}
pending.push(Reverse((regions[target].pixels.len(), target)));
}
for region in regions {
for i in region.pixels {
labels[i] = region.label;
}
}
}
fn noisy(w: usize, h: usize, colours: u64, transparent_one_in: u64, seed: u64) -> Vec<u16> {
let mut state = seed;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
(0..w * h).map(|_| if transparent_one_in > 0 && next() % transparent_one_in == 0 { TRANSPARENT } else { (next() % colours) as u16 }).collect()
}
#[test]
fn compact_denoise_matches_the_reference_merge_order() {
for (seed, (w, h, colours, transparent)) in
[(31, 17, 3, 0), (64, 64, 2, 0), (50, 70, 5, 9), (97, 41, 8, 0), (120, 90, 4, 5), (7, 300, 3, 0), (1, 40, 3, 0), (40, 1, 3, 0)]
.into_iter()
.enumerate()
{
let base = noisy(w, h, colours, transparent, seed as u64 + 1);
for min_area in [2, 3, 5, 9, 25, 80, 400, 100_000] {
for keep in [&[][..], &[false, true, false, true][..]] {
let (mut a, mut b) = (base.clone(), base.clone());
denoise_reference(&mut a, w, h, min_area, keep);
denoise_keeping(&mut b, w, h, min_area, keep);
assert_eq!(a, b, "{w}x{h}, {colours} colours, min_area {min_area}, keep {keep:?}");
}
}
}
}
/// A minimum so large that regions keep merging into big ones.
#[test]
fn compact_denoise_matches_the_reference_with_a_large_min_area() {
let (w, h) = (320, 320);
let base = noisy(w, h, 6, 0, 99);
let (mut a, mut b) = (base.clone(), base);
denoise_reference(&mut a, w, h, 50_000, &[]);
denoise_keeping(&mut b, w, h, 50_000, &[]);
assert_eq!(a, b);
}
}
+151 -12
View File
@@ -13,33 +13,54 @@ use crate::{Raster, parallel_map};
/// Colours this far apart (levels, all channels together) count half as much as equal ones.
const ALIKE: f64 = 20.0;
/// One pass along rows (`dx = 1`) or columns (`dx = 0`).
fn pass(src: &[u8], w: usize, h: usize, along_rows: bool) -> Vec<u8> {
/// How much a neighbour counts, by the squared distance between the two colours (all channels
/// together): `1 / (1 + d2 / ALIKE²)²`. Distances are whole numbers, so every value a pass can ask
/// for is worked out once here instead of once per pixel and neighbour.
fn weight_table() -> Vec<f64> {
(0..=3 * 255 * 255usize).map(|d2| 1.0 / (1.0 + d2 as f64 / (ALIKE * ALIKE)).powi(2)).collect()
}
/// `v` rounded to the nearest level, halves up. The same as `v.round() as u8` for `0 <= v <= 255`,
/// without the library call that `round` is on targets that lack a rounding instruction.
fn level(v: f64) -> u8 {
let whole = v as u8;
whole.saturating_add(u8::from(v - f64::from(whole) >= 0.5))
}
/// The pixel at column `x` of `row`.
fn at(row: &[u8], x: usize) -> Option<&[u8]> {
row.get(x * 4..x * 4 + 4)
}
/// One pass along rows (`dx = 1`) or columns (`dx = 0`), weighting by `weights` (see `weight_table`).
fn pass(src: &[u8], w: usize, h: usize, along_rows: bool, weights: &[f64]) -> Vec<u8> {
let rows: Vec<usize> = (0..h).collect();
let px = |x: usize, y: usize| src.get((y * w + x) * 4..(y * w + x) * 4 + 4);
let row = |y: usize| src.get(y * w * 4..(y + 1) * w * 4).unwrap_or_default();
let done = parallel_map(&rows, |&y| {
let cur = row(y);
let (above, below) = (y.checked_sub(1).map(row), (y + 1 < h).then(|| row(y + 1)));
let mut out = Vec::with_capacity(w * 4);
for x in 0..w {
let Some(p) = px(x, y) else { continue };
for (x, p) in cur.as_chunks::<4>().0.iter().enumerate() {
if p[3] < 128 {
out.extend_from_slice(p);
continue;
}
let near = if along_rows {
[(x > 0).then(|| (x - 1, y)), (x + 1 < w).then(|| (x + 1, y))]
[x.checked_sub(1).and_then(|x| at(cur, x)), at(cur, x + 1)]
} else {
[(y > 0).then(|| (x, y - 1)), (y + 1 < h).then(|| (x, y + 1))]
[above.and_then(|r| at(r, x)), below.and_then(|r| at(r, x))]
};
let (mut sum, mut weight) = ([f64::from(p[0]), f64::from(p[1]), f64::from(p[2])], 1.0);
for q in near.into_iter().flatten().filter_map(|(x, y)| px(x, y)).filter(|q| q[3] >= 128) {
let d2: f64 = (0..3).map(|k| (f64::from(q[k]) - f64::from(p[k])).powi(2)).sum();
let wt = 1.0 / (1.0 + d2 / (ALIKE * ALIKE)).powi(2);
for q in near.into_iter().flatten().filter(|q| q[3] >= 128) {
let d = |k: usize| i32::from(q[k]) - i32::from(p[k]);
let d2 = (d(0) * d(0) + d(1) * d(1) + d(2) * d(2)) as usize;
let wt = weights.get(d2).copied().unwrap_or(0.0);
for k in 0..3 {
sum[k] += wt * f64::from(q[k]);
}
weight += wt;
}
out.extend(sum.map(|v| (v / weight).round() as u8));
out.extend(sum.map(|v| level(v / weight)));
out.push(p[3]);
}
out
@@ -52,8 +73,9 @@ pub(crate) fn smoothed(img: &Raster) -> Raster {
let (w, h) = (img.width as usize, img.height as usize);
let mut rgba = img.rgba.clone();
if rgba.len() == w * h * 4 {
let weights = weight_table();
for _ in 0..3 {
rgba = pass(&pass(&rgba, w, h, true), w, h, false);
rgba = pass(&pass(&rgba, w, h, true, &weights), w, h, false, &weights);
}
}
Raster { width: img.width, height: img.height, rgba }
@@ -85,6 +107,123 @@ mod tests {
assert!(out.pixel(19, 10)[0] < 70 && out.pixel(20, 10)[0] > 150);
}
/// The filter as it was before the weight table: the reference the fast pass must match byte for byte.
fn reference(src: &[u8], w: usize, h: usize, along_rows: bool) -> Vec<u8> {
let px = |x: usize, y: usize| src.get((y * w + x) * 4..(y * w + x) * 4 + 4);
let mut out = Vec::with_capacity(w * h * 4);
for y in 0..h {
for x in 0..w {
let Some(p) = px(x, y) else { continue };
if p[3] < 128 {
out.extend_from_slice(p);
continue;
}
let near = if along_rows {
[(x > 0).then(|| (x - 1, y)), (x + 1 < w).then(|| (x + 1, y))]
} else {
[(y > 0).then(|| (x, y - 1)), (y + 1 < h).then(|| (x, y + 1))]
};
let (mut sum, mut weight) = ([f64::from(p[0]), f64::from(p[1]), f64::from(p[2])], 1.0);
for q in near.into_iter().flatten().filter_map(|(x, y)| px(x, y)).filter(|q| q[3] >= 128) {
let d2: f64 = (0..3).map(|k| (f64::from(q[k]) - f64::from(p[k])).powi(2)).sum();
let wt = 1.0 / (1.0 + d2 / (ALIKE * ALIKE)).powi(2);
for k in 0..3 {
sum[k] += wt * f64::from(q[k]);
}
weight += wt;
}
out.extend(sum.map(|v| (v / weight).round() as u8));
out.push(p[3]);
}
}
out
}
fn reference_smoothed(img: &Raster) -> Vec<u8> {
let (w, h) = (img.width as usize, img.height as usize);
let mut rgba = img.rgba.clone();
for _ in 0..3 {
rgba = reference(&reference(&rgba, w, h, true), w, h, false);
}
rgba
}
fn hash(x: u32, y: u32, salt: u32) -> u32 {
let mut n = x.wrapping_mul(0x9E37_79B1) ^ y.wrapping_mul(0x85EB_CA77) ^ salt.wrapping_mul(0xC2B2_AE3D);
n ^= n >> 15;
n = n.wrapping_mul(0x2C1B_3C6D);
n ^= n >> 13;
n.wrapping_mul(0x297A_2D39) ^ (n >> 16)
}
#[test]
fn same_bytes_as_the_unoptimised_filter() {
let inputs: Vec<(&str, Raster)> = vec![
("random colours", Raster::from_fn(61, 47, |x, y| [hash(x, y, 1) as u8, (hash(x, y, 2) >> 3) as u8, (hash(x, y, 3) >> 5) as u8, 255])),
(
"photo-like",
Raster::from_fn(90, 70, |x, y| {
let base = ((x as f64 / 9.0).sin() * 60.0 + (y as f64 / 13.0).cos() * 60.0 + 128.0) as i32;
let v = (base + (hash(x, y, 4) % 9) as i32 - 4).clamp(0, 255) as u8;
[v, (i32::from(v) / 2 + 60) as u8, 255 - v, 255]
}),
),
("gradient", Raster::from_fn(80, 33, |x, y| [(x * 3) as u8, (y * 7) as u8, (x + y) as u8, 255])),
("flat", Raster::from_fn(20, 20, |_, _| [40, 90, 200, 255])),
("extremes", Raster::from_fn(32, 32, |x, y| if hash(x, y, 5).is_multiple_of(2) { [0, 0, 0, 255] } else { [255, 255, 255, 255] })),
(
"holes and half alpha",
Raster::from_fn(50, 40, |x, y| {
[hash(x, y, 6) as u8, (hash(x, y, 7) >> 8) as u8, 77, [0, 127, 128, 255, 255][(hash(x, y, 8) % 5) as usize]]
}),
),
("one column", Raster::from_fn(1, 30, |_, y| [(y * 8) as u8, 5, 9, 255])),
("one row", Raster::from_fn(30, 1, |x, _| [(x * 8) as u8, 5, 9, 255])),
("one pixel", Raster::from_fn(1, 1, |_, _| [1, 2, 3, 255])),
("two by two", Raster::from_fn(2, 2, |x, y| [(x * 100) as u8, (y * 100) as u8, 3, 255])),
("wide", Raster::from_fn(257, 3, |x, y| [x as u8, (x / 2) as u8, y as u8, 255])),
];
for (name, img) in &inputs {
assert_eq!(smoothed(img).rgba, reference_smoothed(img), "{name}");
}
}
#[test]
fn same_bytes_for_every_pair_of_grey_levels() {
// Every pixel next to every possible neighbour, one table for all of them (the picture
// tests above run the three rounds).
let weights = weight_table();
for p in 0..=255u8 {
for q in 0..=255u8 {
// Grey, and a mixed pair, along a row (2x1) and along a column (1x2).
for src in [[p, p, p, 255, q, q, q, 255], [p, q, p ^ q, 255, q, p, q ^ 0x5a, 255]] {
assert_eq!(pass(&src, 2, 1, true, &weights), reference(&src, 2, 1, true), "{p} {q}");
assert_eq!(pass(&src, 1, 2, false, &weights), reference(&src, 1, 2, false), "{p} {q}");
}
}
}
}
#[test]
fn level_is_round_for_every_value_that_can_occur() {
for v in
[0.0, 0.499_999_999_999_999_94, 0.5, 0.500_000_000_000_000_1, 1.499_999_999_999_999_8, 1.5, 127.5, 254.5, 254.999_999_999_999_97, 255.0]
{
assert_eq!(level(v), v.round() as u8, "{v}");
}
// Values a hair either side of every half, where a wrong rounding would show.
for k in 0..255 {
let half = f64::from(k) + 0.5;
for v in [half, f64::from_bits(half.to_bits() - 1), f64::from_bits(half.to_bits() + 1)] {
assert_eq!(level(v), v.round() as u8, "{v}");
}
}
for i in 0..=255 * 4096u32 {
let v = f64::from(i) / 4096.0;
assert_eq!(level(v), v.round() as u8, "{v}");
}
}
#[test]
fn transparent_pixels_and_odd_sizes_pass_through() {
let img = Raster::from_fn(3, 1, |x, _| [10 * x as u8, 0, 0, if x == 1 { 0 } else { 255 }]);
+26
View File
@@ -609,6 +609,32 @@ fn a_trace_past_its_anchor_budget_is_refused() {
assert_eq!(trace_within(&img, &p, anchors).unwrap(), full);
}
/// Components of a layer are fitted in parallel, a chunk at a time, and added in the order they were found (top to
/// bottom, left to right), also across the chunks. The anchor budget still refuses a trace with many components.
#[test]
fn many_components_come_out_in_scan_order_and_still_meet_the_budget() {
// 20 x 20 black dots, more than one chunk of components.
let img = Raster::from_fn(120, 120, |x, y| if x % 6 < 3 && y % 6 < 3 { BLACK } else { WHITE });
let p = TraceParams { noise: 1, ..bw() };
let full = trace(&img, &p);
assert_eq!(full.paths.len(), 400);
let tops: Vec<(i64, i64)> = full
.paths
.iter()
.map(|t| {
let b = t.path.bounds().unwrap();
(b.y0.round() as i64, b.x0.round() as i64)
})
.collect();
assert!(tops.windows(2).all(|w| w[0] < w[1]), "not in scan order: {tops:?}");
assert_eq!(trace(&img, &p), full, "tracing twice differs");
let anchors = full.anchor_count();
assert!(matches!(trace_within(&img, &p, anchors / 2), Err(TraceError::TooComplex { max }) if max == anchors / 2));
// The last component alone is over the budget: a refusal in a later chunk.
assert!(matches!(trace_within(&img, &p, anchors - 1), Err(TraceError::TooComplex { .. })));
assert_eq!(trace_within(&img, &p, anchors).unwrap(), full);
}
/// #3098: a watched trace says how far it has got, layer by layer, and stops when told to.
#[test]
fn a_watched_trace_counts_its_layers_and_stops_when_told() {
+3 -3
View File
@@ -444,10 +444,10 @@ impl VectorcraftApp {
if !canvas::tiled_area(self, ui) {
if floats {
let rect = ui.available_rect_before_wrap();
if let Some(i) = crate::doc_windows::tab_document(self)
&& canvas::pane(self, ui, i, rect)
if let Some(w) = crate::doc_windows::tab_window(self)
&& canvas::pane(self, ui, w, rect)
{
chrome::show_document(self, i);
crate::doc_windows::show_window(self, w);
}
} else {
canvas::show(self, ui);
+6
View File
@@ -188,6 +188,12 @@ impl VectorcraftApp {
r.insert(0, font.to_string());
r.truncate(MAX_RECENT_FONTS);
}
if id == "text.replaceFont"
&& v.get("warning").is_none()
&& self.ui.status.starts_with("some text is hidden or locked, so its font wasn't replaced")
{
self.ui.status.clear();
}
// A command's warning (Rasterize's when an image couldn't be decoded) shows in the
// status bar, as a tool preview's does.
if let Some(w) = v.get("warning").and_then(Value::as_str) {
+3 -1
View File
@@ -2,7 +2,8 @@ use super::{Value, VectorcraftApp, View, ViewInfo, panels};
impl VectorcraftApp {
/// Keep `views` aligned with the session's documents (a new one starts at its saved view, and
/// opens in a floating window while Open Documents As Tabs is cleared).
/// opens in a floating window while Open Documents As Tabs is cleared). The views Window › New
/// Window opened go with their documents.
pub fn sync_views(&mut self) {
let docs = self.session.documents();
self.views.truncate(docs.len());
@@ -10,6 +11,7 @@ impl VectorcraftApp {
for (view, doc) in self.views.iter_mut().zip(docs) {
view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1));
}
crate::doc_windows::retain_views(self);
crate::doc_windows::opened(self);
// Undo can remove the Artboard tool's active or additionally selected boards. Repair only
// invalid indices: valid multiselection, drag state and tool options must survive history.
+14 -6
View File
@@ -253,7 +253,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let doc = st.doc.clone();
let mask_view = st.shown_mask();
paint_paper(app, st, ui, &painter, &xf, rect, &t);
paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view()));
// The grid behind the art (Guides & Grid › Grids In Back), else over it below.
let grid_look = (app.ui.view.grid && !presenting).then(|| LineLook::grid(&app.session.prefs));
let grids_in_back = app.session.prefs.grids_in_back;
@@ -574,7 +574,7 @@ fn frame_options(
mask_view: Option<vectorcraft_doc::NodeId>,
smooth_images: bool,
) -> vectorcraft_render::RenderOptions {
let opts = vectorcraft_render::RenderOptions { outline: app.outline_view(), background: None, artboards: false, ..Default::default() };
let opts = vectorcraft_render::RenderOptions { outline: key.outline, background: None, artboards: false, ..Default::default() };
vectorcraft_render::RenderOptions {
proof: vectorcraft_render::proof::active_proof(),
overprint_preview: vectorcraft_render::proof::overprint_preview_on(),
@@ -678,8 +678,16 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
}
/// The pasteboard, the artboards' shadows and paper, and the outline mode's white artboards, of
/// document `st`.
fn paint_paper(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, ui: &Ui, painter: &egui::Painter, xf: &Xf, rect: egui::Rect, t: &Tokens) {
/// document `st`, in Outline when `outline`.
fn paint_paper(
app: &VectorcraftApp,
st: &vectorcraft_engine::DocState,
ui: &Ui,
painter: &egui::Painter,
xf: &Xf,
rect: egui::Rect,
(t, outline): (&Tokens, bool),
) {
let doc = &st.doc;
// Pasteboard, artboard shadows and paper (Document Setup: the transparency grid's look, the
// simulated paper colour; a white Background Contents hides the grid).
@@ -691,7 +699,7 @@ fn paint_paper(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, ui: &Ui,
// View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038).
let setup = &doc.setup;
painter.rect_filled(rect, 0.0, if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE });
} else if !app.outline_view() {
} else if !outline {
let setup = &doc.setup;
let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent).then(|| checker_texture(ui.ctx(), setup));
let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE };
@@ -709,7 +717,7 @@ fn paint_paper(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, ui: &Ui,
}
}
}
} else if app.outline_view() {
} else {
for ab in &doc.artboards {
painter.add(Shape::convex_polygon(xf.quad(ab.rect), Color32::WHITE, Stroke::NONE));
}
+113 -105
View File
@@ -1,7 +1,8 @@
//! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document
//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its
//! document from a render of its own, with its artboards, guides and selected objects, and a press
//! in it makes its document the current one.
//! in it makes its document the current one. Each view Window › New Window opened has a pane of
//! its own ([`crate::doc_windows`]).
use std::collections::HashMap;
use std::sync::Arc;
@@ -13,28 +14,32 @@ use super::{
Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, cache_key,
frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, pos2, rulers, shows_artboards, textured_quad, vec2, view_rects,
};
use crate::doc_windows::Win;
use crate::thumb_worker::ThumbWorker;
/// A pane's render: what it shows, the document, its size in pixels and view, and its options.
type PaneFrame = (CacheKey, Arc<vectorcraft_doc::Document>, ((u32, u32), Affine), vectorcraft_render::RenderOptions);
/// The renders that the panes of the documents other than the current one draw.
/// Whose render a pane draws: its document's uid and its view's number.
type Slot = (u64, u32);
/// The renders that the panes of the windows other than the current one draw.
#[derive(Default)]
pub struct Panes {
/// Renders off the UI thread (None: on it, as on wasm).
worker: Option<ThumbWorker<usize, CacheKey>>,
worker: Option<ThumbWorker<Slot, (Slot, CacheKey)>>,
worker_started: bool,
/// Renders on the UI thread when there is no worker.
renderer: Option<vectorcraft_render::Renderer>,
/// By document uid: the render shown and what it shows.
shown: HashMap<usize, (CacheKey, egui::TextureHandle)>,
/// By document uid: the render the worker is making.
pending: HashMap<usize, CacheKey>,
/// The panes the last frame drew, as (document index, pane rect).
pub(crate) last: Vec<(usize, egui::Rect)>,
/// By document uid: the size of the view's area its document was last fitted to in a pane,
/// and the zoom and center the fit gave.
fits: HashMap<usize, (egui::Vec2, f64, Point)>,
/// By slot: the render shown and what it shows.
pub(crate) shown: HashMap<Slot, (CacheKey, egui::TextureHandle)>,
/// By slot: the render the worker is making.
pending: HashMap<Slot, CacheKey>,
/// The panes the last frame drew, as (window, pane rect).
pub(crate) last: Vec<(Win, egui::Rect)>,
/// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and
/// center the fit gave.
fits: HashMap<Slot, (egui::Vec2, f64, Point)>,
}
impl Panes {
@@ -46,27 +51,27 @@ impl Panes {
self.fits.clear();
}
/// Upload `img`, the render `key` describes.
fn upload(&mut self, ctx: &egui::Context, key: CacheKey, img: &vectorcraft_render::Rendered) {
/// Upload `img`, the render `key` describes, for `slot`.
fn upload(&mut self, ctx: &egui::Context, slot: Slot, key: CacheKey, img: &vectorcraft_render::Rendered) {
let color = super::color_image(img);
// Pixel Preview's document pixels show hard-edged, as on the canvas.
let options = if key.pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
match self.shown.get_mut(&key.doc) {
match self.shown.get_mut(&slot) {
Some((k, tex)) => {
tex.set(color, options);
*k = key;
}
None => {
let tex = ctx.load_texture(format!("arrange-pane-{}", key.doc), color, options);
self.shown.insert(key.doc, (key, tex));
let tex = ctx.load_texture(format!("arrange-pane-{}-{}", slot.0, slot.1), color, options);
self.shown.insert(slot, (key, tex));
}
}
}
/// Bring the render of the document `key` describes up to `key` (`size` pixels through `view`),
/// on the worker when there is one, then draw the latest render of that document through `xf`,
/// turned and scaled into the view it was rendered for.
fn draw(&mut self, ctx: &egui::Context, painter: &egui::Painter, xf: &Xf, frame: PaneFrame) {
/// Bring `slot`'s render up to `key` (`size` pixels through `view`), on the worker when there
/// is one, then draw the slot's latest render through `xf`, turned and scaled into the view it
/// was rendered for.
fn draw(&mut self, ctx: &egui::Context, painter: &egui::Painter, xf: &Xf, slot: Slot, frame: PaneFrame) {
let (key, doc, ((w, h), view), opts) = frame;
if !self.worker_started {
self.worker_started = true;
@@ -75,11 +80,12 @@ impl Panes {
match self.worker.as_ref().map(ThumbWorker::poll) {
Some(Some(done)) => {
for d in done {
if self.pending.get(&d.key.doc) == Some(&d.key) {
self.pending.remove(&d.key.doc);
let (s, k) = d.key;
if self.pending.get(&s) == Some(&k) {
self.pending.remove(&s);
}
if let Some(img) = d.img {
self.upload(ctx, d.key, &img);
self.upload(ctx, s, k, &img);
}
}
}
@@ -90,25 +96,24 @@ impl Panes {
}
None => {}
}
let uid = key.doc;
let current = self.shown.get(&uid).is_some_and(|(k, _)| *k == key) || self.pending.get(&uid) == Some(&key);
let current = self.shown.get(&slot).is_some_and(|(k, _)| *k == key) || self.pending.get(&slot) == Some(&key);
if !current {
let mut queued = false;
if let Some(worker) = &self.worker {
let (job_doc, job_opts) = (doc.clone(), opts.clone());
queued = worker.submit(uid, key.clone(), Box::new(move |r| Some(r.render(&job_doc, w, h, view, &job_opts))));
queued = worker.submit(slot, (slot, key.clone()), Box::new(move |r| Some(r.render(&job_doc, w, h, view, &job_opts))));
if queued {
self.pending.insert(uid, key.clone());
self.pending.insert(slot, key.clone());
} else {
self.worker = None;
}
}
if !queued {
let img = self.renderer.get_or_insert_with(vectorcraft_render::Renderer::new).render(&doc, w, h, view, &opts);
self.upload(ctx, key, &img);
self.upload(ctx, slot, key, &img);
}
}
if let Some((k, tex)) = self.shown.get(&uid) {
if let Some((k, tex)) = self.shown.get(&slot) {
// Document pixels: placed over the document rect they cover.
if let Some([x0, y0, x1, y1]) = k.pixel {
textured_quad(painter, tex.id(), &xf.quad(Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64)), (1.0, 1.0));
@@ -140,21 +145,19 @@ pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec<egui::Rect> {
(0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect()
}
/// `window.arrange.tile`: every open document in a pane of its own, each fitted to its pane. With
/// fewer than two documents open (when the menu item is grayed out) it leaves the view and `tiled` as
/// they are. The documents in floating windows come back under the tabs for it.
/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own,
/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it
/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it.
pub(crate) fn tile(app: &mut VectorcraftApp) -> Result<serde_json::Value, String> {
let n = app.session.documents().len();
app.sync_views();
let n = crate::doc_windows::windows(app).len();
if n < 2 {
return Ok(json!({"tiled": app.ui.tiled, "panes": n}));
}
app.sync_views();
crate::doc_windows::dock_all(app);
app.ui.tiled = true;
app.ui.home = None;
for v in &mut app.views {
v.fitted = false;
}
crate::doc_windows::unfit_all(app);
Ok(json!({"tiled": app.ui.tiled, "panes": n}))
}
@@ -167,14 +170,14 @@ pub(crate) fn consolidate(app: &mut VectorcraftApp) -> Result<serde_json::Value,
Ok(json!({"tiled": false, "floating": []}))
}
/// Draw the document area as panes while Tile is on and more than one document is under the tabs,
/// Draw the document area as panes while Tile is on and more than one window is under the tabs,
/// outside the Home screen and Presentation Mode. False when it did not: the caller draws the
/// canvas. The documents in floating windows have no pane.
/// canvas. The floating windows have no pane.
pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
if app.session.documents().is_empty() {
app.ui.tiled = false;
}
let docked = crate::doc_windows::docked(app);
let docked = crate::doc_windows::docked_windows(app);
let n = docked.len();
let tiling = app.ui.tiled && n > 1 && app.ui.screen_mode < 3 && !crate::menus::home_showing(app);
if !tiling {
@@ -185,77 +188,78 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
app.canvas.panes.last.clear();
return false;
}
// The current document's pane is the canvas, unless it is in a floating window.
let active = app.session.active_index().filter(|a| docked.contains(a));
// The current window's pane is the canvas, unless it is a floating one.
let active = crate::doc_windows::current(app).filter(|a| docked.contains(a));
app.sync_views();
let live: Vec<usize> = app.session.documents().iter().map(|d| d.uid as usize).collect();
app.canvas.panes.shown.retain(|uid, _| live.contains(uid));
app.canvas.panes.pending.retain(|uid, _| live.contains(uid));
app.canvas.panes.fits.retain(|uid, _| live.contains(uid));
// A document opened, closed, floated or docked changes the grid, and so does coming back to the
// panes from one document: each document fits its new pane.
if app.canvas.panes.last.iter().map(|(i, _)| *i).ne(docked.iter().copied()) {
for i in &docked {
if let Some(v) = app.views.get_mut(*i) {
let live: Vec<Slot> = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect();
app.canvas.panes.shown.retain(|s, _| live.contains(s));
app.canvas.panes.pending.retain(|s, _| live.contains(s));
app.canvas.panes.fits.retain(|s, _| live.contains(s));
// A window opened, closed, floated or docked changes the grid, and so does coming back to the
// panes from one window: each window fits its new pane.
if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) {
for w in &docked {
if let Some(v) = crate::doc_windows::view_mut(app, *w) {
v.fitted = false;
}
}
}
let t = Tokens::get(ui.ctx());
let ppp = ui.ctx().pixels_per_point();
let cells: Vec<(usize, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect();
let mut areas: Vec<Option<egui::Rect>> = vec![None; app.session.documents().len()];
for (i, cell) in &cells {
if let Some(a) = areas.get_mut(*i) {
*a = Some(view_rects(app, *cell, ppp).1);
}
}
let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect();
let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect();
let unfitted = refit_resized(app, &areas);
let mut activate = None;
// The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar)
// stays over them.
for (i, cell) in cells.iter().copied().filter(|(i, _)| Some(*i) != active) {
if pane(app, ui, i, cell) {
activate = Some(i);
for (w, cell) in cells.iter().copied().filter(|(w, _)| Some(*w) != active) {
if pane(app, ui, w, cell) {
activate = Some(w);
}
ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
}
if let Some((_, cell)) = cells.iter().copied().find(|(i, _)| Some(*i) == active) {
if let Some((_, cell)) = cells.iter().copied().find(|(w, _)| Some(*w) == active) {
let mut canvas = ui.new_child(egui::UiBuilder::new().max_rect(cell));
super::show(app, &mut canvas);
ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
}
// Note the fits this frame made, for `refit_resized`.
for ((i, area), was_unfitted) in areas.iter().enumerate().zip(unfitted) {
if let (Some(area), true, Some(v), Some(d)) = (area, was_unfitted, app.views.get(i).filter(|v| v.fitted), app.session.documents().get(i)) {
app.canvas.panes.fits.insert(d.uid as usize, (area.size(), v.zoom, v.center));
for ((w, area), was_unfitted) in areas.iter().zip(unfitted) {
if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) {
app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center));
}
}
app.canvas.panes.last = cells;
if let Some(i) = activate {
crate::chrome::show_document(app, i);
if let Some(w) = activate {
crate::doc_windows::show_window(app, w);
}
true
}
/// Unfit each document whose view is still where a pane fit left it when its view's area (in
/// `areas`, by document index; None for a document without a pane) has changed size, as when the
/// window or a panel is resized: it fits its pane again. A view zoomed or scrolled since keeps its
/// place. → which views are unfitted now.
fn refit_resized(app: &mut VectorcraftApp, areas: &[Option<egui::Rect>]) -> Vec<bool> {
let fits = &app.canvas.panes.fits;
let docs = app.session.documents();
for ((v, d), area) in app.views.iter_mut().zip(docs).zip(areas) {
if let Some(area) = area
&& let Some((size, zoom, center)) = fits.get(&(d.uid as usize))
&& *size != area.size()
&& *zoom == v.zoom
&& *center == v.center
{
v.fitted = false;
}
}
app.views.iter().map(|v| !v.fitted).collect()
/// Window `w`'s [`Slot`].
fn slot(app: &VectorcraftApp, (i, n): Win) -> Option<Slot> {
app.session.documents().get(i).map(|d| (d.uid, n))
}
/// Unfit each window whose view is still where a pane fit left it when its view's area (`areas`,
/// by window) has changed size, as when the window or a panel is resized: it fits its pane again.
/// A view zoomed or scrolled since keeps its place. → which of `areas`' views are unfitted now.
fn refit_resized(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)]) -> Vec<bool> {
areas
.iter()
.map(|(w, area)| {
let fit = slot(app, *w).and_then(|s| app.canvas.panes.fits.get(&s).copied());
let Some(v) = crate::doc_windows::view_mut(app, *w) else { return false };
if let Some((size, zoom, center)) = fit
&& size != area.size()
&& zoom == v.zoom
&& center == v.center
{
v.fitted = false;
}
!v.fitted
})
.collect()
}
/// Fit `v` to show its artboard (the first if it has gone) in `rect`, as Fit Artboard in Window
@@ -268,41 +272,45 @@ fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, rect: egui::Rect) {
}
}
/// The pane of document `i`, not the current one, in `cell`: its paper, art, grid, artboards,
/// guides and selected objects, and its rulers and the room of the canvas's scroll bars, so the
/// document stays where it is when the pane becomes the canvas. True when a press in the pane asks
/// for its document to become the current one. A floating document's window draws its document
/// with this too ([`crate::doc_windows`]).
pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, i: usize, cell: egui::Rect) -> bool {
/// The pane of window `w` (document `i`'s view `n`), not the current one, in `cell`: its paper,
/// art, grid, artboards, guides and selected objects, and its rulers and the room of the canvas's
/// scroll bars, so the document stays where it is when the pane becomes the canvas. True when a
/// press in the pane asks for its window to become the current one. A floating window draws its
/// view with this too ([`crate::doc_windows`]).
pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> bool {
let t = Tokens::get(ui.ctx());
let ppp = ui.ctx().pixels_per_point();
let (full, rect) = view_rects(app, cell, ppp);
let Some(st) = app.session.documents().get(i) else { return false };
if let Some(v) = app.views.get_mut(i).filter(|v| !v.fitted) {
fit_pane(v, &st.doc, rect);
let Some(st) = app.session.documents().get(w.0) else { return false };
let doc = st.doc.clone();
if let Some(v) = crate::doc_windows::view_mut(app, w).filter(|v| !v.fitted) {
fit_pane(v, &doc, rect);
}
let v = app.views.get(i).copied().unwrap_or_default();
let v = crate::doc_windows::view(app, w).copied().unwrap_or_default();
let Some(st) = app.session.documents().get(w.0) else { return false };
let slot = (st.uid, w.1);
let xf = Xf::new(rect, &v);
let painter = ui.painter_at(rect);
paint_paper(app, st, ui, &painter, &xf, rect, &t);
paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline));
let grid_look = app.ui.view.grid.then(|| LineLook::grid(&app.session.prefs));
let grids_in_back = app.session.prefs.grids_in_back;
if let Some(look) = grid_look.filter(|_| grids_in_back) {
grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look);
}
let size = |l: f32| ((l * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX));
let (w, h) = (size(rect.width()), size(rect.height()));
let (pw, ph) = (size(rect.width()), size(rect.height()));
// View › Pixel Preview, as the canvas draws it.
let pixel = (app.ui.view.pixel_preview && v.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten();
let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps;
let mut key = cache_key(app, ui, st, &t, &v, (w, h, ppp), (pixel, smooth_images));
// The current document's drag and Image Trace hold are not this document's.
(key.dragging, key.trace_source) = (false, None);
let mut key = cache_key(app, ui, st, &t, &v, (pw, ph, ppp), (pixel, smooth_images));
// The current document's drag and Image Trace hold are not this document's, and this view has
// its own Outline or Preview.
(key.dragging, key.trace_source, key.outline) = (false, None, v.outline);
let opts = frame_options(app, &key, st.shown_mask(), smooth_images);
let (fw, fh, view) = frame_view(pixel, (w, h), &v, ppp);
let (fw, fh, view) = frame_view(pixel, (pw, ph), &v, ppp);
let doc = st.doc.clone();
app.canvas.panes.draw(ui.ctx(), &painter, &xf, (key, doc, ((fw, fh), view), opts));
let Some(st) = app.session.documents().get(i) else { return false };
app.canvas.panes.draw(ui.ctx(), &painter, &xf, slot, (key, doc, ((fw, fh), view), opts));
let Some(st) = app.session.documents().get(w.0) else { return false };
if let Some(look) = grid_look.filter(|_| !grids_in_back) {
grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look);
}
@@ -327,7 +335,7 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, i: usize, cell: egui::Rect
ui.painter().rect_filled(bar, 0.0, t.ruler);
}
}
let resp = ui.interact(cell, egui::Id::unique(("arrange-pane", st.uid)), Sense::click_and_drag());
let resp = ui.interact(cell, egui::Id::unique(("arrange-pane", st.uid, w.1)), Sense::click_and_drag());
resp.contains_pointer() && ui.input(|inp| inp.pointer.any_pressed())
}
+4 -4
View File
@@ -45,7 +45,7 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event {
/// The documents' indices in the panes the last frame drew, and the panes.
fn panes(app: &VectorcraftApp) -> (Vec<usize>, Vec<egui::Rect>) {
app.canvas.panes.last.iter().copied().unzip()
app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip()
}
#[test]
@@ -198,7 +198,7 @@ fn closing_a_document_while_tiled_tiles_the_others() {
app.run("window.arrange.tile", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
assert_eq!(panes(&app).0, [0, 1, 2]);
let first = app.session.documents()[0].uid as usize;
let first = (app.session.documents()[0].uid, 1);
assert!(app.canvas.panes.shown.contains_key(&first));
// The first document, not the current one, closes.
app.run("file.close", json!({"index": 0})).unwrap();
@@ -220,7 +220,7 @@ fn an_edit_shows_in_its_pane_once_another_document_is_current() {
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("window.arrange.tile", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
let uid = app.session.documents()[1].uid as usize;
let uid = (app.session.documents()[1].uid, 1);
let before = app.canvas.panes.shown.get(&uid).map(|(k, _)| k.revision);
assert_eq!(before, Some(app.session.documents()[1].revision), "the second document's pane shows it");
app.run("document.activate", json!({"index": 1})).unwrap();
@@ -294,7 +294,7 @@ fn other_panes_show_pixel_preview() {
app.ui.view.pixel_preview = true;
app.views[0].zoom = 4.0;
frame(&mut app, &ctx, vec![]);
let uid = app.session.documents()[0].uid as usize;
let uid = (app.session.documents()[0].uid, 1);
let key = app.canvas.panes.shown.get(&uid).map(|(k, _)| k.clone()).unwrap();
let [x0, y0, x1, y1] = key.pixel.expect("the pane renders document pixels");
assert!(x1 > x0 && y1 > y0);
+5 -4
View File
@@ -117,8 +117,8 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
items.push((tl!("Smooth"), "dc-anchor-smooth", TASK_BAR_TO_SMOOTH, none()));
}
// As in the reference app, open paths offer Join and Edit Path, compound paths and clipping
// masks their Release, images selected with vector art Make Clipping Mask, and type converts
// between point and area type (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html>).
// masks their Release, images selected with vector art Make Clipping Mask, type converts
// between point and area type, and type on a path offers its options (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html>).
if n > 1 {
items.push((tl!("Group"), "group", "object.group", none()));
if mixed {
@@ -144,11 +144,12 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
items.push((tl!("Release Compound Path"), "ungroup", "object.compoundPath.release", none()));
} else if let Some(kind) = text {
items.push((tl!("Create Outlines"), "type", "type.createOutlines", none()));
// Point type converts to area type and back; type on a path doesn't.
// Point type converts to area type and back. The overview above gives type on a path an item to add
// an effect and rearrange the text; here it opens Type on a Path Options.
match kind {
TextKind::Area { .. } => items.push((tl!("Convert To Point Type"), "type", "type.convertToPointType", none())),
TextKind::Point => items.push((tl!("Convert To Area Type"), "dc-type-area", "type.convertToAreaType", none())),
TextKind::OnPath { .. } => {}
TextKind::OnPath { .. } => items.push((tl!("Type on a Path Options"), "dc-type-path", "type.pathOptions", none())),
}
} else if is_image {
// Offset Path and Simplify don't apply to an image.
+70 -52
View File
@@ -1,28 +1,37 @@
use super::{Sense, Stroke, Tokens, Ui, VectorcraftApp, icons, json, theme, vec2, widgets, zoom_label};
/// A document tab's title: "Name* @ 66.67 % (RGB/Preview)", or while an opacity mask is edited
/// "Name* @ 66.67 % (<Opacity Mask>/Opacity Mask)".
/// [`view_tab_title`] for a document with one view.
#[cfg(test)]
pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool, display_print_size: bool) -> String {
view_tab_title(d, None, zoom, outline, display_print_size)
}
/// A document tab's title: "Name* @ 66.67 % (RGB/Preview)", or while an opacity mask is edited
/// "Name* @ 66.67 % (<Opacity Mask>/Opacity Mask)". For a view of a document with more than one
/// view, the view's `number` follows the name: "Name:2* @ 66.67 % (RGB/Preview)".
fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option<u32>, zoom: f64, outline: bool, display_print_size: bool) -> String {
let mode = if d.doc.mask_edit.is_some() {
format!("<{0}>/{0}", tl!("Opacity Mask"))
} else {
let color = if d.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { "CMYK" } else { "RGB" };
format!("{color}/{}", if outline { tl!("Outline") } else { tl!("Preview") })
};
format!("{}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom, display_print_size).replace('%', " %"))
let number = number.map(|n| format!(":{n}")).unwrap_or_default();
format!("{}{number}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom, display_print_size).replace('%', " %"))
}
/// The title of open document `i`'s tab, with its own view's zoom and Outline or Preview.
pub(super) fn doc_tab_title(app: &VectorcraftApp, i: usize, d: &vectorcraft_engine::DocState) -> String {
let view = app.views.get(i);
/// The title of window `w`, a view of document `d`: with the view's zoom and Outline or Preview,
/// and the view's number while the document has more than one view.
fn window_tab_title(app: &VectorcraftApp, w: crate::doc_windows::Win, d: &vectorcraft_engine::DocState) -> String {
let view = crate::doc_windows::view(app, w);
let zoom = view.map_or(1.0, |v| v.zoom);
tab_title(d, zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size)
view_tab_title(d, crate::doc_windows::label(app, w), zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size)
}
/// The title of document `i`'s floating window ([`crate::doc_windows`]): its tab's title.
pub(crate) fn document_window_title(app: &VectorcraftApp, i: usize) -> Option<String> {
let d = app.session.documents().get(i)?;
Some(doc_tab_title(app, i, d))
/// The title of window `w`'s tab and floating window ([`crate::doc_windows`]).
pub(crate) fn document_window_title(app: &VectorcraftApp, w: crate::doc_windows::Win) -> Option<String> {
let d = app.session.documents().get(w.0)?;
Some(window_tab_title(app, w, d))
}
/// The height of the tab strip and the size of a tab's title, in points: larger with User
@@ -31,16 +40,16 @@ fn tab_size(app: &VectorcraftApp) -> (f32, f32) {
if app.session.prefs.large_tabs { (44.0, 14.0) } else { (35.0, 12.5) }
}
/// The tab at the top of document `i`'s floating OS window ([`crate::doc_windows`]): a strip with
/// the document's tab, as the main window's strip draws it but without its ×. → the tab's
/// response, which senses clicks and drags.
pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, i: usize) -> egui::Response {
/// The tab at the top of window `w`'s floating OS window ([`crate::doc_windows`]): a strip with the
/// window's tab, as the main window's strip draws it but without its ×. → the tab's response,
/// which senses clicks and drags.
pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_windows::Win) -> egui::Response {
let t = Tokens::get(ui.ctx());
let (height, title_size) = tab_size(app);
let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
ui.painter().rect_filled(strip, 0.0, t.tab_strip);
ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border));
let title = document_window_title(app, i).unwrap_or_default();
let title = document_window_title(app, w).unwrap_or_default();
let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), t.text_strong);
let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0));
ui.painter().rect_filled(r, 0.0, t.panel);
@@ -88,10 +97,10 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option<usize>, room: f32)
/// Document tab strip: "Name* @ 66.67% (RGB/Preview)". User Interface › Large Tabs makes the tabs
/// taller, with larger titles. Tabs that don't fit are reached from a » button at the strip's
/// right end, which lists every open document, and the active tab is always in view (#746).
/// Documents in floating windows have no tab ([`crate::doc_windows`]); while the current document
/// is in one, the tab of the document the strip shows is the highlighted one. A tab dragged more
/// than [`crate::doc_windows::TEAR_OFF`] above or below the strip floats its document in a window
/// under the pointer.
/// Each view Window › New Window opened has a tab of its own. Windows floating have no tab
/// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the
/// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`]
/// above or below the strip floats its view in a window under the pointer.
pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
/// The width of the » button.
const MORE: f32 = 30.0;
@@ -102,16 +111,16 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.painter().rect_filled(strip, 0.0, t.tab_strip);
ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border));
// On the Home screen no tab is the current one.
let shown = crate::doc_windows::tab_document(app).filter(|_| app.ui.home.is_none());
// The documents under the tabs, by index; `active` is the position of the highlighted one.
let docked = crate::doc_windows::docked(app);
let active = docked.iter().position(|i| Some(*i) == shown);
let shown = crate::doc_windows::tab_window(app).filter(|_| app.ui.home.is_none());
// The windows under the tabs; `active` is the position of the highlighted one.
let docked = crate::doc_windows::docked_windows(app);
let active = docked.iter().position(|w| Some(*w) == shown);
let tabs: Vec<(String, std::sync::Arc<egui::Galley>)> = docked
.iter()
.filter_map(|i| Some((*i, app.session.documents().get(*i)?)))
.map(|(i, d)| {
let title = doc_tab_title(app, i, d);
let color = if Some(i) == shown { t.text_strong } else { t.text_dim };
.filter_map(|w| Some((*w, app.session.documents().get(w.0)?)))
.map(|(w, d)| {
let title = window_tab_title(app, w, d);
let color = if Some(w) == shown { t.text_strong } else { t.text_dim };
(title.clone(), ui.painter().layout_no_wrap(title, theme::semibold(title_size), color))
})
.collect();
@@ -128,10 +137,11 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
if x + w > strip.left() + room && Some(k) != active {
break;
}
let Some(&i) = docked.get(k) else { break };
let Some(&win) = docked.get(k) else { break };
let i = win.0;
let is_active = Some(k) == active;
let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0));
let resp = ui.interact(r, ui.scope_id().with(("tab", i)), Sense::click_and_drag());
let resp = ui.interact(r, ui.scope_id().with(("tab", i, win.1)), Sense::click_and_drag());
if is_active {
ui.painter().rect_filled(r, 0.0, t.panel);
} else if resp.hovered() {
@@ -142,26 +152,27 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
// (#673).
let (x_center, title_left) = if CLOSE_BEFORE_TITLE { (r.left() + 16.0, r.left() + 32.0) } else { (r.right() - 16.0, r.left() + 14.0) };
let xr = egui::Rect::from_center_size(egui::pos2(x_center, r.center().y), vec2(12.0, 12.0));
let xresp = ui.interact(xr.expand(3.0), ui.scope_id().with(("tabx", i)), Sense::click());
let xresp = ui.interact(xr.expand(3.0), ui.scope_id().with(("tabx", i, win.1)), Sense::click());
icons::paint(ui, "x", xr, if xresp.hovered() { t.text_strong } else { t.text });
ui.painter().galley(egui::pos2(title_left, r.center().y - galley.size().y / 2.0), galley.clone(), t.text);
hovering_art |= crate::document_drag::hover_tab(app, &resp, i, xr.expand(3.0));
hovering_art |= crate::document_drag::hover_tab(app, &resp, win, xr.expand(3.0));
if xresp.clicked() {
close = Some(i);
close = Some(win);
} else if resp.clicked() {
activate = Some(i);
activate = Some(win);
} else if let Some(at) = tear_off(ui, &resp, strip) {
float = Some((i, at));
float = Some((win, at));
}
x += w;
}
crate::document_drag::finish_tabs(ui.ctx(), hovering_art);
// The » button: every open document, floating ones included, the active one checked. The list
// The » button: every window, floating ones included, the current one checked. The list
// scrolls once it reaches the bottom of the window, so every document of a large session stays
// reachable (#4017).
if overflow {
let current = app.session.active_index().filter(|_| app.ui.home.is_none());
let titles: Vec<String> = (0..app.session.documents().len()).map(|i| document_window_title(app, i).unwrap_or_default()).collect();
let current = crate::doc_windows::current(app).filter(|_| app.ui.home.is_none());
let all = crate::doc_windows::windows(app);
let titles: Vec<(crate::doc_windows::Win, String)> = all.iter().map(|w| (*w, document_window_title(app, *w).unwrap_or_default())).collect();
let more = egui::Rect::from_min_max(egui::pos2(strip.right() - MORE, strip.top()), egui::pos2(strip.right(), strip.bottom() - 1.0));
let resp = ui.interact(more, ui.scope_id().with("tabs-more"), Sense::click());
ui.painter().rect_filled(more, 0.0, if resp.hovered() { t.hover.gamma_multiply(0.4) } else { t.tab_strip });
@@ -169,25 +180,25 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
let resp = resp.on_hover_text(tl!("Show all open documents"));
egui::Popup::menu(&resp).show(|ui| {
widgets::menu_scroll(ui, |ui| {
for (i, title) in titles.iter().enumerate() {
if widgets::menu_item_name(ui, title, true, Some(i) == current) {
activate = Some(i);
for (w, title) in &titles {
if widgets::menu_item_name(ui, title, true, Some(*w) == current) {
activate = Some(*w);
ui.close();
}
}
});
});
}
if let Some(i) = close {
if let Err(e) = crate::unsaved::close(app, i) {
if let Some(w) = close {
if let Err(e) = crate::doc_windows::close_window(app, w) {
app.status(e);
}
} else if let Some((i, at)) = float {
if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "at": [at.x, at.y]})) {
} else if let Some(((i, n), at)) = float {
if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "view": n, "at": [at.x, at.y]})) {
app.status(e);
}
} else if let Some(i) = activate {
show_document(app, i);
} else if let Some(w) = activate {
crate::doc_windows::show_window(app, w);
}
}
@@ -212,20 +223,27 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, i: usize) {
/// the current one in tab order (before it) the current one, as a click on its tab does. After the
/// last document comes the first, and before the first document comes the last. On the Home
/// screen, where no tab is the current one, the next document is the first and the previous
/// document is the last. Returns `{index}`.
/// document is the last. Each view Window › New Window opened is a step of its own. Returns
/// `{index}`, with the view's number as `view` while the document has more than one view.
pub fn step_document(app: &mut VectorcraftApp, forward: bool) -> Result<serde_json::Value, String> {
let n = app.session.documents().len();
let all = crate::doc_windows::windows(app);
let n = all.len();
if n == 0 {
return Err("no document open".into());
}
let i = match (app.session.active_index().filter(|_| app.ui.home.is_none()), forward) {
let current = crate::doc_windows::current(app).filter(|_| app.ui.home.is_none()).and_then(|c| all.iter().position(|w| *w == c));
let k = match (current, forward) {
(Some(a), true) => (a + 1) % n,
(Some(a), false) => (a + n - 1) % n,
(None, true) => 0,
(None, false) => n - 1,
};
show_document(app, i);
Ok(json!({ "index": i }))
let Some(&w) = all.get(k) else { return Err("no document open".into()) };
crate::doc_windows::show_window(app, w);
Ok(match crate::doc_windows::label(app, w) {
Some(view) => json!({ "index": w.0, "view": view }),
None => json!({ "index": w.0 }),
})
}
/// The isolation mode breadcrumb bar. It is drawn over the top of `area` (the canvas), after the
+1 -1
View File
@@ -873,7 +873,7 @@ fn only_the_outlined_documents_tab_reads_outline() {
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.run("view.outline", json!({})).unwrap();
let titles: Vec<String> = app.session.documents().iter().enumerate().map(|(i, d)| super::tabs::doc_tab_title(&app, i, d)).collect();
let titles: Vec<String> = (0..app.session.documents().len()).filter_map(|i| super::document_window_title(&app, (i, 1))).collect();
assert!(titles[0].ends_with("(RGB/Preview)"), "{titles:?}");
assert!(titles[1].ends_with("(RGB/Outline)"), "{titles:?}");
}
+14 -8
View File
@@ -192,17 +192,23 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
"view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()),
"canvasRect": app.canvas_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),
// Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew:
// each one's document index and rect. Canvas coordinates map to the current document's
// pane, inside its rulers and scroll bars (`canvasRect`).
// each one's document index, view number (Window › New Window) and rect. Canvas
// coordinates map to the current window's pane, inside its rulers and scroll bars
// (`canvasRect`).
"tiled": app.ui.tiled,
"panes": app.canvas.panes.last.iter().map(|(i, c)| json!({
"document": i,
"panes": app.canvas.panes.last.iter().map(|(w, c)| json!({
"document": w.0,
"view": w.1,
"rect": [c.left(), c.top(), c.width(), c.height()],
"active": app.session.active_index() == Some(*i),
"active": crate::doc_windows::current(app) == Some(*w),
})).collect::<Vec<_>>(),
// Window › Arrange › Float in Window: the documents in floating windows, by index. While
// the current one floats, `canvasRect` is in its window's coordinates.
"floating": (0..app.session.documents().len()).filter(|i| crate::doc_windows::is_floating(app, *i)).collect::<Vec<_>>(),
// Window › Arrange › Float in Window: the floating windows' documents, by index. While the
// current one floats, `canvasRect` is in its window's coordinates.
"floating": crate::doc_windows::floating_windows(app).iter().map(|w| w.0).collect::<Vec<_>>(),
// Window › New Window: every window, as [document index, view number], in tab order, and
// the current one.
"windows": crate::doc_windows::windows(app),
"currentWindow": crate::doc_windows::current(app),
"window": [r.width(), r.height()],
"documents": app.session.documents().iter().map(|d| json!({"title": d.title(), "dirty": d.is_dirty()})).collect::<Vec<_>>(),
"activeDocument": app.session.active_index(),
+181 -44
View File
@@ -264,10 +264,14 @@ pub fn contributors_ui(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
ui.label(RichText::new(counts).small().weak());
ui.separator();
if v.table && !list.is_empty() {
// The table scrolls its rows under its header itself, and sideways as a whole.
egui::ScrollArea::horizontal().auto_shrink([false, true]).show(ui, |ui| table(app, ui, &list, &mut v));
// The table scrolls its rows under its header itself; it only scrolls sideways once its
// columns are dragged wider than the dialog.
ui.allocate_ui(egui::vec2(ui.available_width(), SCROLL_HEIGHT), |ui| {
ui.set_max_height(SCROLL_HEIGHT);
egui::ScrollArea::horizontal().auto_shrink([false, false]).show(ui, |ui| table(app, ui, &list, &mut v));
});
} else {
egui::ScrollArea::both().max_height(SCROLL_HEIGHT).auto_shrink([false, true]).show(ui, |ui| {
egui::ScrollArea::vertical().max_height(SCROLL_HEIGHT).auto_shrink([false, true]).show(ui, |ui| {
if list.is_empty() {
ui.label(tl!("No contributor data was built into this copy."));
} else {
@@ -294,20 +298,120 @@ fn link(app: &mut VectorcraftApp, ui: &mut egui::Ui, c: &Contributor, names: Nam
r
}
/// How the contributor table's spare width is shared out: all of it to Name.
const CONTRIBUTOR_GROW: [f32; 10] = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
/// How the model table's spare width is shared out: to Company and Model, the text columns.
const MODEL_GROW: [f32; 6] = [1.0, 2.0, 0.0, 0.0, 0.0, 0.0];
/// The narrowest a column can be dragged.
const MIN_COLUMN: f32 = 28.0;
/// The width a column needs for its header and its widest cell.
fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator<Item = String>) -> f32 {
let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x;
let widest = cells.map(|c| measure(c.into())).fold(measure(header.into()), f32::max);
widest + 2.0 * ui.spacing().button_padding.x
}
/// Opening column widths: each column's natural width, with the spare room shared out by `grow`,
/// so the columns fill `room` exactly. When there is too little room, only the growing columns
/// give way, down to [`MIN_COLUMN`].
fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec<f32> {
let spare = room - natural.iter().sum::<f32>();
let weight = grow.iter().sum::<f32>();
let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| *w).sum();
natural
.iter()
.zip(grow)
.map(|(w, g)| {
if spare >= 0.0 && weight > 0.0 {
w + spare * g / weight
} else if *g > 0.0 && flexible > 0.0 {
(w + spare * w / flexible).max(MIN_COLUMN)
} else {
*w
}
})
.collect()
}
/// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls
/// sideways. Each column can be dragged wider or narrower at its edge. The last column fills
/// whatever width is left but never shrinks below its opening width, so widening a column grows
/// the table, as in a spreadsheet, instead of crushing the last one: only a table dragged wider
/// than the window scrolls sideways. Text too long for its column is clipped.
fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> {
// Every cell is followed by the item gap, and the vertical scrollbar keeps its margins.
let s = ui.spacing();
let gaps = s.item_spacing.x * natural.len() as f32;
let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin;
let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0));
let mut t =
egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY);
let last = widths.len().saturating_sub(1);
for (i, w) in widths.into_iter().enumerate() {
let c = if i == last {
egui_extras::Column::remainder().at_least(w.max(MIN_COLUMN))
} else {
egui_extras::Column::initial(w).at_least(MIN_COLUMN)
};
t = t.column(c.clip(true));
}
t
}
/// Add a cell's widget right-aligned (counts, dates) or left-aligned (names), vertically centred.
fn aligned<R>(ui: &mut egui::Ui, right: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
let layout = if right { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) };
ui.with_layout(layout, add).inner
}
fn row_height(ui: &egui::Ui) -> f32 {
ui.text_style_height(&egui::TextStyle::Body) + 6.0
}
/// One contributor's table cells after the name, in `SortKey::ALL` order.
fn cells(c: &Contributor) -> [String; 9] {
[
group(c.prs),
group(c.commits),
group(c.lines_added),
group(c.lines_deleted),
signed(c.lines_delta()),
group(c.binary_added),
group(c.binary_deleted),
day(c.first_commit).to_string(),
day(c.last_commit).to_string(),
]
}
/// A contributor-table header. The sorted column is highlighted; its direction shows on the
/// toolbar's sort-order button, so no arrow widens the column.
fn header_text(k: SortKey) -> RichText {
RichText::new(k.label().1).strong()
}
/// The contributors as a table whose header row, the sort buttons, stays above the rows as they
/// scroll (#4944).
fn table(app: &mut VectorcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {
let (row, names) = (ui.spacing().interact_size.y, v.names);
egui_extras::TableBuilder::new(ui)
.id_salt("credits_table")
.striped(true)
.columns(egui_extras::Column::auto(), SortKey::ALL.len())
.max_scroll_height(SCROLL_HEIGHT - row)
.header(row, |mut header| {
let h = row_height(ui);
let rows: Vec<[String; 9]> = list.iter().map(|c| cells(c)).collect();
let widths: Vec<f32> = SortKey::ALL
.iter()
.enumerate()
.map(|(i, &k)| match i.checked_sub(1) {
None => natural(ui, header_text(k), list.iter().map(|c| c.name(v.names))),
Some(col) => natural(ui, header_text(k), rows.iter().filter_map(|r| r.get(col).cloned())),
})
.collect();
fitted_table(ui, "credits_table", &widths, &CONTRIBUTOR_GROW)
.header(h + 4.0, |mut header| {
for k in SortKey::ALL {
header.col(|ui| {
let arrow = if v.key == k { if v.ascending { " ▲" } else { " ▼" } } else { "" };
if ui.button(RichText::new(format!("{}{arrow}", k.label().1)).strong()).on_hover_text(k.label().0).clicked() {
let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))).on_hover_text(k.label().0);
if r.clicked() {
if v.key == k {
v.ascending = !v.ascending;
} else {
@@ -319,25 +423,14 @@ fn table(app: &mut VectorcraftApp, ui: &mut egui::Ui, list: &[&Contributor], v:
}
})
.body(|mut body| {
for c in list {
body.row(row, |mut r| {
r.col(|ui| {
link(app, ui, c, names);
for (c, cells) in list.iter().zip(rows) {
body.row(h, |mut row| {
row.col(|ui| {
aligned(ui, false, |ui| link(app, ui, c, v.names));
});
let cells = [
group(c.prs),
group(c.commits),
group(c.lines_added),
group(c.lines_deleted),
signed(c.lines_delta()),
group(c.binary_added),
group(c.binary_deleted),
day(c.first_commit).to_string(),
day(c.last_commit).to_string(),
];
for text in cells {
r.col(|ui| {
ui.label(text);
row.col(|ui| {
aligned(ui, true, |ui| ui.label(text));
});
}
});
@@ -352,21 +445,50 @@ pub fn models_ui(ui: &mut egui::Ui) {
return;
}
let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1);
egui::ScrollArea::both().max_height(SCROLL_HEIGHT).auto_shrink([false, true]).show(ui, |ui| {
egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| {
for h in [tl!("Company"), tl!("Model"), tl!("Version"), tl!("Commits"), tl!("% of all commits"), tl!("Lines +/−")] {
ui.label(RichText::new(h).strong());
}
ui.end_row();
for m in MODELS {
ui.label(m.company);
ui.label(m.model);
ui.label(m.version);
ui.label(group(m.commits));
ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64));
ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)));
ui.end_row();
}
let h = row_height(ui);
let titles = [tl!("Company"), tl!("Model"), tl!("Version"), tl!("Commits"), tl!("% of all commits"), tl!("Lines +/−")];
// Company, Model and Version read as text; the counts line up on the right.
let right = [false, false, false, true, true, true];
let rows: Vec<[String; 6]> = MODELS
.iter()
.map(|m| {
[
m.company.to_string(),
m.model.to_string(),
m.version.to_string(),
group(m.commits),
format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64),
format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)),
]
})
.collect();
let widths: Vec<f32> = titles
.iter()
.enumerate()
.map(|(i, title)| natural(ui, RichText::new(*title).strong(), rows.iter().filter_map(|r| r.get(i).cloned())))
.collect();
ui.allocate_ui(egui::vec2(ui.available_width(), SCROLL_HEIGHT), |ui| {
ui.set_max_height(SCROLL_HEIGHT);
egui::ScrollArea::horizontal().id_salt("credits_models").auto_shrink([false, false]).show(ui, |ui| {
fitted_table(ui, "credits_models", &widths, &MODEL_GROW)
.header(h + 4.0, |mut header| {
for (title, r) in titles.into_iter().zip(right) {
header.col(|ui| {
aligned(ui, r, |ui| ui.label(RichText::new(title).strong()));
});
}
})
.body(|mut body| {
for cells in rows {
body.row(h, |mut row| {
for (text, r) in cells.into_iter().zip(right) {
row.col(|ui| {
aligned(ui, r, |ui| ui.label(text));
});
}
});
}
});
});
});
}
@@ -494,4 +616,19 @@ mod tests {
assert_eq!(after[0], Some(header), "the header stays where it was");
assert!(after[1].is_none_or(|p| p.y < row.y), "the rows scrolled: {:?} from {row:?}", after[1]);
}
#[test]
fn columns_fill_the_room_and_spare_width_goes_to_growing_columns() {
assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 300.0), [200.0, 40.0, 60.0]);
assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 2.0, 0.0], 230.0), [110.0, 60.0, 60.0]);
let w = fit_widths(&[123.0, 45.5, 67.25], &[1.0, 0.0, 2.0], 512.0);
assert!((w.iter().sum::<f32>() - 512.0).abs() < 0.01, "a fitted table neither scrolls nor leaves a gap: {w:?}");
}
#[test]
fn too_little_room_shrinks_only_growing_columns() {
assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 150.0), [50.0, 40.0, 60.0]);
assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]);
assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]);
}
}
+2 -2
View File
@@ -32,11 +32,11 @@ pub(super) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
ui.separator();
match tab {
1 => {
ui.set_width(660.0);
ui.set_width(820.0);
crate::credits::contributors_ui(app, ui);
}
2 => {
ui.set_width(660.0);
ui.set_width(820.0);
crate::credits::models_ui(ui);
}
_ => about_tab(app, ui),
+22 -8
View File
@@ -43,6 +43,7 @@ fn heading_label(d: &Dialog) -> String {
/// Fields: `__effect`, `__label`, `__item?` (as given to `effect.dialog`), `__target` and
/// `__index` (the applied effect's item and position). OK edits it; `discard: true` then OK adds
/// a new one.
/// `__editTarget` stores the targets used when editing the applied effect.
pub const EXISTS: &str = "effectExists";
pub(super) const EXISTS_SPEC: DialogSpec = DialogSpec {
@@ -67,7 +68,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
// The list the effect goes to: `item` as given, else the active item's (the object's without
// one). A new effect keeps `item` unresolved, so `effect.apply` targets each object as usual.
let target = p.get("item").cloned().unwrap_or_else(|| json!(app.session.appearance_item()));
let applied = target_effects(app, &target);
let (edit_target, applied) = target_effects(app, p);
let target = edit_target.get("item").cloned().unwrap_or(target);
let mut fields = Map::new();
fields.insert("__effect".into(), json!(id));
fields.insert("__label".into(), json!(info.label.trim_end_matches('…')));
@@ -85,12 +87,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
return Err(format!("effect {k} is `{}`, not `{id}`", e.id));
}
fields.insert("__item".into(), target);
fields.insert("__editTarget".into(), edit_target);
fields.insert("__index".into(), json!(k));
fields.extend(params_of(e));
}
None => {
if let Some(k) = applied.iter().rposition(|e| e.id == id) {
fields.insert("__target".into(), target);
fields.insert("__editTarget".into(), edit_target);
fields.insert("__index".into(), json!(k));
app.ui.dialog = Some(Dialog { kind: EXISTS.into(), fields });
return Ok(json!({ "pending": EXISTS }));
@@ -106,11 +110,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
Ok(Value::Null)
}
/// The function reads effects at `item` (an index or null) from the targeted node or first selected object.
fn target_effects(app: &VectorcraftApp, item: &Value) -> Vec<vectorcraft_doc::Effect> {
let Some(st) = app.session.active() else { return vec![] };
let node = st.selection.subjects().first().and_then(|id| st.doc.node(*id));
node.and_then(|n| n.appearance.effects_at(item.as_u64().map(|i| i as usize))).cloned().unwrap_or_default()
/// The function returns target parameters and effects at `item` (an index or null).
/// An omitted `item` uses the active row.
fn target_effects(app: &VectorcraftApp, p: &Value) -> (Value, Vec<vectorcraft_doc::Effect>) {
let mut params = json!({"aligned": p.get("aligned").and_then(Value::as_bool).unwrap_or(false)});
if let Some(item) = p.get("item") {
params["item"] = item.clone();
}
app.session.appearance_effect_target(&params).map(|(target, effects)| (target, effects.to_vec())).unwrap_or_else(|| (json!({}), vec![]))
}
/// An applied effect's values over its defaults.
@@ -128,6 +135,7 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String>
let target = fields.remove("__target").unwrap_or(Value::Null);
if d.bool("discard") {
fields.remove("__index");
fields.remove("__editTarget");
let id = d.str("__effect");
let defaults = vectorcraft_effects::default_params(&id);
fields.extend(defaults.and_then(|v| v.as_object().cloned()).unwrap_or_default());
@@ -136,7 +144,10 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String>
}
} else {
let k = fields.get("__index").and_then(Value::as_u64).unwrap_or(0) as usize;
fields.extend(target_effects(app, &target).get(k).map(params_of).unwrap_or_default());
let edit_target = fields.get("__editTarget").cloned().unwrap_or_else(|| json!({"item": target}));
let applied = app.session.appearance_effect_target(&edit_target).map(|(_, effects)| effects.to_vec()).unwrap_or_default();
let params = applied.get(k).map(params_of).unwrap_or_default();
fields.extend(params);
fields.insert("__item".into(), target);
}
fields.insert("preview".into(), json!(true));
@@ -804,7 +815,10 @@ fn command(d: &Dialog) -> (&'static str, Value) {
let params = form::params(d);
let item = d.fields.get("__item").cloned();
if let Some(index) = d.fields.get("__index") {
let mut p = json!({"index": index, "item": item.unwrap_or(Value::Null), "params": params});
let mut p = d.fields.get("__editTarget").filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({}));
p["index"] = index.clone();
p["item"] = item.unwrap_or(Value::Null);
p["params"] = params;
let id = d.str("__effect");
// The displayed style comes from the first target. Preserve other targets' Warp IDs
// unless the user deliberately chooses Style, including after a preview rollback.
+180 -158
View File
@@ -12,11 +12,20 @@
//!
//! With Preferences › User Interface › Open Documents As Tabs cleared, each document opened or
//! created afterwards opens in a floating window ([`opened`]).
//!
//! Each view of a document that Window › New Window opened ([`views`]) is a window of its own
//! here: it has its own tab, pane or floating window.
use serde_json::{Value, json};
use crate::VectorcraftApp;
mod views;
pub(crate) use views::{
Views, Win, close_current, close_window, current, label, new_window, retain as retain_views, show_window, unfit_all, view, view_mut, windows,
};
use views::{find, key, window_param};
/// How far above or below the tab strip, in points, a dragged document tab must be released to
/// float its document.
pub(crate) const TEAR_OFF: f32 = 24.0;
@@ -30,11 +39,13 @@ const CASCADE_MARGIN: f32 = 24.0;
/// The smallest size of a document window, in points.
const MIN_SIZE: egui::Vec2 = egui::vec2(240.0, 180.0);
/// A document in a floating window.
/// A document's view in a floating window.
#[derive(Clone, Debug)]
pub struct DocWindow {
/// The document ([`vectorcraft_engine::DocState::uid`]).
pub uid: u64,
/// The view's number ([`views`]).
pub view: u32,
/// Where the window goes, in the main window's points.
pub place: egui::Rect,
/// The window's own number ([`Windows::opened`]): a document floated again gets a new window,
@@ -61,8 +72,8 @@ pub struct DocWindow {
type Fit = (egui::Vec2, f64, vectorcraft_geom::Point);
impl DocWindow {
fn new(uid: u64, place: egui::Rect) -> Self {
Self { uid, place, number: 0, generation: 0, screen: None, focused: false, body: None, fit: None, grab: None }
fn new((uid, view): (u64, u32), place: egui::Rect) -> Self {
Self { uid, view, place, number: 0, generation: 0, screen: None, focused: false, body: None, fit: None, grab: None }
}
}
@@ -71,17 +82,19 @@ impl DocWindow {
pub struct Windows {
/// The document area of the main window (the tabs and the canvas) in its last frame.
pub(crate) area: Option<egui::Rect>,
/// The current document (its uid) when the windows were last drawn: a floating document that
/// becomes the current one comes to the front.
current: Option<u64>,
/// While Presentation Mode is on: the floating documents (their uids) it has shown.
presented: Option<Vec<u64>>,
/// The current window ([`views::key`]) when the windows were last drawn: a floating window
/// that becomes the current one comes to the front.
current: Option<(u64, u32)>,
/// While Presentation Mode is on: the floating windows ([`views::key`]) it has shown.
presented: Option<Vec<(u64, u32)>>,
/// The main window's tab strip in its last frame, while it was drawn.
pub(crate) strip: Option<egui::Rect>,
/// Counts the windows opened ([`DocWindow::number`]).
opened: u32,
/// The open documents (their uids) when [`opened`] last ran, or when the app started.
known: Vec<u64>,
/// The documents' views beyond the one each shows ([`views`]).
pub(crate) views: Views,
}
impl Windows {
@@ -97,32 +110,51 @@ pub(crate) fn torn_off(strip: egui::Rect, p: egui::Pos2) -> bool {
p.y > strip.bottom() + TEAR_OFF || p.y < strip.top() - TEAR_OFF
}
/// Whether document `i` is in a floating window.
/// Whether window `w` is in a floating window.
pub(crate) fn floats(app: &VectorcraftApp, w: Win) -> bool {
key(app, w).is_some_and(|(u, n)| app.ui.floating.iter().any(|x| x.uid == u && x.view == n))
}
/// Whether document `i`'s shown view is in a floating window.
#[cfg(test)]
pub(crate) fn is_floating(app: &VectorcraftApp, i: usize) -> bool {
app.session.documents().get(i).is_some_and(|d| app.ui.floating.iter().any(|w| w.uid == d.uid))
floats(app, (i, views::shown(app, i)))
}
/// The documents under the tab strip, by index, in tab order.
/// The windows under the tab strip, in tab order.
pub(crate) fn docked_windows(app: &VectorcraftApp) -> Vec<Win> {
windows(app).into_iter().filter(|w| !floats(app, *w)).collect()
}
/// The documents with a window under the tab strip, by index, in tab order.
#[cfg(test)]
pub(crate) fn docked(app: &VectorcraftApp) -> Vec<usize> {
(0..app.session.documents().len()).filter(|i| !is_floating(app, *i)).collect()
let mut docs: Vec<usize> = docked_windows(app).into_iter().map(|(i, _)| i).collect();
docs.dedup();
docs
}
/// The document the tab strip shows: the current one when it is under the tabs, else the tabbed
/// document that was current last, else the first tabbed one.
pub(crate) fn tab_document(app: &VectorcraftApp) -> Option<usize> {
let docked = docked(app);
let active = app.session.active_index();
if let Some(a) = active.filter(|a| docked.contains(a)) {
return Some(a);
/// The window the tab strip shows: the current one when it is under the tabs, else the tabbed
/// window that was current last, else the first tabbed one.
pub(crate) fn tab_window(app: &VectorcraftApp) -> Option<Win> {
let docked = docked_windows(app);
if let Some(c) = current(app).filter(|c| docked.contains(c)) {
return Some(c);
}
let last = app.ui.tab_document.and_then(|uid| app.session.documents().iter().position(|d| d.uid == uid));
last.filter(|i| docked.contains(i)).or(docked.first().copied())
let last = app.ui.tab_document.and_then(|k| find(app, k));
last.filter(|w| docked.contains(w)).or(docked.first().copied())
}
/// Whether the current document is in a floating window, outside the Home screen and Presentation
/// Mode: the main window's canvas then draws the tab strip's document as a pane.
/// The document of the window the tab strip shows ([`tab_window`]).
#[cfg(test)]
pub(crate) fn tab_document(app: &VectorcraftApp) -> Option<usize> {
tab_window(app).map(|(i, _)| i)
}
/// Whether the current window is a floating one, outside the Home screen and Presentation Mode:
/// the main window's canvas then draws the tab strip's window as a pane.
pub(crate) fn current_floats(app: &VectorcraftApp) -> bool {
app.session.active_index().is_some_and(|i| is_floating(app, i)) && !crate::menus::home_showing(app) && !presenting(app)
current(app).is_some_and(|w| floats(app, w)) && !crate::menus::home_showing(app) && !presenting(app)
}
/// Whether Presentation Mode is on: the main window shows the current document, and the floating
@@ -151,11 +183,11 @@ fn area(app: &VectorcraftApp) -> egui::Rect {
app.canvas.windows.area.filter(|r| r.is_positive()).unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)))
}
/// Float documents `docs` (indices), each at the next cascade place after the windows already
/// open. Each fits its window.
fn float(app: &mut VectorcraftApp, docs: &[usize]) {
/// Float windows `wins`, each at the next cascade place after the windows already open. Each fits
/// its window.
fn float(app: &mut VectorcraftApp, wins: &[Win]) {
app.sync_views();
place(app, docs);
place(app, wins);
}
/// The documents opened or created since the last call: each one opened while Preferences › User
@@ -168,131 +200,120 @@ pub(crate) fn opened(app: &mut VectorcraftApp) {
if known.len() == docs.len() && known.iter().zip(docs).all(|(u, d)| *u == d.uid) {
return;
}
let new: Vec<usize> = docs.iter().enumerate().filter(|(_, d)| !d.opened_as_tab && !known.contains(&d.uid)).map(|(i, _)| i).collect();
let new: Vec<Win> = docs.iter().enumerate().filter(|(_, d)| !d.opened_as_tab && !known.contains(&d.uid)).map(|(i, _)| (i, 1)).collect();
app.canvas.windows.known = docs.iter().map(|d| d.uid).collect();
if !new.is_empty() {
place(app, &new);
}
}
/// [`float`] for documents whose views exist.
fn place(app: &mut VectorcraftApp, docs: &[usize]) {
/// [`float`] for windows whose views exist.
fn place(app: &mut VectorcraftApp, wins: &[Win]) {
let first = app.ui.floating.len();
let places = cascade_places(area(app), first + docs.len());
for (k, i) in docs.iter().enumerate() {
let Some(uid) = app.session.documents().get(*i).map(|d| d.uid) else { continue };
if app.ui.floating.iter().any(|w| w.uid == uid) {
let places = cascade_places(area(app), first + wins.len());
for (k, w) in wins.iter().enumerate() {
let Some(key) = key(app, *w) else { continue };
if floats(app, *w) {
continue;
}
let place = places.get(first + k).copied().unwrap_or(egui::Rect::from_min_size(egui::Pos2::ZERO, MIN_SIZE));
app.canvas.windows.opened = app.canvas.windows.opened.wrapping_add(1);
let mut w = DocWindow::new(uid, place);
w.number = app.canvas.windows.opened;
app.ui.floating.push(w);
if let Some(v) = app.views.get_mut(*i) {
let mut win = DocWindow::new(key, place);
win.number = app.canvas.windows.opened;
app.ui.floating.push(win);
if let Some(v) = view_mut(app, *w) {
v.fitted = false;
}
}
if !docs.is_empty() {
if !wins.is_empty() {
app.ui.home = None;
}
}
/// The floating documents' indices, in the order their windows opened.
/// The floating windows' document indices, in the order the windows opened.
fn floating_indices(app: &VectorcraftApp) -> Vec<usize> {
app.ui.floating.iter().filter_map(|w| app.session.documents().iter().position(|d| d.uid == w.uid)).collect()
floating_windows(app).into_iter().map(|(i, _)| i).collect()
}
/// The open document `p`'s `index` names: `Ok(None)` without one.
fn document_param(app: &VectorcraftApp, p: &Value) -> Result<Option<usize>, String> {
match p.get("index") {
None | Some(Value::Null) => Ok(None),
Some(v) => v
.as_u64()
.and_then(|i| usize::try_from(i).ok())
.filter(|i| *i < app.session.documents().len())
.map(Some)
.ok_or_else(|| "no such document".to_string()),
}
/// The floating windows, in the order they opened.
pub(crate) fn floating_windows(app: &VectorcraftApp) -> Vec<Win> {
app.ui.floating.iter().filter_map(|w| find(app, (w.uid, w.view))).collect()
}
/// `window.arrange.floatInWindow`: the current document, or document `index`, leaves the tab strip
/// for a floating window of its own, with its top-left corner at `at` (`[x, y]` in the main
/// window's points) when given, else at the next cascade place. A document already floating stays
/// where it is. Document `index` becomes the current one. Returns `{floating}`.
/// `window.arrange.floatInWindow`: the current window, or document `index`'s view `view` (its
/// shown view without one), leaves the tab strip for a floating window of its own, with its
/// top-left corner at `at` (`[x, y]` in the main window's points) when given, else at the next
/// cascade place. A window already floating stays where it is. The window `index` names becomes
/// the current one. Returns `{floating}`, the floating windows' document indices.
pub(crate) fn float_in_window(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let index = document_param(app, p)?;
let named = window_param(app, p)?;
let at = p
.get("at")
.and_then(Value::as_array)
.and_then(|a| Some(egui::pos2(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32)))
.filter(|at| at.is_finite());
if let Some(i) = index.or(app.session.active_index()).filter(|i| !is_floating(app, *i)) {
float(app, &[i]);
if let Some(w) = named.or(current(app)).filter(|w| !floats(app, *w)) {
float(app, &[w]);
if let (Some(at), Some(w)) = (at, app.ui.floating.last_mut()) {
w.place = egui::Rect::from_min_size(at, w.place.size());
}
}
if let Some(i) = index {
crate::chrome::show_document(app, i);
if let Some(w) = named {
show_window(app, w);
}
Ok(json!({ "floating": floating_indices(app) }))
}
/// `window.arrange.consolidateAllWindows` with an `index`: document `index`, floating or not,
/// goes back under its tab, fitted there, and becomes the current one; the other windows and Tile
/// stay as they are. Returns `{tiled, floating}`.
/// `window.arrange.consolidateAllWindows` with an `index`: document `index`'s view `view` (its
/// shown view without one), floating or not, goes back under its tab, fitted there, and becomes
/// the current window; the other windows and Tile stay as they are. Returns `{tiled, floating}`.
pub(crate) fn dock(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let Some(i) = document_param(app, p)? else {
let Some(w) = window_param(app, p)? else {
return Err("no such document".into());
};
if is_floating(app, i) {
let uid = app.session.documents().get(i).map(|d| d.uid);
app.ui.floating.retain(|w| Some(w.uid) != uid);
if let Some(v) = app.views.get_mut(i) {
if let Some((u, n)) = key(app, w).filter(|_| floats(app, w)) {
app.ui.floating.retain(|x| !(x.uid == u && x.view == n));
if let Some(v) = view_mut(app, w) {
v.fitted = false;
}
}
crate::chrome::show_document(app, i);
show_window(app, w);
Ok(json!({ "tiled": app.ui.tiled, "floating": floating_indices(app) }))
}
/// `window.arrange.floatAllInWindows`: every document under the tab strip goes to a floating window
/// `window.arrange.floatAllInWindows`: every window under the tab strip goes to a floating window
/// of its own. Returns `{floating}`.
pub(crate) fn float_all(app: &mut VectorcraftApp) -> Result<Value, String> {
let docked = docked(app);
let docked = docked_windows(app);
float(app, &docked);
Ok(json!({ "floating": floating_indices(app) }))
}
/// `window.arrange.cascade`: every document in a floating window, the windows stacked from the
/// document area's upper left to its lower right in tab order, each fitted to its window, the
/// current document's in front. Returns `{floating}`.
/// `window.arrange.cascade`: every window floating, stacked from the document area's upper left to
/// its lower right in tab order, each fitted to its window, the current window in front. Returns
/// `{floating}`.
pub(crate) fn cascade(app: &mut VectorcraftApp) -> Result<Value, String> {
app.ui.tiled = false;
let docked = docked(app);
let docked = docked_windows(app);
float(app, &docked);
let order: Vec<u64> = app.session.documents().iter().map(|d| d.uid).collect();
app.ui.floating.sort_by_key(|w| order.iter().position(|u| *u == w.uid));
let order: Vec<(u64, u32)> = windows(app).into_iter().filter_map(|w| key(app, w)).collect();
app.ui.floating.sort_by_key(|w| order.iter().position(|k| *k == (w.uid, w.view)));
let places = cascade_places(area(app), app.ui.floating.len());
for (w, place) in app.ui.floating.iter_mut().zip(places) {
w.place = place;
w.generation += 1;
}
for v in &mut app.views {
v.fitted = false;
}
// The current document's window comes to the front.
unfit_all(app);
// The current window comes to the front.
app.canvas.windows.current = None;
Ok(json!({ "floating": floating_indices(app) }))
}
/// Every floating document back under the tab strip ([`crate::canvas::consolidate`], Tile), each
/// Every floating window back under the tab strip ([`crate::canvas::consolidate`], Tile), each
/// fitted to where it shows.
pub(crate) fn dock_all(app: &mut VectorcraftApp) {
let floating = floating_indices(app);
for i in floating {
if let Some(v) = app.views.get_mut(i) {
for w in floating_windows(app) {
if let Some(v) = view_mut(app, w) {
v.fitted = false;
}
}
@@ -319,9 +340,9 @@ fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
true
}
/// The OS window of document window `uid`.
fn viewport_id(uid: u64) -> egui::ViewportId {
egui::ViewportId::from_hash_of(("vectorcraft-document-window", uid))
/// The OS window of document window `w`.
fn viewport_id(w: &DocWindow) -> egui::ViewportId {
egui::ViewportId::from_hash_of(("vectorcraft-document-window", w.uid, w.number))
}
/// The id of document window `w` inside the main window: a new one for each window and each
@@ -352,33 +373,36 @@ struct Shown {
/// Draw the floating document windows, after the main window's canvas. Call once per frame from
/// the main window.
pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let live: Vec<u64> = app.session.documents().iter().map(|d| d.uid).collect();
app.ui.floating.retain(|w| live.contains(&w.uid));
let current = app.session.active().map(|d| d.uid);
if let Some(uid) = current.filter(|u| !app.ui.floating.iter().any(|w| w.uid == *u)) {
app.ui.tab_document = Some(uid);
let live: Vec<(u64, u32)> = windows(app).into_iter().filter_map(|w| key(app, w)).collect();
app.ui.floating.retain(|w| live.contains(&(w.uid, w.view)));
let current = current(app).and_then(|w| key(app, w));
let floating = |app: &VectorcraftApp, k: &(u64, u32)| app.ui.floating.iter().any(|w| (w.uid, w.view) == *k);
if let Some(k) = current.filter(|k| !floating(app, k)) {
app.ui.tab_document = Some(k);
}
// Presentation Mode fits each floating document it shows to the main window: back in their
// floating windows, those documents fit their windows again.
// Presentation Mode fits each floating window it shows to the main window: back in their
// floating windows, those views fit their windows again.
let presenting = presenting(app);
if presenting {
let is_floating = current.is_some_and(|k| floating(app, &k));
let shown = app.canvas.windows.presented.get_or_insert_default();
if let Some(uid) = current.filter(|u| app.ui.floating.iter().any(|w| w.uid == *u) && !shown.contains(u)) {
shown.push(uid);
if let Some(k) = current.filter(|k| is_floating && !shown.contains(k)) {
shown.push(k);
if let Some(v) = app.session.active_index().and_then(|i| app.views.get_mut(i)) {
v.fitted = false;
ctx.request_repaint();
}
}
} else if let Some(shown) = app.canvas.windows.presented.take() {
for (d, v) in app.session.documents().iter().zip(app.views.iter_mut()) {
if shown.contains(&d.uid) {
let wins: Vec<Win> = shown.into_iter().filter_map(|k| find(app, k)).collect();
for w in wins {
if let Some(v) = view_mut(app, w) {
v.fitted = false;
}
}
}
// While Presentation Mode hides the windows, `current` keeps the document whose window was in
// front, so a document made current meanwhile comes to the front when it ends.
// While Presentation Mode hides the windows, `current` keeps the window that was in front, so a
// window made current meanwhile comes to the front when it ends.
if presenting {
return;
}
@@ -402,7 +426,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
#[cfg(not(target_arch = "wasm32"))]
if native {
input::register(ctx, app.services.native_input_hook.clone(), app.ui.floating.iter().map(|w| viewport_id(w.uid)).collect());
input::register(ctx, app.services.native_input_hook.clone(), app.ui.floating.iter().map(viewport_id).collect());
}
// While a dialog or other modal is open the windows take no input, as the main window behind
// it takes none: each draws its document as a pane, the current one included.
@@ -412,31 +436,29 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let mut dock = None;
let mut over_strip = false;
for w in app.ui.floating.clone() {
let Some(i) = app.session.documents().iter().position(|d| d.uid == w.uid) else { continue };
let shown = if native {
os_window(app, ctx, &w, (i, blocked), raise == Some(w.uid))
} else {
app_window(app, ctx, &w, (i, blocked), raise == Some(w.uid))
};
let Some(win) = find(app, (w.uid, w.view)) else { continue };
let raised = raise == Some((w.uid, w.view));
let shown = if native { os_window(app, ctx, &w, (win, blocked), raised) } else { app_window(app, ctx, &w, (win, blocked), raised) };
if blocked {
continue;
}
if let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid) {
// The OS window took the keyboard: its document becomes the current one.
if shown.focused && !win.focused && app.session.active_index() != Some(i) {
activate = Some(i);
let is_current = views::current(app) == Some(win);
if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid && x.view == w.view) {
// The OS window took the keyboard: its view becomes the current window.
if shown.focused && !x.focused && !is_current {
activate = Some(win);
}
win.focused = shown.focused;
win.body = shown.body;
win.fit = shown.fit;
x.focused = shown.focused;
x.body = shown.body;
x.fit = shown.fit;
}
over_strip |= shown.over_strip;
if shown.close {
close = Some(i);
close = Some(win);
} else if shown.dock {
dock = Some(i);
} else if shown.activate && app.session.active_index() != Some(i) {
activate = Some(i);
dock = Some(win);
} else if shown.activate && !is_current {
activate = Some(win);
}
}
// The tab strip a dragged window would go back under shows where it lands.
@@ -446,61 +468,61 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
painter.rect_filled(strip, 0.0, t.accent.gamma_multiply(0.12));
painter.rect_stroke(strip, 0.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);
}
if let Some(i) = close {
if let Some(win) = close {
// The save prompt opens in the main window.
if let Err(e) = crate::unsaved::close(app, i) {
if let Err(e) = close_window(app, win) {
app.status(e);
}
if native && app.ui.dialog.is_some() {
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus);
}
} else if let Some(i) = dock {
if let Err(e) = app.run("window.arrange.consolidateAllWindows", json!({ "index": i })) {
} else if let Some((i, n)) = dock {
if let Err(e) = app.run("window.arrange.consolidateAllWindows", json!({ "index": i, "view": n })) {
app.status(e);
}
if native {
ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Focus);
}
} else if let Some(i) = activate {
crate::chrome::show_document(app, i);
app.canvas.windows.current = app.session.active().map(|d| d.uid);
} else if let Some(win) = activate {
show_window(app, win);
app.canvas.windows.current = views::current(app).and_then(|w| key(app, w));
}
}
/// Document `i`'s window body in `ui`: the canvas for the current document, else (and while
/// `blocked` by a modal) a pane. The document fits the body again when the body changed size since
/// `fit` and its view has not moved. → whether a press in the pane asks for its document to become
/// the current one, the body's rect and the fit after this frame.
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (i, blocked): (usize, bool), fit: Option<Fit>) -> (bool, egui::Rect, Option<Fit>) {
/// Window `win`'s body in `ui`: the canvas for the current window, else (and while `blocked` by a
/// modal) a pane. The view fits the body again when the body changed size since `fit` and the view
/// has not moved. → whether a press in the pane asks for its window to become the current one, the
/// body's rect and the fit after this frame.
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool), fit: Option<Fit>) -> (bool, egui::Rect, Option<Fit>) {
let t = crate::theme::Tokens::get(ui.ctx());
let rect = ui.available_rect_before_wrap();
ui.painter().rect_filled(rect, 0.0, t.pasteboard);
if let (Some(v), Some((size, zoom, center))) = (app.views.get_mut(i), fit)
if let (Some(v), Some((size, zoom, center))) = (view_mut(app, win), fit)
&& size != rect.size()
&& zoom == v.zoom
&& center == v.center
{
v.fitted = false;
}
let was_fitted = app.views.get(i).is_some_and(|v| v.fitted);
let pressed = if !blocked && app.session.active_index() == Some(i) && !crate::menus::home_showing(app) {
let was_fitted = view(app, win).is_some_and(|v| v.fitted);
let pressed = if !blocked && views::current(app) == Some(win) && !crate::menus::home_showing(app) {
crate::canvas::show(app, ui);
false
} else {
crate::canvas::pane(app, ui, i, rect)
crate::canvas::pane(app, ui, win, rect)
};
ui.advance_cursor_after_rect(rect);
let fit = match app.views.get(i) {
let fit = match view(app, win) {
Some(v) if v.fitted && !was_fitted => Some((rect.size(), v.zoom, v.center)),
_ => fit,
};
(pressed, rect, fit)
}
/// Document `i`'s window `w` as an OS window of its own, `blocked` by a modal or not; `raise`
/// brings it to the front. The document's tab is at the top of the window, above its body.
fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown {
let vid = viewport_id(w.uid);
/// Window `win`'s floating window `w` as an OS window of its own, `blocked` by a modal or not;
/// `raise` brings it to the front. Its tab is at the top of the window, above its body.
fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win, blocked): (Win, bool), raise: bool) -> Shown {
let vid = viewport_id(w);
let origin = ctx.input(|inp| inp.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO);
let screen = match w.screen {
Some((pos, generation)) if generation == w.generation => pos,
@@ -510,8 +532,8 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b
ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::OuterPosition(pos));
ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::InnerSize(w.place.size()));
}
if let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid) {
win.screen = Some((pos, w.generation));
if let Some(x) = app.ui.floating.iter_mut().find(|x| x.uid == w.uid && x.view == w.view) {
x.screen = Some((pos, w.generation));
}
pos
}
@@ -519,7 +541,7 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b
if raise {
ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::Focus);
}
let title = crate::chrome::document_window_title(app, i).unwrap_or_default();
let title = crate::chrome::document_window_title(app, win).unwrap_or_default();
let builder =
egui::ViewportBuilder::default().with_title(title).with_position(screen).with_inner_size(w.place.size()).with_min_inner_size(MIN_SIZE);
let mut forwarded = (Vec::new(), None);
@@ -532,9 +554,9 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b
// or a modal can keep the document open.
ui.ctx().send_viewport_cmd(egui::ViewportCommand::CancelClose);
}
let tab = crate::chrome::window_tab(app, ui, i);
let (over_strip, dock) = if blocked { (false, false) } else { drag_tab(app, ui, (w.uid, origin), &tab, strip) };
let (pressed, rect, fit) = body(app, ui, (i, blocked), w.fit);
let tab = crate::chrome::window_tab(app, ui, win);
let (over_strip, dock) = if blocked { (false, false) } else { drag_tab(app, ui, ((w.uid, w.view), origin), &tab, strip) };
let (pressed, rect, fit) = body(app, ui, (win, blocked), w.fit);
let activate = pressed || (!blocked && (tab.clicked() || tab.drag_started()));
// Keys the window's widgets left over run the main window's shortcuts and tool keys, as a
// floating panel's do.
@@ -559,18 +581,18 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, b
shown
}
/// A drag of document window `uid`'s OS window by the `tab` at its top: the window follows the
/// pointer, and its document goes back under the tabs when the tab is released over the main
/// window's tab `strip` (on the screen). `origin` is the main window's top-left corner on the
/// A drag of floating window `key`'s ([`views::key`]) OS window by the `tab` at its top: the window
/// follows the pointer, and its view goes back under the tabs when the tab is released over the
/// main window's tab `strip` (on the screen). `origin` is the main window's top-left corner on the
/// screen. → whether the pointer is over the strip, and whether the tab was released there.
fn drag_tab(
app: &mut VectorcraftApp,
ui: &egui::Ui,
(uid, origin): (u64, egui::Pos2),
((uid, view), origin): ((u64, u32), egui::Pos2),
tab: &egui::Response,
strip: Option<egui::Rect>,
) -> (bool, bool) {
let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == uid) else {
let Some(win) = app.ui.floating.iter_mut().find(|x| x.uid == uid && x.view == view) else {
return (false, false);
};
if !tab.dragged() && !tab.drag_stopped() {
@@ -598,14 +620,14 @@ fn drag_tab(
(over, false)
}
/// Document `i`'s window `w` as a window inside the main window, `blocked` by a modal or not;
/// `raise` brings it to the front.
fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i, blocked): (usize, bool), raise: bool) -> Shown {
/// Window `win`'s floating window `w` as a window inside the main window, `blocked` by a modal or
/// not; `raise` brings it to the front.
fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win, blocked): (Win, bool), raise: bool) -> Shown {
let id = window_id(w);
if raise {
ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id));
}
let title = crate::chrome::document_window_title(app, i).unwrap_or_default();
let title = crate::chrome::document_window_title(app, win).unwrap_or_default();
let mut open = true;
let (mut activate, mut rect, mut fit) = (false, None, w.fit);
let frame = egui::Frame::window(&ctx.global_style()).inner_margin(0.0);
@@ -619,7 +641,7 @@ fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (i,
.frame(frame)
.open(&mut open)
.show(ctx, |ui| {
let (pressed, r, f) = body(app, ui, (i, blocked), fit);
let (pressed, r, f) = body(app, ui, (win, blocked), fit);
(activate, rect, fit) = (pressed, Some(r), f);
});
// A press on its title bar or edges, which brings the window to the front, also makes its
+168 -3
View File
@@ -257,11 +257,11 @@ fn tile_brings_floating_documents_back_into_the_grid() {
app.run("window.arrange.tile", json!({})).unwrap();
app.run("window.arrange.floatInWindow", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
let docs: Vec<usize> = app.canvas.panes.last.iter().map(|(i, _)| *i).collect();
let docs: Vec<usize> = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect();
assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it");
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3}));
frame(&mut app, &ctx, vec![]);
let docs: Vec<usize> = app.canvas.panes.last.iter().map(|(i, _)| *i).collect();
let docs: Vec<usize> = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect();
assert_eq!(docs, [0, 1, 2]);
assert!(app.ui.floating.is_empty());
}
@@ -437,7 +437,7 @@ fn closing_an_os_window_keeps_it_while_its_unsaved_document_stays_open() {
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
app.run("window.arrange.floatInWindow", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
let vid = viewport_id(app.session.documents()[1].uid);
let vid = viewport_id(&app.ui.floating[0]);
host.borrow_mut().close = true;
frame(&mut app, &ctx, vec![]);
host.borrow_mut().close = false;
@@ -725,3 +725,168 @@ fn the_arrange_items_are_enabled_as_the_documents_allow() {
app.run("window.arrange.consolidateAllWindows", json!({})).unwrap();
assert_eq!(states(&app), [true, true, true, true, false], "consolidated");
}
/// The title of window `w`'s tab.
fn title_of(app: &VectorcraftApp, w: Win) -> String {
crate::chrome::document_window_title(app, w).unwrap()
}
#[test]
fn new_window_opens_a_numbered_view_with_its_own_zoom() {
let mut app = app_with(1);
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let name = app.session.documents()[0].title();
assert!(!title_of(&app, (0, 1)).contains(&format!("{name}:")), "one view: no number");
let zoom = app.view().unwrap().zoom;
assert_eq!(app.run("window.newWindow", json!({})).unwrap(), json!({"index": 0, "view": 2}));
assert_eq!(windows(&app), [(0, 1), (0, 2)]);
assert_eq!(current(&app), Some((0, 2)), "the new view is the current window");
assert_eq!(app.view().unwrap().zoom, zoom, "it opens where the first view is");
assert!(title_of(&app, (0, 1)).starts_with(&format!("{name}:1 @")), "{}", title_of(&app, (0, 1)));
assert!(title_of(&app, (0, 2)).starts_with(&format!("{name}:2 @")), "{}", title_of(&app, (0, 2)));
let shapes = frame(&mut app, &ctx, vec![]);
assert!(tab_drawn(&shapes, &format!("{name}:1")) && tab_drawn(&shapes, &format!("{name}:2")), "each view has a tab");
// Each view keeps its own zoom.
app.run("view.zoomIn", json!({})).unwrap();
let zoomed = app.view().unwrap().zoom;
assert_ne!(zoomed, zoom);
show_window(&mut app, (0, 1));
assert_eq!(app.view().unwrap().zoom, zoom, "the first view did not zoom");
assert_eq!(view(&app, (0, 2)).unwrap().zoom, zoomed);
show_window(&mut app, (0, 2));
assert_eq!(app.view().unwrap().zoom, zoomed);
assert_eq!(app.run("window.newWindow", json!({})).unwrap(), json!({"index": 0, "view": 3}));
}
#[test]
fn an_edit_in_one_view_shows_in_the_other() {
let mut app = app_with(1);
let ctx = egui::Context::default();
app.run("window.newWindow", json!({})).unwrap();
app.run("window.arrange.tile", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
assert_eq!(app.canvas.panes.last.iter().map(|(w, _)| *w).collect::<Vec<_>>(), [(0, 1), (0, 2)], "one pane per view");
view_mut(&mut app, (0, 1)).unwrap().zoom = 0.5;
app.view_mut().unwrap().zoom = 2.0;
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![]);
let d = &app.session.documents()[0];
let shown = app.canvas.panes.shown.get(&(d.uid, 1)).map(|(k, _)| (k.revision, k.zoom));
assert_eq!(shown, Some((d.revision, 0.5)), "the other view's pane shows the edit at its own zoom");
assert_eq!(app.view().unwrap().zoom, 2.0, "the view edited in keeps its zoom");
}
#[test]
fn closing_a_view_leaves_the_document_open() {
let mut app = app_with(1);
let ctx = egui::Context::default();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
app.run("window.newWindow", json!({})).unwrap();
app.run("window.newWindow", json!({})).unwrap();
show_window(&mut app, (0, 2));
assert_eq!(app.run("file.close", json!({})).unwrap(), json!({"index": 0, "views": 2}));
assert!(app.ui.dialog.is_none(), "closing a view does not ask to save");
assert_eq!((app.session.documents().len(), windows(&app)), (1, vec![(0, 1), (0, 3)]));
assert_eq!(current(&app), Some((0, 3)), "the next view becomes the current window");
frame(&mut app, &ctx, vec![]);
assert_eq!(app.run("file.close", json!({})).unwrap(), json!({"index": 0, "views": 1}));
assert_eq!(windows(&app), [(0, 1)], "the view left is the document's only view again");
let name = app.session.documents()[0].title();
assert!(!title_of(&app, (0, 1)).contains(&format!("{name}:")), "{}", title_of(&app, (0, 1)));
// The last view: the document closes, asking to save it first.
app.run("file.close", json!({})).unwrap();
assert!(app.ui.dialog.is_some(), "the changed document asks to be saved");
assert_eq!(app.session.documents().len(), 1);
}
#[test]
fn arrange_treats_each_view_as_a_window() {
let mut app = app_with(1);
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
assert!(!enabled(&app, "window.arrange.tile") && !enabled(&app, "window.arrange.cascade"), "one window");
app.run("window.newWindow", json!({})).unwrap();
assert!(enabled(&app, "window.arrange.tile") && enabled(&app, "window.arrange.cascade"), "two views of one document");
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2}));
app.run("window.arrange.cascade", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
let uid = app.session.documents()[0].uid;
let floating: Vec<(u64, u32)> = app.ui.floating.iter().map(|w| (w.uid, w.view)).collect();
assert_eq!(floating, [(uid, 1), (uid, 2)], "each view in a window of its own, in tab order");
assert_ne!(app.ui.floating[0].place.min, app.ui.floating[1].place.min, "stacked down and to the right");
assert!(docked_windows(&app).is_empty());
app.run("window.arrange.consolidateAllWindows", json!({})).unwrap();
assert!(app.ui.floating.is_empty());
assert_eq!(docked_windows(&app), [(0, 1), (0, 2)]);
// Float in Window floats the current view only.
app.run("window.arrange.floatInWindow", json!({})).unwrap();
assert_eq!(app.ui.floating.iter().map(|w| (w.uid, w.view)).collect::<Vec<_>>(), [(uid, 2)]);
assert_eq!(docked_windows(&app), [(0, 1)], "the first view keeps its tab");
frame(&mut app, &ctx, vec![]);
let shapes = frame(&mut app, &ctx, vec![]);
let name = app.session.documents()[0].title();
assert!(tab_drawn(&shapes, &format!("{name}:1")) && !tab_drawn(&shapes, &format!("{name}:2")));
// A new view of a floating view floats too.
app.run("window.newWindow", json!({})).unwrap();
assert!(floats(&app, (0, 3)), "it opens beside the view it came from");
app.run("window.arrange.floatAllInWindows", json!({})).unwrap();
assert!(docked_windows(&app).is_empty());
assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({"index": 0, "view": 3})).unwrap()["floating"], json!([0, 0]));
assert_eq!((docked_windows(&app), current(&app)), (vec![(0, 3)], Some((0, 3))));
}
#[test]
fn each_pane_draws_its_own_views_outline_or_preview() {
let mut app = app_with(1);
let ctx = egui::Context::default();
app.run("window.newWindow", json!({})).unwrap();
show_window(&mut app, (0, 1));
app.run("view.outline", json!({})).unwrap();
show_window(&mut app, (0, 2));
assert!(!app.outline_view(), "the second view is in Preview");
app.run("window.arrange.tile", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
let uid = app.session.documents()[0].uid;
assert_eq!(app.canvas.panes.shown.get(&(uid, 1)).map(|(k, _)| k.outline), Some(true), "the first view's pane is in Outline");
}
#[test]
fn next_and_previous_document_step_through_the_views() {
let mut app = app_with(2);
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("window.newWindow", json!({})).unwrap();
assert_eq!(app.run("window.nextDocument", json!({})).unwrap(), json!({"index": 1}));
assert_eq!(app.run("window.nextDocument", json!({})).unwrap(), json!({"index": 0, "view": 1}));
assert_eq!(app.run("window.nextDocument", json!({})).unwrap(), json!({"index": 0, "view": 2}));
assert_eq!(current(&app), Some((0, 2)));
assert_eq!(app.run("window.previousDocument", json!({})).unwrap(), json!({"index": 0, "view": 1}));
assert_eq!(app.run("window.previousDocument", json!({})).unwrap(), json!({"index": 1}));
}
#[test]
fn switching_views_resets_the_tool() {
let mut app = app_with(2);
app.run("window.newWindow", json!({})).unwrap();
let before = app.session.tool_resets();
show_window(&mut app, (1, 1));
assert_eq!(app.session.tool_resets(), before + 1, "another view of the current document resets the tool");
show_window(&mut app, (1, 1));
assert_eq!(app.session.tool_resets(), before + 1, "the current view stays as it is");
}
#[test]
fn switching_views_targets_the_artboard_the_view_shows() {
let mut app = app_with(1);
app.run("artboard.new", json!({})).unwrap();
app.run("tool.select", json!({"tool": "artboard"})).unwrap();
crate::panels::artboards::select(&mut app, 0);
app.run("window.newWindow", json!({})).unwrap();
crate::panels::artboards::select(&mut app, 1);
assert_eq!(app.session.tool_options()["active"], json!(1));
show_window(&mut app, (0, 1));
assert_eq!(app.session.tool_options()["active"], json!(0), "the first view shows the first artboard");
show_window(&mut app, (0, 2));
assert_eq!(app.session.tool_options()["active"], json!(1));
}
+247
View File
@@ -0,0 +1,247 @@
//! Window › New Window: more views of an open document, each with its own zoom, center, rotation,
//! artboard and Outline or Preview, shown as tabs titled with the view's number ("Name:2"). Tile,
//! Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as
//! they arrange a document. Every view shows the same document, so an edit made in one shows in
//! all of them. Closing a view leaves the document open until its last view closes.
//!
//! A window is a document's index and its view's number ([`Win`]). The view a document shows
//! while it is the current one is in [`VectorcraftApp::views`]; its other views are kept in
//! [`Views`].
use std::collections::HashMap;
use serde_json::{Value, json};
use crate::VectorcraftApp;
use crate::state::View;
/// A window: an open document's index and its view's number (1 for a document's first view).
pub(crate) type Win = (usize, u32);
/// A view of an open document other than the one [`VectorcraftApp::views`] holds for it.
#[derive(Clone, Debug)]
struct OtherView {
/// The document ([`vectorcraft_engine::DocState::uid`]).
uid: u64,
/// The view's number.
number: u32,
view: View,
}
/// The views of the open documents beyond the one each document shows.
#[derive(Default)]
pub struct Views {
others: Vec<OtherView>,
/// By document uid: the number of the view in [`VectorcraftApp::views`] (1 when absent).
shown: HashMap<u64, u32>,
}
fn uid(app: &VectorcraftApp, i: usize) -> Option<u64> {
app.session.documents().get(i).map(|d| d.uid)
}
/// The number of the view of document `i` that [`VectorcraftApp::views`] holds.
pub(crate) fn shown(app: &VectorcraftApp, i: usize) -> u32 {
uid(app, i).and_then(|u| app.canvas.windows.views.shown.get(&u).copied()).unwrap_or(1)
}
/// The numbers of document `i`'s views, in order; none for a document that is not open.
pub(crate) fn numbers(app: &VectorcraftApp, i: usize) -> Vec<u32> {
let Some(u) = uid(app, i) else { return vec![] };
let mut n: Vec<u32> =
std::iter::once(shown(app, i)).chain(app.canvas.windows.views.others.iter().filter(|o| o.uid == u).map(|o| o.number)).collect();
n.sort_unstable();
n
}
/// Every window, by document and then by view number: the tab order.
pub(crate) fn windows(app: &VectorcraftApp) -> Vec<Win> {
(0..app.session.documents().len()).flat_map(|i| numbers(app, i).into_iter().map(move |n| (i, n))).collect()
}
/// The current window: the current document's shown view.
pub(crate) fn current(app: &VectorcraftApp) -> Option<Win> {
app.session.active_index().map(|i| (i, shown(app, i)))
}
/// Window `w`'s key, which stays the same while documents before it close: its document's uid and
/// its view's number.
pub(crate) fn key(app: &VectorcraftApp, (i, n): Win) -> Option<(u64, u32)> {
uid(app, i).map(|u| (u, n))
}
/// The window `key` ([`key`]) names, while its document is open.
pub(crate) fn find(app: &VectorcraftApp, (u, n): (u64, u32)) -> Option<Win> {
let i = app.session.documents().iter().position(|d| d.uid == u)?;
numbers(app, i).contains(&n).then_some((i, n))
}
/// Window `w`'s view.
pub(crate) fn view(app: &VectorcraftApp, (i, n): Win) -> Option<&View> {
if n == shown(app, i) {
return app.views.get(i);
}
let u = uid(app, i)?;
app.canvas.windows.views.others.iter().find(|o| o.uid == u && o.number == n).map(|o| &o.view)
}
/// Window `w`'s view, to change.
pub(crate) fn view_mut(app: &mut VectorcraftApp, (i, n): Win) -> Option<&mut View> {
if n == shown(app, i) {
return app.views.get_mut(i);
}
let u = uid(app, i)?;
app.canvas.windows.views.others.iter_mut().find(|o| o.uid == u && o.number == n).map(|o| &mut o.view)
}
/// Unfit every window's view: each fits where it shows next.
pub(crate) fn unfit_all(app: &mut VectorcraftApp) {
for v in &mut app.views {
v.fitted = false;
}
for o in &mut app.canvas.windows.views.others {
o.view.fitted = false;
}
}
/// The number a window's title shows: its view's while its document has more than one view.
pub(crate) fn label(app: &VectorcraftApp, (i, n): Win) -> Option<u32> {
(numbers(app, i).len() > 1).then_some(n)
}
/// Make view `n` the one [`VectorcraftApp::views`] holds for document `i`. False when the document
/// has no such view. While document `i` is the current one, the tool is reset first, as a switch to
/// another document resets it, and with the Artboard tool the artboard the view shows becomes the
/// tool's target.
fn bring(app: &mut VectorcraftApp, (i, n): Win) -> bool {
let old = shown(app, i);
if n == old {
return app.views.get(i).is_some();
}
let Some(u) = uid(app, i) else { return false };
if app.views.get(i).is_none() || !app.canvas.windows.views.others.iter().any(|o| o.uid == u && o.number == n) {
return false;
}
if app.session.active_index() == Some(i) {
app.session.reset_tool();
}
let views = &mut app.canvas.windows.views;
let (Some(other), Some(shown)) = (views.others.iter_mut().find(|o| o.uid == u && o.number == n), app.views.get_mut(i)) else {
return false;
};
std::mem::swap(shown, &mut other.view);
other.number = old;
views.shown.insert(u, n);
if app.session.active_index() == Some(i)
&& app.session.tool_id() == "artboard"
&& let Some(count) = app.session.active().map(|d| d.doc.artboards.len())
{
let board = crate::panels::artboards::selected(app, count);
crate::panels::artboards::select(app, board);
}
true
}
/// Make window `w` the current one, as a click on its tab does.
pub(crate) fn show_window(app: &mut VectorcraftApp, w: Win) {
bring(app, w);
crate::chrome::show_document(app, w.0);
}
/// Forget the views of documents that have closed, and keep each other view on an artboard its
/// document has. Called by [`VectorcraftApp::sync_views`].
pub(crate) fn retain(app: &mut VectorcraftApp) {
let views = &mut app.canvas.windows.views;
if views.others.is_empty() && views.shown.is_empty() {
return;
}
let docs = app.session.documents();
views.shown.retain(|u, _| docs.iter().any(|d| d.uid == *u));
views.others.retain_mut(|o| match docs.iter().find(|d| d.uid == o.uid) {
Some(d) => {
o.view.artboard = o.view.artboard.min(d.doc.artboards.len().saturating_sub(1));
true
}
None => false,
});
}
/// `window.newWindow`: another view of the current document, numbered after its others, which
/// starts where the current view is and becomes the current window. It opens as a tab, or in a
/// floating window of its own when the current view is in one. Returns `{index, view}`.
pub(crate) fn new_window(app: &mut VectorcraftApp) -> Result<Value, String> {
app.sync_views();
let Some((i, n)) = current(app) else { return Err("no document open".into()) };
let (Some(u), Some(view)) = (uid(app, i), app.views.get(i).copied()) else { return Err("no document open".into()) };
let number = numbers(app, i).last().copied().unwrap_or(n) + 1;
let floats = super::floats(app, (i, n));
app.canvas.windows.views.others.push(OtherView { uid: u, number, view });
show_window(app, (i, number));
if floats {
super::place(app, &[(i, number)]);
}
Ok(json!({ "index": i, "view": number }))
}
/// Close window `w`: its view goes, and its document stays open with its other views. A
/// document's last view closes the document, asking to save it first when it has changed
/// ([`crate::unsaved::close`]). When one view is left, it is numbered 1 again. Nothing closes while
/// a file dialog's sheet is on the window.
pub(crate) fn close_window(app: &mut VectorcraftApp, (i, n): Win) -> Result<Value, String> {
let nums = numbers(app, i);
if nums.len() <= 1 {
return crate::unsaved::close(app, i);
}
crate::unsaved::refuse_while_picking(app)?;
let Some(u) = uid(app, i) else { return Err("no such document".into()) };
if !nums.contains(&n) {
return Err("no such document".into());
}
let was_current = current(app) == Some((i, n));
// The document's next view in the tab strip takes the closing one's place.
let next = nums.iter().copied().find(|m| *m > n).or(nums.iter().copied().rfind(|m| *m != n));
if n == shown(app, i)
&& let Some(next) = next
{
bring(app, (i, next));
}
app.canvas.windows.views.others.retain(|o| !(o.uid == u && o.number == n));
app.ui.floating.retain(|w| !(w.uid == u && w.view == n));
if app.ui.tab_document == Some((u, n)) {
app.ui.tab_document = None;
}
let left = numbers(app, i);
if let [only] = left[..] {
app.canvas.windows.views.shown.remove(&u);
for w in app.ui.floating.iter_mut().filter(|w| w.uid == u && w.view == only) {
w.view = 1;
}
if app.ui.tab_document == Some((u, only)) {
app.ui.tab_document = Some((u, 1));
}
}
if was_current {
crate::chrome::show_document(app, i);
}
Ok(json!({ "index": i, "views": left.len() }))
}
/// `file.close` without an `index`: the current window closes ([`close_window`]).
pub(crate) fn close_current(app: &mut VectorcraftApp) -> Result<Value, String> {
let Some(w) = current(app) else { return Err("no document open".into()) };
close_window(app, w)
}
/// `params`' `index` and `view`: the window they name, `Ok(None)` without an `index`. Without a
/// `view`, the document's shown view.
pub(crate) fn window_param(app: &VectorcraftApp, p: &Value) -> Result<Option<Win>, String> {
let i = match p.get("index") {
None | Some(Value::Null) => return Ok(None),
Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < app.session.documents().len()).ok_or("no such document")?,
};
let n = match p.get("view") {
None | Some(Value::Null) => shown(app, i),
Some(v) => v.as_u64().and_then(|n| u32::try_from(n).ok()).filter(|n| numbers(app, i).contains(n)).ok_or("no such document")?,
};
Ok(Some((i, n)))
}
+9 -5
View File
@@ -26,6 +26,8 @@ struct Artwork {
#[derive(Clone)]
struct Hover {
uid: u64,
/// The hovered tab's view of its document (Window › New Window).
view: u32,
since: f64,
}
@@ -91,14 +93,16 @@ pub(crate) fn cleanup(app: &VectorcraftApp, ctx: &Context) {
}
}
/// Hover uses `contains_pointer`: the source canvas still owns egui's dragged widget.
pub(crate) fn hover_tab(app: &mut VectorcraftApp, resp: &Response, index: usize, close: egui::Rect) -> bool {
/// Hover uses `contains_pointer`: the source canvas still owns egui's dragged widget. The tab is
/// window `win`'s: another view of the current document's is a tab to switch to as well.
pub(crate) fn hover_tab(app: &mut VectorcraftApp, resp: &Response, win: crate::doc_windows::Win, close: egui::Rect) -> bool {
let ctx = &resp.ctx;
let (index, view) = win;
let eligible = resp.contains_pointer()
&& ctx
.input(|i| i.pointer.primary_down() && !i.key_pressed(egui::Key::Escape) && i.pointer.interact_pos().is_some_and(|p| !close.contains(p)))
&& app.ui.dialog.is_none();
if !eligible || app.session.active_index() == Some(index) || ctx.data(|d| d.get_temp::<egui::Pos2>(activated_at_id()).is_some()) {
if !eligible || crate::doc_windows::current(app) == Some(win) || ctx.data(|d| d.get_temp::<egui::Pos2>(activated_at_id()).is_some()) {
return false;
}
let transfer = egui::DragAndDrop::has_payload_of_type::<Artwork>(ctx);
@@ -110,7 +114,7 @@ pub(crate) fn hover_tab(app: &mut VectorcraftApp, resp: &Response, index: usize,
return false;
};
let now = ctx.input(|i| i.time);
let hover = ctx.data(|d| d.get_temp::<Hover>(hover_id())).filter(|h| h.uid == uid).unwrap_or(Hover { uid, since: now });
let hover = ctx.data(|d| d.get_temp::<Hover>(hover_id())).filter(|h| h.uid == uid && h.view == view).unwrap_or(Hover { uid, view, since: now });
ctx.data_mut(|d| d.insert_temp(hover_id(), hover.clone()));
let remaining = HOVER_SECONDS - (now - hover.since);
if remaining > 0.0 {
@@ -147,7 +151,7 @@ pub(crate) fn hover_tab(app: &mut VectorcraftApp, resp: &Response, index: usize,
egui::DragAndDrop::set_payload(ctx, art);
}
app.ui.home = None;
app.session.set_active(index);
crate::doc_windows::show_window(app, win);
ctx.request_repaint();
let at = ctx.input(|i| i.pointer.interact_pos());
ctx.data_mut(|d| {
+11 -1
View File
@@ -286,7 +286,7 @@ mod tests {
/// Change All leaves locked text in its font, and the status bar says so.
#[test]
fn change_all_says_when_locked_text_keeps_its_font() {
fn change_all_clears_the_skip_warning_after_unlocking_text() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
@@ -298,6 +298,16 @@ mod tests {
assert_eq!(r["runs"], 0, "{r}");
assert_eq!(fonts(&mut app)[0]["family"], "Missing Family");
assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced");
app.run("object.unlockAll", json!({})).unwrap();
assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced");
let r = change(&mut app, &d, &from, true).unwrap();
assert_eq!(r["runs"], 1, "{r}");
assert!(r.get("warning").is_none(), "{r}");
assert_eq!(app.ui.status, "");
app.ui.status = "Saved another document".into();
let r = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap();
assert_eq!(r["runs"], 0, "{r}");
assert_eq!(app.ui.status, "Saved another document");
}
#[test]
+1
View File
@@ -6027,6 +6027,7 @@ breakText Glyphs Глифи
Gap 5 Разстояние 5
@msg {_1}: they came in as the page's art {_1}: те са внесени като изображението от страницата
@msg objects that drew differently from the file's own page came in as its art: {_1} обектите, изобразени различно от собствената страница на файла, са внесени като изображението от страницата: {_1}
@msg You must choose a side pattern. Трябва да изберете страничен шаблон.
@msg invalid pattern tile choice невалиден избор на плочка за шаблон
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -4257,7 +4257,7 @@ imageTrace Outline Obris
@msg Save for Web: the image is empty Sačuvaj za web: slika je prazna
@msg Save writes {_1}, not {_2}: use document.export for other formats Sačuvaj zapisuje {_1}, a ne {_2}: za druge formate koristite document.export
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Sačuvaj zapisuje {_1}, a ne {_2}: za zapisivanje koristite file.saveAsTemplate
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 zapisuje naslijeđene .ai datoteke; .ait predložak je uvijek kompatibilan s PDF-om
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 zapisuje naslijeđene .ai datoteke, a ne .ait predloške
@msg Saved recovery data for {title} Sačuvani podaci za oporavak za {title}
@msg Saved to User Defined: {_1} Sačuvano u korisnički definisano: {_1}
@msg Saved {path} Sačuvano: {path}
@@ -6061,6 +6061,7 @@ shape Open Otvoren
@msg the paths have nothing to merge there putanje tu nemaju šta spojiti
@msg the path is locked or hidden putanja je zaključana ili skrivena
@msg {_1}: they came in as the page's art {_1}: uvezeni su kao ilustracija stranice
@msg objects that drew differently from the file's own page came in as its art: {_1} objekti koji su se iscrtali drugačije od vlastite stranice datoteke uvezeni su kao ilustracija stranice: {_1}
@msg You must choose a side pattern. Morate odabrati bočni uzorak.
@msg invalid pattern tile choice nevažeći izbor pločice uzorka
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -4921,7 +4921,7 @@ digits Malayalam Malaiàlam
@msg a {width}×{height} screenshot's byte count overflows el recompte de bytes d’una captura de pantalla de {width}×{height} es desborda
@msg action is required cal una acció
@msg add a format to export afegiu un format per exportar
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 escriu fitxers .ai heretats; una plantilla .ait sempre és compatible amb PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 escriu fitxers .ai heretats, no plantilles .ait
@msg already editing a pattern ja s’està editant un motiu
@msg an exporter always gets an export's budget: leave `budget` out un exportador sempre rep el pressupost d’una exportació: ometeu `budget`
@msg an image has no pixels and was left out una imatge no té píxels i s’ha omès
@@ -6159,6 +6159,7 @@ breakText Glyphs Glifs
Gap 5 Separació 5
@msg {_1}: they came in as the page's art {_1}: han entrat com a art de la pàgina
@msg objects that drew differently from the file's own page came in as its art: {_1} els objectes que es dibuixaven diferent de la pàgina pròpia del fitxer han entrat com a art de la pàgina: {_1}
@msg the JPEG 2000 file can't be read no es pot llegir el fitxer JPEG 2000
@msg the JPEG 2000 file has an unsupported color space or JPX content el fitxer JPEG 2000 té un espai de color o contingut JPX no compatible
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -4305,7 +4305,7 @@ imageTrace Outline Obrys
@msg Save for Web: the image is empty Uložit pro web: obraz je prázdný
@msg Save writes {_1}, not {_2}: use document.export for other formats Uložení zapisuje {_1}, ne {_2}: pro jiné formáty použijte document.export
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Uložení zapisuje {_1}, ne {_2}: k jeho zápisu použijte file.saveAsTemplate
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 zapisuje starší soubory .ai; šablona .ait je vždy kompatibilní s PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 zapisuje starší soubory .ai, ne šablony .ait
@msg Saved recovery data for {title} Data pro obnovení uložena pro {title}
@msg Saved to User Defined: {_1} Uloženo do uživatelských knihoven: {_1}
@msg Saved {path} Uloženo: {path}
@@ -6175,6 +6175,7 @@ breakText Glyphs Glyfy
Gap 5 Mezera 5
@msg {_1}: they came in as the page's art {_1}: byly načteny jako kresba ze stránky
@msg objects that drew differently from the file's own page came in as its art: {_1} objekty, které se vykreslily jinak než vlastní stránka souboru, byly načteny jako kresba ze stránky: {_1}
@msg You must choose a side pattern. Musíte zvolit boční vzorek.
@msg invalid pattern tile choice neplatná volba dlaždice vzorku
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -6043,6 +6043,7 @@ breakText Glyphs Glyffer
Gap 5 Mellemrum 5
@msg {_1}: they came in as the page's art {_1}: de blev importeret som sidens grafik
@msg objects that drew differently from the file's own page came in as its art: {_1} objekter, der blev tegnet anderledes end filens egen side, blev importeret som sidens grafik: {_1}
@msg You must choose a side pattern. Du skal vælge et sidemønster.
@msg invalid pattern tile choice ugyldigt valg af mønsterflise
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -3912,7 +3912,7 @@ theme Appearance Erscheinungsbild
@msg Save for Web: the image is empty Für Web speichern: Das Bild ist leer
@msg Save writes {_1}, not {_2}: use document.export for other formats „Speichern“ schreibt {_1}, nicht {_2}: Verwenden Sie document.export für andere Formate
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it „Speichern“ schreibt {_1}, nicht {_2}: Verwenden Sie dafür file.saveAsTemplate
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 schreibt ältere .ai-Dateien; eine .ait-Vorlage ist immer PDF-kompatibel
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 schreibt ältere .ai-Dateien, keine .ait-Vorlagen
@msg Saved recovery data for {title} Wiederherstellungsdaten für {title} gespeichert
@msg Saved to User Defined: {_1} In „Benutzerdefiniert“ gespeichert: {_1}
@msg Saved {path} {path} gespeichert
@@ -5761,6 +5761,7 @@ breakText Glyphs Glyphen
Gap 5 Lücke 5
@msg {_1}: they came in as the page's art {_1}: sie wurden als Seitengrafik importiert
@msg objects that drew differently from the file's own page came in as its art: {_1} Objekte, die anders als die eigene Seite der Datei gezeichnet wurden, wurden als Seitengrafik importiert: {_1}
@msg You must choose a side pattern. Sie müssen ein Seitenmuster auswählen.
@msg invalid pattern tile choice ungültige Auswahl einer Musterkachel
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -2203,7 +2203,7 @@ axis Both Και τα δύο
@msg Save for Web: the image is empty Αποθήκευση για ιστό: η εικόνα είναι κενή
@msg Save writes {_1}, not {_2}: use document.export for other formats Η αποθήκευση γράφει {_1}, όχι {_2}: χρησιμοποιήστε το document.export για άλλες μορφές
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Η αποθήκευση γράφει {_1}, όχι {_2}: χρησιμοποιήστε το file.saveAsTemplate για να το γράψετε
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible Το aiVersion 7 γράφει αρχεία .ai παλαιού τύπου· ένα πρότυπο .ait είναι πάντα συμβατό με PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates Το aiVersion 7 γράφει αρχεία .ai παλαιού τύπου, όχι πρότυπα .ait
@msg Saved recovery data for {title} Αποθηκεύτηκαν δεδομένα ανάκτησης για το {title}
@msg Saved to User Defined: {_1} Αποθηκεύτηκε στις προσαρμοσμένες ρυθμίσεις: {_1}
@msg Saved {path} Αποθηκεύτηκε το {path}
@@ -6127,6 +6127,7 @@ breakText Glyphs Γλύφοι
Gap 5 Διάκενο 5
@msg {_1}: they came in as the page's art {_1}: εισήχθησαν ως γραφικά της σελίδας
@msg objects that drew differently from the file's own page came in as its art: {_1} τα αντικείμενα που σχεδιάστηκαν διαφορετικά από την ίδια τη σελίδα του αρχείου εισήχθησαν ως γραφικά της σελίδας: {_1}
@msg You must choose a side pattern. Πρέπει να επιλέξετε πλευρικό μοτίβο.
@msg invalid pattern tile choice μη έγκυρη επιλογή πλακιδίου μοτίβου
Can't render this file because it contains an unexpected character in line 163 and column 5.
+2 -1
View File
@@ -3997,7 +3997,7 @@ axis Both Ambos
@msg Save for Web: the image is empty Guardar para web: la imagen está vacía
@msg Save writes {_1}, not {_2}: use document.export for other formats Guardar escribe {_1}, no {_2}: usa document.export para otros formatos
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Guardar escribe {_1}, no {_2}: usa file.saveAsTemplate para escribirlo
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 escribe archivos .ai heredados; una plantilla .ait siempre es compatible con PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 escribe archivos .ai heredados, no plantillas .ait
@msg Saved recovery data for {title} Se guardaron los datos de recuperación de {title}
@msg Saved to User Defined: {_1} Se guardó en Definido por el usuario: {_1}
@msg Saved {path} Se guardó {path}
@@ -6117,6 +6117,7 @@ breakText Glyphs Glifos
Gap 5 Hueco 5
@msg {_1}: they came in as the page's art {_1}: se importaron como el arte de la página
@msg objects that drew differently from the file's own page came in as its art: {_1} los objetos que se dibujaban de forma distinta a la página del propio archivo se importaron como el arte de la página: {_1}
@msg You must choose a side pattern. Debe elegir un motivo lateral.
@msg invalid pattern tile choice selección de mosaico de motivo no válida
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -4219,7 +4219,7 @@ imageTrace Outline Ääriviiva
@msg Save for Web: the image is empty Tallenna verkkoon: kuva on tyhjä
@msg Save writes {_1}, not {_2}: use document.export for other formats Tallenna kirjoittaa muotoa {_1}, ei {_2}: käytä muille muodoille komentoa document.export
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Tallenna kirjoittaa muotoa {_1}, ei {_2}: kirjoita se komennolla file.saveAsTemplate
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 kirjoittaa vanhoja .ai-tiedostoja; .ait-malli on aina PDF-yhteensopiva
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 kirjoittaa vanhoja .ai-tiedostoja, ei .ait-malleja
@msg Saved recovery data for {title} Tallennettiin palautustiedot: {title}
@msg Saved to User Defined: {_1} Tallennettiin kohteeseen Käyttäjän määrittämä: {_1}
@msg Saved {path} Tallennettiin {path}
@@ -6205,6 +6205,7 @@ breakText Glyphs Merkit
Gap 5 Väli 5
@msg {_1}: they came in as the page's art {_1}: ne tuotiin sivun piirroksena
@msg objects that drew differently from the file's own page came in as its art: {_1} objektit, jotka piirtyivät eri tavoin kuin tiedoston oma sivu, tuotiin sivun piirroksena: {_1}
@msg You must choose a side pattern. Valitse sivukuvio.
@msg invalid pattern tile choice virheellinen kuviolaatan valinta
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -3987,7 +3987,7 @@ axis Both Les deux
@msg Save for Web: the image is empty Enregistrer pour le Web : l’image est vide
@msg Save writes {_1}, not {_2}: use document.export for other formats Enregistrer écrit du {_1}, pas du {_2} : utilisez document.export pour les autres formats
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Enregistrer écrit du {_1}, pas du {_2} : utilisez file.saveAsTemplate pour l’écrire
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 écrit des fichiers .ai hérités, alors qu’un modèle .ait est toujours compatible PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 écrit des fichiers .ai hérités, pas des modèles .ait
@msg Saved recovery data for {title} Données de récupération enregistrées pour {title}
@msg Saved to User Defined: {_1} Enregistré dans Défini par l’utilisateur : {_1}
@msg Saved {path} {path} enregistré
@@ -6170,6 +6170,7 @@ breakText Glyphs Glyphes
Gap 5 Écart 5
@msg {_1}: they came in as the page's art {_1} : ils ont été importés comme le dessin de la page
@msg objects that drew differently from the file's own page came in as its art: {_1} les objets dessinés différemment de la page du fichier lui-même ont été importés comme le dessin de la page : {_1}
@msg You must choose a side pattern. Vous devez choisir un motif latéral.
@msg invalid pattern tile choice choix de tuile de motif non valide
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -5104,7 +5104,7 @@ imageTrace Outline Körvonal
@msg Save for Web: the image is empty Mentés webre: a kép üres
@msg Save writes {_1}, not {_2}: use document.export for other formats a Mentés ezt írja: {_1}, ezt nem: {_2}; más formátumhoz használd a document.export parancsot
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it a Mentés ezt írja: {_1}, ezt nem: {_2}; ennek írásához használd a file.saveAsTemplate parancsot
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible az aiVersion 7 régi .ai fájlokat ír; egy .ait sablon mindig PDF-kompatibilis
@msg aiVersion 7 writes legacy .ai files, not .ait templates az aiVersion 7 régi .ai fájlokat ír, nem .ait sablonokat
@msg saved panel layout is invalid; reset the workspace first a mentett panelelrendezés érvénytelen; előbb állítsd vissza a munkaterületet
@msg Saved recovery data for {title} Helyreállítási adatok mentve: {title}
@msg Saved to User Defined: {_1} Mentve a felhasználóiak közé: {_1}
@@ -6159,6 +6159,7 @@ breakText Glyphs Glifák
Gap 5 Hézag 5
@msg {_1}: they came in as the page's art {_1}: az oldal rajzaként lettek importálva
@msg objects that drew differently from the file's own page came in as its art: {_1} a fájl saját oldalától eltérően rajzolt objektumok az oldal rajzaként lettek importálva: {_1}
@msg You must choose a side pattern. Válasszon oldalsó mintát.
@msg invalid pattern tile choice érvénytelen mintacsempe-választás
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -6043,6 +6043,7 @@ breakText Glyphs Glif
Gap 5 Jarak 5
@msg {_1}: they came in as the page's art {_1}: diimpor sebagai gambar halaman
@msg objects that drew differently from the file's own page came in as its art: {_1} objek yang tergambar berbeda dari halaman file itu sendiri diimpor sebagai gambar halaman: {_1}
@msg You must choose a side pattern. Anda harus memilih pola sisi.
@msg invalid pattern tile choice pilihan ubin pola tidak valid
Can't render this file because it contains an unexpected character in line 2214 and column 5.
+2 -1
View File
@@ -4039,7 +4039,7 @@ axis Both Entrambi
@msg Save for Web: the image is empty Salva per il web: l'immagine è vuota
@msg Save writes {_1}, not {_2}: use document.export for other formats Salva scrive {_1}, non {_2}: usa document.export per gli altri formati
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Salva scrive {_1}, non {_2}: usa file.saveAsTemplate per scriverlo
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 scrive file .ai tradizionali; un modello .ait è sempre compatibile PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 scrive file .ai tradizionali, non modelli .ait
@msg Saved recovery data for {title} Dati di recupero salvati per {title}
@msg Saved to User Defined: {_1} Salvato in Definito dall'utente: {_1}
@msg Saved {path} Salvato {path}
@@ -5795,6 +5795,7 @@ breakText Glyphs Glifi
Gap 5 Spazio 5
@msg {_1}: they came in as the page's art {_1}: sono stati importati come elementi grafici della pagina
@msg objects that drew differently from the file's own page came in as its art: {_1} gli oggetti disegnati in modo diverso dalla pagina del file stesso sono stati importati come elementi grafici della pagina: {_1}
@msg You must choose a side pattern. Devi scegliere un motivo laterale.
@msg invalid pattern tile choice scelta della tessera motivo non valida
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -4154,7 +4154,7 @@ swatch Bright Violet ビビッドバイオレット
@msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: この環境にはファイルシステムがありません (開くには dataBase64 を渡し、dataBase64 を受け取るにはパスを省略してください)
@msg Save writes {_1}, not {_2}: use document.export for other formats 保存できる形式は {_1} のみで、{_2} 形式では保存できません: ほかの形式には document.export を使用してください
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 保存できる形式は {_1} のみで、{_2} 形式では保存できません: この形式で保存するには file.saveAsTemplate を使用してください
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 は従来の .ai ファイルを書き出します。.ait テンプレートは常に PDF 互換です
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 は従来の .ai ファイルを書き出し、.ait テンプレートは書き出しません
@msg no changes since the last save 前回の保存以降、変更はありません
@msg unknown format `{f}` (Save writes {_1}) `{f}` は不明な形式です (保存できる形式: {_1})
@msg `svg` must be an object of SVG options (see document.formats) `svg` には SVG オプションのオブジェクトを指定してください (document.formats を参照)
@@ -5860,6 +5860,7 @@ breakText Glyphs 字形
Gap 5 間隔 5
@msg {_1}: they came in as the page's art {_1}: ページのアートとして読み込みました
@msg objects that drew differently from the file's own page came in as its art: {_1} ファイル自身のページと描画が異なるオブジェクトをページのアートとして読み込みました: {_1}
@msg You must choose a side pattern. 側面パターンを選択してください。
@msg invalid pattern tile choice パターンタイルの選択が無効です
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -5522,7 +5522,7 @@ imageTrace Outline კონტური
@msg its editing data is for a {w} × {h} pt page, the file's {pw} × {ph} pt page at {scale} მისი რედაქტირების მონაცემები {w} × {h} pt გვერდს ეკუთვნის: ეს ფაილის {pw} × {ph} pt გვერდია მასშტაბით {scale}
@msg no history to clear გასასუფთავებელი ისტორია არ არის
@msg {_1} files are written by file.saveAsTemplate {_1} ფაილებს წერს file.saveAsTemplate
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 წერს ძველი ფორმატის .ai ფაილებს; .ait შაბლონი ყოველთვის PDF-თან თავსებადია
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 წერს ძველი ფორმატის .ai ფაილებს და არა .ait შაბლონებს
@msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest ფაილის ცვლადების ბიბლიოთეკა მხოლოდ ნაწილობრივ იქნა წაკითხული (გამოტოვებული ჩანაწერები: {_1}): პანელი „ცვლადები“ დანარჩენს აჩვენებს
@msg the file's variable library couldn't be read: the Variables panel doesn't list it ფაილის ცვლადების ბიბლიოთეკის წაკითხვა ვერ მოხერხდა: პანელი „ცვლადები“ მას არ აჩვენებს
@msg a variable of unknown kind can't be bound to objects უცნობი სახის ცვლადის ობიექტებთან დაკავშირება შეუძლებელია
@@ -6163,6 +6163,7 @@ breakText Glyphs გლიფები
Gap 5 შუალედი 5
@msg {_1}: they came in as the page's art {_1}: იმპორტირებულია გვერდის გამოსახულების სახით
@msg objects that drew differently from the file's own page came in as its art: {_1} ობიექტები, რომლებიც ფაილის საკუთარი გვერდისგან განსხვავებულად იხატებოდა, იმპორტირებულია გვერდის გამოსახულების სახით: {_1}
@msg You must choose a side pattern. აირჩიეთ გვერდითი ნიმუში.
@msg invalid pattern tile choice ნიმუშის ფილა არასწორად არის არჩეული
Can't render this file because it is too large.
+2 -1
View File
@@ -4081,7 +4081,7 @@ theme Appearance 외관
@msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: 여기에는 파일 시스템이 없습니다(열려면 dataBase64를 전달하고, dataBase64를 얻으려면 경로를 생략하세요)
@msg Save writes {_1}, not {_2}: use document.export for other formats 저장은 {_2}이(가) 아닌 {_1}(으)로 기록합니다. 다른 형식은 document.export를 사용하세요
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 저장은 {_2}이(가) 아닌 {_1}(으)로 기록합니다. 이 형식으로 기록하려면 file.saveAsTemplate를 사용하세요
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7은(는) 레거시 .ai 파일을 기록합니다. .ait 템플릿은 항상 PDF 호환입니다
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7은(는) 레거시 .ai 파일을 기록하며 .ait 템플릿은 기록하지 않습니다
@msg no changes since the last save 마지막 저장 이후 변경 내용이 없습니다
@msg unknown format `{f}` (Save writes {_1}) 알 수 없는 형식 `{f}`(저장은 {_1}(으)로 기록)
@msg `svg` must be an object of SVG options (see document.formats) `svg`는 SVG 옵션 개체여야 합니다(document.formats 참조)
@@ -5756,6 +5756,7 @@ breakText Glyphs 글리프
Gap 5 간격 5
@msg {_1}: they came in as the page's art {_1}: 페이지의 아트로 가져왔습니다
@msg objects that drew differently from the file's own page came in as its art: {_1} 파일 자체 페이지와 다르게 그려진 오브젝트를 페이지의 아트로 가져왔습니다: {_1}
@msg You must choose a side pattern. 측면 패턴을 선택해야 합니다.
@msg invalid pattern tile choice 잘못된 패턴 타일 선택
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -6087,6 +6087,7 @@ breakText Glyphs Glyphs
Gap 5 Tussenruimte 5
@msg {_1}: they came in as the page's art {_1}: ze zijn geïmporteerd als pagina-afbeelding
@msg objects that drew differently from the file's own page came in as its art: {_1} objecten die anders werden getekend dan de eigen pagina van het bestand, zijn geïmporteerd als pagina-afbeelding: {_1}
@msg You must choose a side pattern. Kies een zijpatroon.
@msg invalid pattern tile choice ongeldige keuze voor patroontegel
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -4128,7 +4128,7 @@ imageTrace Outline Kontur
@msg Save for Web: the image is empty Zapisz dla Internetu: obraz jest pusty
@msg Save writes {_1}, not {_2}: use document.export for other formats Zapis tworzy {_1}, nie {_2}: dla innych formatów użyj document.export
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Zapis tworzy {_1}, nie {_2}: aby go zapisać, użyj file.saveAsTemplate
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 zapisuje starsze pliki .ai; szablon .ait jest zawsze zgodny z PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 zapisuje starsze pliki .ai, a nie szablony .ait
@msg Saved recovery data for {title} Zapisano dane odzyskiwania dla {title}
@msg Saved to User Defined: {_1} Zapisano w zdefiniowanych przez użytkownika: {_1}
@msg Saved {path} Zapisano {path}
@@ -6030,6 +6030,7 @@ breakText Glyphs Glify
Gap 5 Odstęp 5
@msg {_1}: they came in as the page's art {_1}: zaimportowano je jako grafikę strony
@msg objects that drew differently from the file's own page came in as its art: {_1} obiekty rysowane inaczej niż własna strona pliku zaimportowano jako grafikę strony: {_1}
@msg You must choose a side pattern. Musisz wybrać wzór boczny.
@msg invalid pattern tile choice nieprawidłowy wybór kafelka wzoru
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -3591,7 +3591,7 @@ axis Both Ambos
@msg Save for Web: the image is empty Salvar para Web: a imagem está vazia
@msg Save writes {_1}, not {_2}: use document.export for other formats Salvar grava {_1}, não {_2}: use document.export para outros formatos
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Salvar grava {_1}, não {_2}: use file.saveAsTemplate para gravá-lo
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 grava arquivos .ai legados; um modelo .ait é sempre compatível com PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 grava arquivos .ai legados, não modelos .ait
@msg Saved recovery data for {title} Dados de recuperação de {title} salvos
@msg Saved to User Defined: {_1} Salvo em Definido pelo usuário: {_1}
@msg Saved {path} {path} salvo
@@ -6093,6 +6093,7 @@ breakText Glyphs Glifos
Gap 5 Lacuna 5
@msg {_1}: they came in as the page's art {_1}: foram importados como arte da página
@msg objects that drew differently from the file's own page came in as its art: {_1} os objetos desenhados de forma diferente da própria página do arquivo foram importados como arte da página: {_1}
@msg You must choose a side pattern. Você deve escolher um padrão lateral.
@msg invalid pattern tile choice escolha inválida de ladrilho de padrão
Can't render this file because it contains an unexpected character in line 6 and column 47.
+2 -1
View File
@@ -4034,7 +4034,7 @@ axis Both Оба
@msg Save for Web: the image is empty Сохранить для web: изображение пусто
@msg Save writes {_1}, not {_2}: use document.export for other formats Сохранение записывает {_1}, а не {_2}: используйте document.export для других форматов
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Сохранение записывает {_1}, а не {_2}: чтобы записать его, используйте file.saveAsTemplate
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 записывает устаревшие файлы .ai; шаблон .ait всегда совместим с PDF
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 записывает устаревшие файлы .ai, а не шаблоны .ait
@msg Saved recovery data for {title} Сохранены данные восстановления для {title}
@msg Saved to User Defined: {_1} Сохранено в «Пользовательский»: {_1}
@msg Saved {path} Сохранено: {path}
@@ -6152,6 +6152,7 @@ breakText Glyphs Глифы
Gap 5 Зазор 5
@msg {_1}: they came in as the page's art {_1}: импортированы как графика страницы
@msg objects that drew differently from the file's own page came in as its art: {_1} объекты, которые отрисовывались иначе, чем собственная страница файла, импортированы как графика страницы: {_1}
@msg You must choose a side pattern. Выберите боковой узор.
@msg invalid pattern tile choice недопустимый выбор плитки узора
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2 -1
View File
@@ -3908,7 +3908,7 @@ axis Both Båda
@msg Save for Web: the image is empty Spara för webb: bilden är tom
@msg Save writes {_1}, not {_2}: use document.export for other formats Spara skriver {_1}, inte {_2}: använd document.export för andra format
@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Spara skriver {_1}, inte {_2}: använd file.saveAsTemplate för att skriva det
@msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 skriver äldre .ai-filer; en .ait-mall är alltid PDF-kompatibel
@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 skriver äldre .ai-filer, inte .ait-mallar
@msg Saved recovery data for {title} Sparade återställningsdata för {title}
@msg Saved to User Defined: {_1} Sparat i Användardefinierat: {_1}
@msg Saved {path} Sparade {path}
@@ -6227,6 +6227,7 @@ breakText Glyphs Glyfer
Gap 5 Mellanrum 5
@msg {_1}: they came in as the page's art {_1}: de importerades som sidans bild
@msg objects that drew differently from the file's own page came in as its art: {_1} objekt som ritades annorlunda än filens egen sida importerades som sidans bild: {_1}
@msg You must choose a side pattern. Du måste välja ett sidomönster.
@msg invalid pattern tile choice ogiltigt val av mönsterplatta
Can't render this file because it contains an unexpected character in line 5 and column 25.
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more