mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 01:10:54 +01:00
Merge upstream/main into cursor/properties-quick-actions-groups
Resolve docs conflicts in gaps.md, roadmap.md, target-app-parity.md and ui-parity.md: take main's Last reviewed banner, keep both history rows (newest first). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
077930d760
283 files changed
+22431
-1669
No files matched your search
Generated
+1
@@ -8670,6 +8670,7 @@ name = "vectorcraft-js"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-xml",
|
||||
"getrandom 0.4.3",
|
||||
"proptest",
|
||||
"unicode-properties",
|
||||
|
||||
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
|
||||
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
@@ -255,6 +257,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
|
||||
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
|
||||
|
||||
@@ -57,6 +57,37 @@ impl Document {
|
||||
pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p)))
|
||||
}
|
||||
|
||||
/// Which artboard in the document owns object bounds `b`: the artboard that holds its center,
|
||||
/// or the one it has the greatest overlap area with if its center lies outside all artboards.
|
||||
/// Bounds with no width or no height (a straight horizontal or vertical line) have no area, so
|
||||
/// for them the overlap is the length of the line on the artboard.
|
||||
pub fn artboard_for_bounds(&self, b: Rect) -> Option<usize> {
|
||||
let c = b.center();
|
||||
if let Some(i) = self.artboard_holding(c, false) {
|
||||
return Some(i);
|
||||
}
|
||||
let (flat_x, flat_y) = (b.x1 - b.x0 <= 1e-9, b.y1 - b.y0 <= 1e-9);
|
||||
let mut best: Option<(usize, f64)> = None;
|
||||
for (i, a) in self.artboards.iter().enumerate() {
|
||||
let r = a.rect;
|
||||
let w = b.x1.min(r.x1) - b.x0.max(r.x0);
|
||||
let h = b.y1.min(r.y1) - b.y0.max(r.y0);
|
||||
if w < 0.0 || h < 0.0 {
|
||||
continue;
|
||||
}
|
||||
let overlap = match (flat_x, flat_y) {
|
||||
(true, true) => 0.0,
|
||||
(true, false) => h,
|
||||
(false, true) => w,
|
||||
(false, false) => w * h,
|
||||
};
|
||||
if overlap > 1e-9 && best.is_none_or(|(_, max)| overlap > max + 1e-9) {
|
||||
best = Some((i, overlap));
|
||||
}
|
||||
}
|
||||
best.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// The art that moves with an artboard at `rect`: top-level objects (children of layers and
|
||||
/// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and
|
||||
/// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display ›
|
||||
@@ -89,6 +120,54 @@ impl Document {
|
||||
art
|
||||
}
|
||||
|
||||
/// The art that is copied when artboard `index` is duplicated or copied: objects wholly inside
|
||||
/// the artboard (with rounding tolerance), objects within its bleed rectangle, and artwork
|
||||
/// placed on/overlapping this artboard that belongs to it by center or primary overlap
|
||||
/// ([`Document::artboard_for_bounds`]).
|
||||
pub fn art_for_artboard_copy(&self, index: usize, locked_and_hidden: bool) -> Vec<NodeId> {
|
||||
let Some(rect) = self.artboards.get(index).map(|a| a.rect) else { return vec![] };
|
||||
let r = rect.inflate(1e-6, 1e-6);
|
||||
let on_copy = |b: Rect| -> bool {
|
||||
// 1. Wholly inside the artboard (edges included, with tolerance).
|
||||
if b.x0 >= r.x0 && b.y0 >= r.y0 && b.x1 <= r.x1 && b.y1 <= r.y1 {
|
||||
return true;
|
||||
}
|
||||
// 2. Within the artboard's bleed rectangle (if document setup specifies bleed).
|
||||
if self.setup.has_bleed() {
|
||||
let br = self.setup.bleed_rect(rect).inflate(1e-6, 1e-6);
|
||||
if b.x0 >= br.x0 && b.y0 >= br.y0 && b.x1 <= br.x1 && b.y1 <= br.y1 {
|
||||
return self.artboard_for_bounds(b).is_none_or(|owner| owner == index);
|
||||
}
|
||||
}
|
||||
// 3. Artwork that intersects this artboard and belongs to it (#4479).
|
||||
let inter_x0 = b.x0.max(r.x0);
|
||||
let inter_y0 = b.y0.max(r.y0);
|
||||
let inter_x1 = b.x1.min(r.x1);
|
||||
let inter_y1 = b.y1.min(r.y1);
|
||||
if inter_x1 < inter_x0 || inter_y1 < inter_y0 {
|
||||
return false;
|
||||
}
|
||||
self.artboard_for_bounds(b) == Some(index)
|
||||
};
|
||||
fn collect(n: &Node, s: &SymbolBoxes, on: &dyn Fn(Rect) -> bool, all: bool, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) {
|
||||
if c.is_layer() {
|
||||
collect(c, s, on, all, out);
|
||||
} else if let Some(b) = c.geometric_bounds_with(s)
|
||||
&& on(b)
|
||||
{
|
||||
out.push(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let symbols = self.symbol_boxes();
|
||||
let mut art = vec![];
|
||||
for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) {
|
||||
collect(l, &symbols, &on_copy, locked_and_hidden, &mut art);
|
||||
}
|
||||
art
|
||||
}
|
||||
|
||||
/// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers,
|
||||
/// hidden and locked ones and those on template layers included, whose visual bounds (symbol
|
||||
/// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip
|
||||
|
||||
@@ -435,6 +435,140 @@ fn art_on_artboard_tolerates_roundoff_at_each_edge() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.setup.bleed = [9.0; 4];
|
||||
let layer = d.layers[0].id;
|
||||
// An oversized background (250x250 centered on the 200x200 artboard, #4479).
|
||||
let bg = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(bg, shapes::rectangle(Rect::new(-25.0, -25.0, 225.0, 225.0)), Appearance::default_art())).unwrap();
|
||||
// A shape with 5pt bleed over the top-right corner.
|
||||
let bleed = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(bleed, shapes::rectangle(Rect::new(150.0, -5.0, 205.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
// A shape lying entirely in the bleed margin without touching the artboard itself (-8..-2 vs 0..200).
|
||||
let bleed_margin_only = d.alloc_id();
|
||||
d.insert(
|
||||
Some(layer),
|
||||
usize::MAX,
|
||||
Node::path(bleed_margin_only, shapes::rectangle(Rect::new(-8.0, 50.0, -2.0, 100.0)), Appearance::default_art()),
|
||||
)
|
||||
.unwrap();
|
||||
// A small shape hanging 20pt over the left edge (center outside, more than bleed).
|
||||
let hanging = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(hanging, shapes::rectangle(Rect::new(-20.0, 90.0, 10.0, 120.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
// A straight line hanging 60pt over the left edge (center outside, no area): it lies on the
|
||||
// artboard for 40pt, so it is copied as a thin rectangle there would be.
|
||||
let line = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(line, shapes::line(Point::new(-60.0, 150.0), Point::new(40.0, 150.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
// A shape completely outside the artboard.
|
||||
let outside = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(outside, shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
|
||||
// Standard art_on_artboard keeps strict containment: none of the overhanging shapes are on it.
|
||||
let strict_art = d.art_on_artboard(Rect::new(0.0, 0.0, 200.0, 200.0), false);
|
||||
assert!(!strict_art.contains(&bg), "strict art_on_artboard excludes oversized background");
|
||||
assert!(!strict_art.contains(&bleed), "strict art_on_artboard excludes bleed shape");
|
||||
assert!(!strict_art.contains(&bleed_margin_only), "strict art_on_artboard excludes bleed-margin-only shape");
|
||||
assert!(!strict_art.contains(&hanging), "strict art_on_artboard excludes hanging shape");
|
||||
assert!(!strict_art.contains(&outside), "strict art_on_artboard excludes outside shape");
|
||||
|
||||
// Copying the artboard takes the artwork touching this artboard that belongs to it, or within bleed.
|
||||
let copy_art = d.art_for_artboard_copy(0, false);
|
||||
assert!(copy_art.contains(&bg), "oversized background is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&bleed), "bleed shape is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&bleed_margin_only), "bleed-margin-only shape is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&hanging), "touching shape owned by artboard 0 is copied: {copy_art:?}");
|
||||
assert!(copy_art.contains(&line), "a line hanging over the edge is copied: {copy_art:?}");
|
||||
assert!(!copy_art.contains(&outside), "outside shape is not copied: {copy_art:?}");
|
||||
|
||||
// If Artboard 1 is added next to Artboard 0, art primarily on Artboard 1 is not copied with Artboard 0:
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(200.0, 0.0, 400.0, 200.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
});
|
||||
// Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1.
|
||||
let neighbor_art = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(neighbor_art, shapes::rectangle(Rect::new(190.0, 50.0, 300.0, 150.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
|
||||
let copy_art0 = d.art_for_artboard_copy(0, false);
|
||||
assert!(!copy_art0.contains(&neighbor_art), "art owned by neighboring Artboard 1 is not copied with Artboard 0");
|
||||
let copy_art1 = d.art_for_artboard_copy(1, false);
|
||||
assert!(copy_art1.contains(&neighbor_art), "art owned by Artboard 1 is copied with Artboard 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_for_bounds_edge_cases_and_tie_breaks() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
// Artboard 0: (0, 0, 100, 100)
|
||||
// Artboard 1: (200, 0, 300, 100)
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(200.0, 0.0, 300.0, 100.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
});
|
||||
|
||||
// 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most:
|
||||
// Bounds: (50, -100, 150, 50) -> Center: (100, -25) which is outside all artboards.
|
||||
// Overlap with Board 0: 50x50 = 2500; Board 1: 0.
|
||||
let b_center_outside = Rect::new(50.0, -100.0, 150.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_center_outside), Some(0));
|
||||
|
||||
// 2. Equal overlap on two boards (defined tie-break: the lower index, board 0):
|
||||
// Bounds: (50, -50, 250, 50) -> Center: (150, 0) outside all boards.
|
||||
// Overlap with Board 0: (50..100) x (0..50) = 2500; Board 1: (200..250) x (0..50) = 2500.
|
||||
let b_equal_overlap = Rect::new(50.0, -50.0, 250.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_equal_overlap), Some(0), "equal overlap picks lower index");
|
||||
|
||||
// 3. No overlap at all: returns None.
|
||||
let b_no_overlap = Rect::new(500.0, 500.0, 600.0, 600.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_no_overlap), None);
|
||||
|
||||
// 4. Rotated object bounds (bounds, not the inner geometry):
|
||||
// A 40x40 square rotated 45 deg centered at (50, 50) has bounding box ~56.57x56.57.
|
||||
let b_rotated_bounds = Rect::new(50.0 - 28.28, 50.0 - 28.28, 50.0 + 28.28, 50.0 + 28.28);
|
||||
assert_eq!(d.artboard_for_bounds(b_rotated_bounds), Some(0));
|
||||
|
||||
// 5. Zero-size bounds (a point):
|
||||
// On board 0:
|
||||
let b_zero_on_board = Rect::new(50.0, 50.0, 50.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_zero_on_board), Some(0));
|
||||
// Outside all boards:
|
||||
let b_zero_outside = Rect::new(150.0, 50.0, 150.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_zero_outside), None);
|
||||
|
||||
// 6. Straight lines whose center is outside every board: owned by the board they lie on most,
|
||||
// as a rectangle of any thickness would be (they have no area to compare).
|
||||
// Horizontal, from x = -100 to 50 on board 0: center (-25, 50).
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.0)), Some(0));
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.1)), Some(0), "the same as a thin rectangle");
|
||||
// Vertical, from y = -100 to 50 on board 1: center (250, -25).
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(250.0, -100.0, 250.0, 50.0)), Some(1));
|
||||
// Below both boards.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 120.0, 260.0, 120.0)), None);
|
||||
// Across the gap between the boards, 20 pt on board 0 and 60 on board 1.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 50.0, 260.0, 50.0)), Some(1), "center (170, 50) in the gap: board 1 holds more of it");
|
||||
// Only touching a board's corner from outside: no overlap.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 0.0, 0.0, 0.0)), None);
|
||||
}
|
||||
|
||||
/// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one
|
||||
/// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with
|
||||
/// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one.
|
||||
|
||||
@@ -196,6 +196,15 @@ impl Unit {
|
||||
}
|
||||
parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
|
||||
/// number that looks like a grouped integer, even when it is part of an expression.
|
||||
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
|
||||
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
|
||||
return None;
|
||||
}
|
||||
self.parse(&decimal_point(text))
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
pub const fn key(self) -> &'static str {
|
||||
@@ -397,6 +406,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
|
||||
/// read a percentage's number without its percent sign.
|
||||
fn thousands_operand(operand: &str) -> bool {
|
||||
let operand = operand.trim();
|
||||
if let Some((picas, points)) = operand.split_once('p')
|
||||
&& !points.trim().is_empty()
|
||||
&& points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b','))
|
||||
{
|
||||
return thousands(picas) || thousands(points);
|
||||
}
|
||||
thousands(operand.strip_suffix('%').unwrap_or(operand))
|
||||
}
|
||||
|
||||
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
|
||||
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
|
||||
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
|
||||
|
||||
@@ -97,6 +97,7 @@ mod style;
|
||||
pub use style::styled_node;
|
||||
pub mod stylelib;
|
||||
mod svgfilter;
|
||||
pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES;
|
||||
mod swatch;
|
||||
pub mod swatchlib;
|
||||
pub(crate) mod symboledit;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
|
||||
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
|
||||
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
|
||||
//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives
|
||||
//! it in each unit of Preferences › Units › East Asian Type
|
||||
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
|
||||
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
|
||||
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
|
||||
@@ -10,7 +10,7 @@
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
"{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
@@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(CONVERT, "missing `value`"));
|
||||
};
|
||||
let pt = match v {
|
||||
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
|
||||
Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s),
|
||||
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_read_as_number_fields_read_them() {
|
||||
fn values_accept_units_arithmetic_and_decimal_commas() {
|
||||
let mut s = session();
|
||||
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
|
||||
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
|
||||
@@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
|
||||
// Each number of a sum reads its own separator.
|
||||
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
|
||||
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25));
|
||||
assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5));
|
||||
assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
// x, X and × multiply as * does, and each counts toward the 128 signs.
|
||||
@@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thousands_comma_in_an_arithmetic_operand_is_refused() {
|
||||
let mut s = session();
|
||||
for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] {
|
||||
let result = s.execute("addon.units.convert", &json!({"value": value}));
|
||||
assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_the_commands_do_not_take_are_refused() {
|
||||
let s = session();
|
||||
|
||||
@@ -562,16 +562,30 @@ fn mode_converter(mode: ColorMode, intent: Option<Intent>, grays: Grays) -> impl
|
||||
}
|
||||
|
||||
/// The name and color of each global swatch of `d`, for [`mode_color`].
|
||||
fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> {
|
||||
d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect()
|
||||
fn global_bases(d: &vectorcraft_doc::Document) -> BTreeMap<String, Color> {
|
||||
let mut first = BTreeMap::new();
|
||||
for w in d.swatches_iter() {
|
||||
// An ineligible first record still shadows a later global solid of the same name.
|
||||
first.entry(w.name.as_str()).or_insert(w);
|
||||
}
|
||||
first
|
||||
.into_values()
|
||||
.filter_map(|w| {
|
||||
if !w.global {
|
||||
return None;
|
||||
}
|
||||
let Paint::Solid { color, swatch: None, .. } = &w.paint else { return None };
|
||||
Some((w.name.clone(), d.linked_color(*color, w.spot)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in
|
||||
/// `bases` (already converted) is that swatch's color at its tint; any other color goes through
|
||||
/// `conv` ([`mode_converter`]).
|
||||
fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color {
|
||||
match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
|
||||
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
|
||||
fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap<String, Color>, conv: &dyn Fn(&Color) -> Color) -> Color {
|
||||
match link.and_then(|(name, tint)| Some((bases.get(name)?, tint))) {
|
||||
Some((base, tint)) if tint < 1.0 => base.tinted(tint),
|
||||
_ => conv(col),
|
||||
}
|
||||
}
|
||||
@@ -685,8 +699,8 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
|
||||
vectorcraft_brush::store(d, &brushes);
|
||||
}
|
||||
// This pass gives tint swatches their converted swatch's color at their tint; the passes above already did the same for the art's tints.
|
||||
d.map_solid_paints(&mut |c, link, tint| match bases.iter().find(|(n, _)| Some(n) == link.as_ref()) {
|
||||
Some((_, base)) if *tint < 1.0 => {
|
||||
d.map_solid_paints(&mut |c, link, tint| match link.as_ref().and_then(|name| bases.get(name)) {
|
||||
Some(base) if *tint < 1.0 => {
|
||||
*c = base.tinted(*tint);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec<u8> {
|
||||
pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "view.proofSetup.save";
|
||||
let (path, named) = file_path(s, p, C)?;
|
||||
let mut setup = proof::view().setup;
|
||||
setup_params(p, &mut setup, C)?;
|
||||
check_device(&setup.target).map_err(|e| bad(C, e))?;
|
||||
// A file `view.proofSetup.load` would refuse is not written (a device with a very long name).
|
||||
let bytes = encode(&setup);
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let (setup, bytes) = encode_options(p, &path)?;
|
||||
if named
|
||||
&& let Some(dir) = std::path::Path::new(&path).parent()
|
||||
&& !dir.is_dir()
|
||||
@@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Object(r))
|
||||
}
|
||||
|
||||
/// Serialize the Customize dialog's draft without committing it or writing a path.
|
||||
pub fn draft_bytes(p: &Value) -> Result<Vec<u8>> {
|
||||
encode_options(p, "Proof Setup").map(|(_, bytes)| bytes)
|
||||
}
|
||||
|
||||
fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec<u8>)> {
|
||||
const C: &str = "view.proofSetup.save";
|
||||
let mut setup = proof::view().setup;
|
||||
setup_params(p, &mut setup, C)?;
|
||||
check_device(&setup.target).map_err(|e| bad(C, e))?;
|
||||
let bytes = encode(&setup);
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
Ok((setup, bytes))
|
||||
}
|
||||
|
||||
/// The file `p` names for `cmd` and the usable proof setup in it.
|
||||
fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> {
|
||||
let (path, _) = file_path(s, p, cmd)?;
|
||||
// One byte past the limit shows a file over it, which is not read further.
|
||||
let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?;
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let setup = checked_setup(&bytes, &path, cmd)?;
|
||||
Ok((path, setup))
|
||||
}
|
||||
|
||||
/// Read a picked proof setup's validated settings without applying them to the view.
|
||||
pub fn draft_fields(bytes: &[u8], name: &str) -> Result<Value> {
|
||||
let setup = checked_setup(bytes, name, "view.proofSetup.read")?;
|
||||
Ok(Value::Object(setup_json(&setup)))
|
||||
}
|
||||
|
||||
fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result<ProofSetup> {
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
|
||||
check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
|
||||
Ok(setup)
|
||||
}
|
||||
|
||||
pub(super) fn read(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (path, setup) = read_setup(s, p, "view.proofSetup.read")?;
|
||||
let mut r = setup_json(&setup);
|
||||
|
||||
@@ -27,7 +27,7 @@ pub const EXTS: &[&str] = &["vccomposite"];
|
||||
const EXPORT: &str = "type.compositeFonts.export";
|
||||
|
||||
/// The largest file Import reads, in bytes.
|
||||
const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
pub const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
|
||||
/// The keys a part may give.
|
||||
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
|
||||
@@ -349,7 +349,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let too_large = || bad(C, "the file is larger than 4 MB");
|
||||
let bytes = match given {
|
||||
(Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?,
|
||||
(None, Some(text), None) => text.as_bytes().to_vec(),
|
||||
(None, Some(text), None) => {
|
||||
if text.len() > MAX_FILE_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
(None, None, Some(b64)) => {
|
||||
if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 {
|
||||
return Err(too_large());
|
||||
|
||||
@@ -27,6 +27,27 @@ fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Inline and encoded files share the same raw byte limit; rejection changes no fonts or history.
|
||||
#[test]
|
||||
fn import_file_byte_boundaries_preserve_the_document_on_refusal() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("Existing")]})).unwrap();
|
||||
let before = steps(&s);
|
||||
let large = " ".repeat(super::MAX_FILE_BYTES + 1);
|
||||
for params in [json!({"data": large}), json!({"dataBase64": vectorcraft_format::base64_encode(large.as_bytes())})] {
|
||||
let error = s.execute("type.compositeFonts.import", ¶ms).unwrap_err();
|
||||
assert!(error.to_string().contains("the file is larger than 4 MB"), "{error}");
|
||||
assert_eq!(names(&s), ["Existing"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
let mut exact = json!({"compositeFonts": [font("Imported")]}).to_string();
|
||||
exact.extend(std::iter::repeat_n(' ', super::MAX_FILE_BYTES - exact.len()));
|
||||
let imported = s.execute("type.compositeFonts.import", &json!({"data": exact, "apply": false})).unwrap();
|
||||
assert_eq!(imported["fonts"][0]["name"], "Imported");
|
||||
assert_eq!(names(&s), ["Existing"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
|
||||
@@ -284,7 +284,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Metadata Template…",
|
||||
[],
|
||||
None,
|
||||
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
|
||||
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
|
||||
has_doc,
|
||||
super::fileinfo::apply_template
|
||||
),
|
||||
|
||||
@@ -815,6 +815,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
turned.recost_paints();
|
||||
st.history.redo.push(turned);
|
||||
st.history.trim();
|
||||
st.history_restores += 1;
|
||||
st.revision += 1;
|
||||
st.selection.prune(&st.doc);
|
||||
// Guides locked and slices locked or hidden since the step was made stay deselected.
|
||||
@@ -852,6 +853,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
turned.recost_paints();
|
||||
st.history.undo.push(turned);
|
||||
st.history.trim();
|
||||
st.history_restores += 1;
|
||||
st.revision += 1;
|
||||
st.selection.prune(&st.doc);
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
|
||||
@@ -213,7 +213,7 @@ enum Merge {
|
||||
Append,
|
||||
}
|
||||
|
||||
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
|
||||
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`.
|
||||
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mode = match text_param(p, "mode", APPLY)? {
|
||||
Some("replace") => Merge::Replace,
|
||||
@@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
|
||||
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
|
||||
/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes.
|
||||
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
|
||||
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
|
||||
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", APPLY)?];
|
||||
// At most one byte past the limit is read, so a huge file is never read whole.
|
||||
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
|
||||
let bytes = match given {
|
||||
[Some(path), None, None] => read(path)?,
|
||||
[None, Some(name), None] => {
|
||||
[Some(path), None, None, None] => read(path)?,
|
||||
[None, Some(name), None, None] => {
|
||||
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
|
||||
let mut path = template_path(dir, name, APPLY)?;
|
||||
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
|
||||
@@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
|
||||
// The app's own folder: no root applies.
|
||||
crate::file_access::unconfined(|| read(&path))?
|
||||
}
|
||||
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
|
||||
[None, None, Some(data)] => data.as_bytes().to_vec(),
|
||||
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
|
||||
[None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
|
||||
[None, None, Some(data), None] => data.as_bytes().to_vec(),
|
||||
[None, None, None, Some(data)] => {
|
||||
if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 {
|
||||
return Err(too_big(APPLY));
|
||||
}
|
||||
vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))?
|
||||
}
|
||||
_ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > MAX_TEMPLATE_FILE {
|
||||
return Err(too_big(APPLY));
|
||||
|
||||
@@ -124,6 +124,17 @@ impl StopOwner {
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing paints affected by an edit from the Gradient panel.
|
||||
#[derive(PartialEq)]
|
||||
pub struct GradientEditPaints(Vec<EditedPaint>);
|
||||
|
||||
#[derive(PartialEq)]
|
||||
struct EditedPaint {
|
||||
id: NodeId,
|
||||
item: Option<usize>,
|
||||
paints: Vec<Paint>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not
|
||||
/// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it
|
||||
@@ -136,6 +147,36 @@ impl Session {
|
||||
.is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty()))
|
||||
}
|
||||
|
||||
/// Snapshot the paints a gradient edit without explicit targets would write, by object and
|
||||
/// appearance item. Text without an item has one paint per run. The proxy can display just
|
||||
/// the first paint when an edit goes to several objects or text runs.
|
||||
pub fn gradient_edit_paints(&self, stroke: bool) -> Result<GradientEditPaints> {
|
||||
const CMD: &str = "paint.editGradient";
|
||||
let p = json!({ "stroke": stroke });
|
||||
if super::paint::for_tool(self, &p, stroke) {
|
||||
return Ok(GradientEditPaints(Vec::new()));
|
||||
}
|
||||
let doc = &self.doc()?.doc;
|
||||
let item = item_target(self, &p, CMD)?.of_kind(self, !stroke);
|
||||
let ids = item.targets_for(self, &p, !stroke)?;
|
||||
let ids = super::appearance::drop_design_art_rows(self, ids, item, !stroke, CMD)?;
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for (id, item) in ids.iter().copied().zip(item.per_target(self, &ids)) {
|
||||
let (Some(node), Some(item)) = (doc.node(id), item) else { continue };
|
||||
let index = item.resolve(&node.appearance, !stroke, CMD)?;
|
||||
let (item, paints) = if index.is_none()
|
||||
&& let NodeKind::Text(text) = &node.kind
|
||||
{
|
||||
(None, text.runs.iter().map(|run| if stroke { run.style.stroke.clone() } else { run.style.fill.clone() }).collect())
|
||||
} else {
|
||||
let item = index.or_else(|| node.appearance.items.iter().rposition(|row| row.is_fill() != stroke));
|
||||
(item, node.appearance.paint_at(index, !stroke).cloned().into_iter().collect())
|
||||
};
|
||||
out.push(EditedPaint { id, item, paints });
|
||||
}
|
||||
Ok(GradientEditPaints(out))
|
||||
}
|
||||
|
||||
/// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on
|
||||
/// is still the one behind the active proxy. Callers check it against the stop count (an undo
|
||||
/// can remove stops).
|
||||
|
||||
@@ -76,6 +76,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
cmd!(
|
||||
"links.replaceEmbedded",
|
||||
"Replace Image",
|
||||
[],
|
||||
None,
|
||||
"{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}",
|
||||
has_doc,
|
||||
replace_embedded
|
||||
),
|
||||
cmd!(
|
||||
query "links.list",
|
||||
"Links",
|
||||
@@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement.
|
||||
fn replace_embedded(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.replaceEmbedded";
|
||||
let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?;
|
||||
let doc = &s.doc()?.doc;
|
||||
let mut seen = BTreeSet::new();
|
||||
for id in &ids {
|
||||
if !seen.insert(*id) {
|
||||
return Err(bad(C, format!("image {} is listed twice", id.0)));
|
||||
}
|
||||
if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) {
|
||||
return Err(bad(C, format!("object {} is not an image", id.0)));
|
||||
}
|
||||
}
|
||||
let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?;
|
||||
let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?;
|
||||
let mut img = fileio::raster_image(&bytes)?;
|
||||
img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?;
|
||||
s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?;
|
||||
Ok(json!({ "replaced": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels
|
||||
/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the
|
||||
/// transform still gives it its old size. Its Placement Options do not apply. The result is what
|
||||
@@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it:
|
||||
/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a
|
||||
/// distort maps a path's.
|
||||
fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo {
|
||||
fn refill_distorted(
|
||||
n: &mut Node,
|
||||
old_clip: Option<&FileClip>,
|
||||
link: Option<&LinkInfo>,
|
||||
img: &RasterImage,
|
||||
held: Option<(&PathData, FillRule)>,
|
||||
) -> ClipTo {
|
||||
let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule)));
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned());
|
||||
}
|
||||
let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule)));
|
||||
placed_clip_to(old.as_ref(), None, file, held)
|
||||
@@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
|
||||
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
|
||||
/// show that content.
|
||||
fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
install_with(d, ids, read, force, also, false)
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
install_with(d, ids, Some(&link), img, force, also, false)
|
||||
}
|
||||
|
||||
/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it
|
||||
@@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo {
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`].
|
||||
/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes
|
||||
/// through [`unembed_clip`].
|
||||
fn install_with(
|
||||
d: &mut Document,
|
||||
ids: &[NodeId],
|
||||
(link, img): FileRead,
|
||||
link: Option<&LinkInfo>,
|
||||
img: RasterImage,
|
||||
force: Option<Preserve>,
|
||||
also: Option<(&str, &str)>,
|
||||
unembed: bool,
|
||||
@@ -1341,7 +1380,7 @@ fn install_with(
|
||||
NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held);
|
||||
let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held);
|
||||
return (n, keep(clip, held.is_some()));
|
||||
}
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
@@ -1353,7 +1392,7 @@ fn install_with(
|
||||
};
|
||||
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
|
||||
clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some());
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
|
||||
}
|
||||
(n, clip)
|
||||
};
|
||||
@@ -1367,7 +1406,7 @@ fn install_with(
|
||||
};
|
||||
let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule));
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
|
||||
let clip = refill_distorted(n, old_clip.as_ref(), link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
|
||||
clips.push((*id, keep(clip, held.is_some())));
|
||||
}
|
||||
continue;
|
||||
@@ -1384,12 +1423,12 @@ fn install_with(
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
{
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
|
||||
}
|
||||
}
|
||||
// A DCS file's spot plates print on spot swatches of their inks.
|
||||
super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates());
|
||||
store_image(d, &img.key, img.blob, true);
|
||||
store_image(d, &img.key, img.blob, link.is_some());
|
||||
clips.into_iter().try_for_each(|(id, clip)| match clip {
|
||||
ClipTo::Keep => Ok(()),
|
||||
ClipTo::Path(path) => clip_image_to(d, id, path),
|
||||
@@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Read before writing: pixels that can't be read leave no file behind.
|
||||
let img = linked_image(&bytes, Some(&path))?;
|
||||
write_file(&path, &bytes)?;
|
||||
let read = (link_info(&path, &bytes), img);
|
||||
let link = link_info(&path, &bytes);
|
||||
drop(doc);
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?;
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?;
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
@@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
|
||||
drop(doc);
|
||||
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
|
||||
let edited = s.edit("Unembed", |d, _| {
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))
|
||||
editing_brush_art(d, |d| {
|
||||
reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true))
|
||||
})
|
||||
});
|
||||
if let Err(e) = edited {
|
||||
remove_written(&written);
|
||||
|
||||
@@ -406,6 +406,13 @@ fn edit_blends(s: &mut Session, label: &str, f: impl Fn(&mut Vec<Arc<Node>>, &mu
|
||||
ok()
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Whether Blend Options would operate on selected artwork rather than new-blend defaults.
|
||||
pub fn has_selected_blend(&self) -> bool {
|
||||
super::common::any_selected_of(self, is_blend, |_| true)
|
||||
}
|
||||
}
|
||||
|
||||
/// The first selected blend: its id, spec and key ids.
|
||||
fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec<NodeId>)> {
|
||||
let b = *selected_of(s, is_blend).first()?;
|
||||
|
||||
@@ -8,6 +8,7 @@ use vectorcraft_geom::{Rect, Vec2};
|
||||
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, switch_or};
|
||||
use crate::{Clipboard, EngineError};
|
||||
|
||||
/// The panel command specifications registered with the engine.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("artboard.reorder", "Move Artboard Up/Down", [], None, "{index, to} change an artboard's number", has_doc, artboard_reorder),
|
||||
@@ -16,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art fully inside each when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}",
|
||||
"{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art on each (fully inside, within its bleed or centered/overlapping on it, #4479) when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}",
|
||||
has_doc,
|
||||
artboard_duplicate
|
||||
),
|
||||
@@ -25,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art fully inside each when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art on each (fully inside, within its bleed or centered/overlapping on it, #4479) when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.copy")?;
|
||||
@@ -37,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} artboard.copy, then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.cut")?;
|
||||
@@ -288,16 +289,19 @@ pub(crate) fn locked_and_hidden(s: &mut Session, p: &Value, art: bool, cmd: &str
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
/// The art that goes with artboard `i` when `art`: the objects fully inside it (locked and hidden
|
||||
/// ones only when `all`), in paint order. With `moving` (a move or a cut), the art also on another
|
||||
/// locked artboard stays unless `all` ([`vectorcraft_doc::Document::art_moving_with`]); a copy
|
||||
/// takes it.
|
||||
/// The art that goes with artboard `i` when `art`: when copying, the art on the artboard (fully
|
||||
/// inside, within its bleed or centered/overlapping on it, #4479); with `moving` (a move or a cut),
|
||||
/// the objects fully inside it (locked and hidden ones only when `all`), in paint order. With
|
||||
/// `moving`, the art also on another locked artboard stays unless `all`
|
||||
/// ([`vectorcraft_doc::Document::art_moving_with`]); a copy takes it.
|
||||
pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving: bool) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let rect = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
|
||||
if i >= d.artboards.len() {
|
||||
return Err(EngineError::Other("no such artboard".into()));
|
||||
}
|
||||
Ok(match (art, moving) {
|
||||
(false, _) => vec![],
|
||||
(true, false) => d.art_on_artboard(rect, all),
|
||||
(true, false) => d.art_for_artboard_copy(i, all),
|
||||
(true, true) => d.art_moving_with(i, all),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -177,6 +177,13 @@ fn opened_document_art(
|
||||
super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false);
|
||||
}
|
||||
l.doc.drop_edit_modes();
|
||||
// The native file does not store type's layout bounds. Measure them before cropping or
|
||||
// copying the art, so the placed group keeps the positions of aligned point type.
|
||||
for warning in crate::Session::refresh_text_bounds(&mut l.doc) {
|
||||
if !l.warnings.contains(&warning) {
|
||||
l.warnings.push(warning);
|
||||
}
|
||||
}
|
||||
let n = l.doc.artboards.len();
|
||||
let board = (page as usize).checked_sub(1).and_then(|i| l.doc.artboards.get(i)).map(|a| a.rect);
|
||||
let artboards = if n == 1 { "artboard" } else { "artboards" };
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
//! editing one adds a copy to the document under the default's name, and from then on that copy is
|
||||
//! the filter of that name. Deleting the copy lists the default again.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, Document, SvgFilter};
|
||||
use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter};
|
||||
@@ -17,7 +19,7 @@ use super::fileio::{absolute_path, read_file_head};
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, text_param};
|
||||
|
||||
/// The largest SVG file Import SVG Filter reads.
|
||||
const MAX_IMPORT_BYTES: usize = 16 << 20;
|
||||
pub const MAX_IMPORT_BYTES: usize = 16 << 20;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -53,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import SVG Filter…",
|
||||
[],
|
||||
None,
|
||||
"{path?|svg?} add the <filter> elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters) or of SVG text to the document's SVG filters, as one undo step; a filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}",
|
||||
"{path?|svg?|dataBase64?} add the <filter> elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters), SVG text or base64-encoded file bytes to the document's SVG filters, as one undo step; file bytes keep their UTF-8, BOM-marked UTF-16 or declared ISO 8859-1 encoding. A filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}",
|
||||
has_doc,
|
||||
import
|
||||
),
|
||||
@@ -197,13 +199,19 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "filters": filters_json(&s.doc()?.doc) }))
|
||||
}
|
||||
|
||||
/// The bytes of `p`'s `path` (an SVG file, read up to [`MAX_IMPORT_BYTES`]) or `svg`.
|
||||
fn import_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> {
|
||||
let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?) {
|
||||
/// The bytes of `p`'s `path`, `svg` text or `dataBase64`, up to [`MAX_IMPORT_BYTES`]. Inline SVG borrows its UTF-8 bytes.
|
||||
fn import_bytes<'a>(p: &'a Value, cmd: &str) -> Result<Cow<'a, [u8]>> {
|
||||
let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?, text_param(p, "dataBase64", cmd)?) {
|
||||
// One byte past the cap is enough to refuse the file below.
|
||||
(Some(path), _) => read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?,
|
||||
(None, Some(svg)) => svg.as_bytes().to_vec(),
|
||||
_ => return Err(bad(cmd, "give `path`, an SVG file, or `svg`, SVG text")),
|
||||
(Some(path), _, _) => Cow::Owned(read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?),
|
||||
(None, Some(svg), _) => Cow::Borrowed(svg.as_bytes()),
|
||||
(None, None, Some(encoded)) => {
|
||||
if vectorcraft_format::base64_decoded_len(encoded) > MAX_IMPORT_BYTES as u64 {
|
||||
return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes")));
|
||||
}
|
||||
Cow::Owned(vectorcraft_format::base64_decode(encoded).ok_or_else(|| bad(cmd, "bad dataBase64"))?)
|
||||
}
|
||||
_ => return Err(bad(cmd, "give `path`, an SVG file, `svg`, SVG text, or `dataBase64`, file bytes")),
|
||||
};
|
||||
if bytes.len() > MAX_IMPORT_BYTES {
|
||||
return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes")));
|
||||
|
||||
@@ -876,11 +876,17 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result<Value> {
|
||||
/// result is that command's, with `format` set to `csv` or `xml`.
|
||||
fn variable_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.import";
|
||||
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
|
||||
let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
let (name, input) = if let Some(path) = str_param(p, "path") {
|
||||
(path, json!({"path": path}))
|
||||
} else {
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `path` or `name` with `dataBase64`"))?;
|
||||
let bytes = str_param(p, "dataBase64").ok_or_else(|| bad(C, "missing `dataBase64`"))?;
|
||||
(name, json!({"dataBase64": bytes}))
|
||||
};
|
||||
let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
|
||||
let (format, mut out) = match ext.as_deref() {
|
||||
Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?),
|
||||
Some("xml") => ("xml", load_library(s, &json!({"path": path}))?),
|
||||
Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &input)?),
|
||||
Some("xml") => ("xml", load_library(s, &input)?),
|
||||
_ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")),
|
||||
};
|
||||
out["format"] = json!(format);
|
||||
@@ -1084,7 +1090,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import…",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes)} import a data source chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`",
|
||||
has_doc,
|
||||
variable_import
|
||||
),
|
||||
|
||||
@@ -74,6 +74,9 @@ pub struct DocState {
|
||||
/// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not
|
||||
/// change it, and a batch that fails puts it back with the document.
|
||||
pub reverts: u64,
|
||||
/// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects
|
||||
/// across that boundary.
|
||||
pub history_restores: u64,
|
||||
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
|
||||
/// the UI opens it in a floating window of its own.
|
||||
pub opened_as_tab: bool,
|
||||
@@ -419,6 +422,7 @@ impl DocState {
|
||||
recalled_selection: RecalledSelection::default(),
|
||||
uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
reverts: 0,
|
||||
history_restores: 0,
|
||||
opened_as_tab: true,
|
||||
mask_view: None,
|
||||
spelling_ignored: Default::default(),
|
||||
|
||||
@@ -30,7 +30,7 @@ pub use cmd::clipboard::{Clipboard, SourceLayer};
|
||||
pub use cmd::create::constrain_click;
|
||||
pub use cmd::distortcmds::{perspective_click, width_point_pair};
|
||||
pub use cmd::flare::flare_settings;
|
||||
pub use cmd::gradient::StopOwner;
|
||||
pub use cmd::gradient::{GradientEditPaints, StopOwner};
|
||||
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
|
||||
pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::auto_simplify_level;
|
||||
|
||||
@@ -1684,8 +1684,12 @@ fn millis(t: Option<std::time::SystemTime>) -> Data {
|
||||
|
||||
/// One host function of `__vcFiles`, counted and charged as a host call of the run `link` holds.
|
||||
fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem {
|
||||
HostItem::Function(call_function(link, f))
|
||||
}
|
||||
|
||||
fn call_function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> vectorcraft_js::HostFunction {
|
||||
let l = link.clone();
|
||||
HostItem::Function(Rc::new(move |a| {
|
||||
Rc::new(move |a| {
|
||||
let h = super::current(&l)?;
|
||||
bump(&h.counts.file_calls);
|
||||
let r = f(&h, &a);
|
||||
@@ -1693,7 +1697,7 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) ->
|
||||
let r = r?;
|
||||
h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?;
|
||||
Ok(r)
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// `Ok(true)`, or `{error}` for a failure.
|
||||
@@ -1875,6 +1879,228 @@ fn copy(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
Ok(done(r.map_err(|_| WRITE_FAILED)))
|
||||
}
|
||||
|
||||
/// Is `path` an XMP sidecar file, by its `.xmp` extension in any case?
|
||||
fn is_sidecar(path: &str) -> bool {
|
||||
Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp"))
|
||||
}
|
||||
|
||||
/// The text of a sidecar's bytes and its character form as `XMPFile.getPacketInfo` gives it: 0 for
|
||||
/// UTF-8, 2 for UTF-16 big-endian and 3 for UTF-16 little-endian, by its byte order mark.
|
||||
fn sidecar_text(bytes: &[u8]) -> Option<(String, u32)> {
|
||||
let utf16 = |rest: &[u8], big: bool| {
|
||||
let units = rest.as_chunks::<2>().0.iter().map(|&pair| if big { u16::from_be_bytes(pair) } else { u16::from_le_bytes(pair) });
|
||||
rest.len().is_multiple_of(2).then(|| char::decode_utf16(units).collect::<Result<String, _>>().ok()).flatten()
|
||||
};
|
||||
match bytes {
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => std::str::from_utf8(rest).ok().map(|t| (t.to_string(), 0)),
|
||||
[0xFE, 0xFF, rest @ ..] => utf16(rest, true).map(|t| (t, 2)),
|
||||
[0xFF, 0xFE, rest @ ..] => utf16(rest, false).map(|t| (t, 3)),
|
||||
_ => std::str::from_utf8(bytes).ok().map(|t| (t.to_string(), 0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `xmpOpen(path, update, scan)`: the XMP packet of the file at `path` for `XMPFile`, read under
|
||||
/// the rules for reading; with `update`, a file that can take a packet must also be one the run may write. A `.xmp` file
|
||||
/// is read whole as its packet unless `scan`; any other file is scanned for its first UTF-8 packet.
|
||||
/// → `{packet, offset, length, writeable, sidecar, charForm}`, with `packet` null when the file has
|
||||
/// none.
|
||||
fn xmp_open(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
let path = arg_text(a, 0);
|
||||
let (update, scan) = (matches!(a.get(1), Some(Data::Bool(true))), matches!(a.get(2), Some(Data::Bool(true))));
|
||||
let mut disk = host.disk.borrow_mut();
|
||||
match disk.stat(&path) {
|
||||
Ok(Some(e)) if !e.file => return Ok(error(NOT_REGULAR)),
|
||||
Ok(Some(e)) if e.len > MAX_FILE_BYTES as u64 => return Ok(error(TOO_LARGE)),
|
||||
Ok(Some(_)) => {}
|
||||
Ok(None) => return Ok(error(NOT_FOUND)),
|
||||
Err(m) => return Ok(error(m)),
|
||||
}
|
||||
let (real, bytes) = match disk.scope.read(Path::new(&path), MAX_FILE_BYTES) {
|
||||
Ok(read) => read,
|
||||
Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)),
|
||||
Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)),
|
||||
Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)),
|
||||
Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)),
|
||||
};
|
||||
disk.charge_read(&real, bytes.len())?;
|
||||
let sidecar = is_sidecar(&path) && is_sidecar(&real.to_string_lossy()) && !scan;
|
||||
// Only a file that can take a packet needs to be one the run may write.
|
||||
if update
|
||||
&& sidecar
|
||||
&& let Err(m) = disk.target(&path, true)
|
||||
{
|
||||
return Ok(error(m));
|
||||
}
|
||||
let number = |n: usize| Data::Number(n as f64);
|
||||
let (packet, offset, length, writeable, char_form) = if sidecar {
|
||||
let Some((text, form)) = sidecar_text(&bytes) else { return Ok(error(UNDECODABLE)) };
|
||||
(Data::String(text), 0, bytes.len(), true, form)
|
||||
} else {
|
||||
match vectorcraft_js::find_xmp_packet(&bytes) {
|
||||
Some(span) => match bytes.get(span.start..span.end).map(std::str::from_utf8) {
|
||||
Some(Ok(text)) => (Data::String(text.to_string()), span.start, span.end - span.start, span.writeable, 0),
|
||||
_ => return Ok(error(UNDECODABLE)),
|
||||
},
|
||||
None => (Data::Null, 0, 0, false, 0),
|
||||
}
|
||||
};
|
||||
Ok(Data::Object(vec![
|
||||
("packet".into(), packet),
|
||||
("offset".into(), number(offset)),
|
||||
("length".into(), number(length)),
|
||||
("writeable".into(), Data::Bool(writeable)),
|
||||
("sidecar".into(), Data::Bool(sidecar)),
|
||||
("charForm".into(), Data::Number(f64::from(char_form))),
|
||||
]))
|
||||
}
|
||||
|
||||
fn xmp_utf8_packet(text: &str) -> Result<Vec<u8>, &'static str> {
|
||||
let body = text.strip_prefix('\u{feff}').unwrap_or(text);
|
||||
if body.starts_with("<?xml") && body.as_bytes().get(5).is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n')) {
|
||||
let options = craft_xml::Options { pis: true, comments: true, drop_blank_text: false, ..craft_xml::Options::default() }.strict();
|
||||
let mut events = options.events(body.as_bytes());
|
||||
match events.next() {
|
||||
Ok(Some(_)) => Ok(body.as_bytes()[events.span().start..].to_vec()),
|
||||
_ => Err(UNDECODABLE),
|
||||
}
|
||||
} else {
|
||||
Ok(text.as_bytes().to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
/// `xmpWrite(path, packet, safely)`: the `.xmp` file at `path` replaced by `packet` in UTF-8, under
|
||||
/// the rules for writing. The packet goes to a temporary file in the same folder that then takes the
|
||||
/// file's name, when the run may write there; otherwise to the file itself, unless `safely`, which
|
||||
/// fails and leaves the file as it is. Open objects of the file hold the new bytes.
|
||||
/// The writer omits a leading XML declaration.
|
||||
/// On Unix, the destination folder is flushed after writing. A folder flush failure returns an
|
||||
/// error after the written path is recorded and open readers receive the replacement packet.
|
||||
fn xmp_write(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
let path = arg_text(a, 0);
|
||||
let packet = match xmp_utf8_packet(&arg_text(a, 1)) {
|
||||
Ok(packet) => packet,
|
||||
Err(message) => return Ok(error(message)),
|
||||
};
|
||||
let safely = matches!(a.get(2), Some(Data::Bool(true)));
|
||||
if !is_sidecar(&path) {
|
||||
return Ok(error(ACCESS_DENIED));
|
||||
}
|
||||
if packet.len() > MAX_FILE_BYTES {
|
||||
return Ok(error(TOO_LARGE));
|
||||
}
|
||||
let mut disk = host.disk.borrow_mut();
|
||||
let target = match disk.target(&path, true) {
|
||||
Ok(t) => t,
|
||||
Err(m) => return Ok(error(m)),
|
||||
};
|
||||
// A `.xmp` link that leads to another kind of file does not make that file a sidecar.
|
||||
if !is_sidecar(&target.to_string_lossy()) {
|
||||
return Ok(error(ACCESS_DENIED));
|
||||
}
|
||||
if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) {
|
||||
return Ok(error(NOT_REGULAR));
|
||||
}
|
||||
// An open object of the file with changes not yet written keeps them: the packet is not written
|
||||
// over them.
|
||||
if disk.open.values().any(|o| o.dirty && o.holds(&target)) {
|
||||
return Ok(error(WRITE_FAILED));
|
||||
}
|
||||
let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let temp_name = |n: u32| target.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id()));
|
||||
let first = temp_name(0);
|
||||
let temp_allowed = disk.target(&first.to_string_lossy(), false).is_ok_and(|t| t == first);
|
||||
// A safe update writes only through a temporary file.
|
||||
if safely && !temp_allowed {
|
||||
return Ok(error(WRITE_FAILED));
|
||||
}
|
||||
let holders = disk.open.values().filter(|o| o.holds(&target)).count();
|
||||
disk.charge_write(packet.len().saturating_mul(holders.saturating_add(1)))?;
|
||||
// `changed` is whether the file's bytes may differ from before: after a replacement, or once a
|
||||
// direct write has opened (and so emptied) the file.
|
||||
let (r, changed) = if temp_allowed {
|
||||
// The temporary file takes a name no file or link has, so only the sidecar is replaced; when
|
||||
// none of the names is free the sidecar is left as it is.
|
||||
// Each name is checked against the places the run may write before it is made.
|
||||
let allowed = |t: &Path| disk.target(&t.to_string_lossy(), false).is_ok_and(|r| r == t);
|
||||
let new_file = |t: &Path| {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
// On Unix the file starts readable and writable by its owner alone, until the packet is in
|
||||
// it and the sidecar's permission bits are copied to it.
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
allowed(t).then(|| options.open(t).ok()).flatten()
|
||||
};
|
||||
let Some((temp, mut out)) = (0..16).map(temp_name).find_map(|t| new_file(&t).map(|f| (t, f))) else {
|
||||
return Ok(error(WRITE_FAILED));
|
||||
};
|
||||
let mut write_temp = || {
|
||||
#[cfg(test)]
|
||||
if XMP_WRITE_FAILS.with(std::cell::Cell::get) {
|
||||
return Err(std::io::Error::other("write failed"));
|
||||
}
|
||||
#[cfg(all(test, unix))]
|
||||
{
|
||||
let mode = std::os::unix::fs::PermissionsExt::mode(&out.metadata()?.permissions());
|
||||
XMP_TEMP_MODE.with(|m| m.set(Some(mode)));
|
||||
}
|
||||
std::io::Write::write_all(&mut out, &packet)?;
|
||||
// The packet is on the disk before it takes the sidecar's name, as a saved document's is.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
vectorcraft_format::sync_file(&out)?;
|
||||
Ok(())
|
||||
};
|
||||
let r = write_temp();
|
||||
drop(out);
|
||||
// The replacement keeps the sidecar's permission bits, group and (Linux) access ACL, or is
|
||||
// readable by its owner alone, as a saved document is (`vectorcraft_format::keep_permissions`).
|
||||
// On Windows the only permission is the read-only attribute, and a read-only temporary file
|
||||
// could not be removed after a failed rename. The web build has no such files. Keeping them
|
||||
// is best effort, as for a saved document: a volume without Unix permissions (SMB, FAT) refuses them, and the
|
||||
// update still goes through.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if r.is_ok() {
|
||||
let _ = vectorcraft_format::keep_permissions(&target, &temp);
|
||||
}
|
||||
let r = r.and_then(|()| std::fs::rename(&temp, &target)).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
});
|
||||
let changed = r.is_ok();
|
||||
(r, changed)
|
||||
} else {
|
||||
match std::fs::File::create(&target) {
|
||||
Ok(mut f) => (std::io::Write::write_all(&mut f, &packet), true),
|
||||
Err(e) => (Err(e), false),
|
||||
}
|
||||
};
|
||||
if changed {
|
||||
disk.wrote(&target);
|
||||
}
|
||||
if r.is_ok() {
|
||||
for file in disk.open.values_mut().filter(|o| o.holds(&target)) {
|
||||
let reset = file.bytes.starts_with(&[0xEF, 0xBB, 0xBF]) || matches!(file.encoding, Encoding::Utf16Le | Encoding::Utf16Be);
|
||||
file.bytes.clone_from(&packet);
|
||||
// `File` readers with a UTF-8 byte order mark or UTF-16 encoding restart in UTF-8.
|
||||
if reset {
|
||||
file.encoding = Encoding::Utf8;
|
||||
file.name = Encoding::Utf8.name().to_string();
|
||||
file.pos = 0;
|
||||
}
|
||||
file.pos = file.pos.min(packet.len());
|
||||
file.dirty = false;
|
||||
}
|
||||
}
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
let r = r.and_then(|()| {
|
||||
#[cfg(test)]
|
||||
if XMP_DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
|
||||
return Err(std::io::Error::other("directory flush failed"));
|
||||
}
|
||||
vectorcraft_format::sync_parent(&target)
|
||||
});
|
||||
Ok(done(r.map_err(|_| WRITE_FAILED)))
|
||||
}
|
||||
|
||||
/// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to.
|
||||
fn remove(host: &Host, a: &[Data]) -> Result<Data, HostError> {
|
||||
let mut disk = host.disk.borrow_mut();
|
||||
@@ -2480,8 +2706,20 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
|
||||
("setHidden".into(), call(link, set_hidden)),
|
||||
("createAlias".into(), call(link, create_alias)),
|
||||
("pick".into(), call(link, pick)),
|
||||
("xmpOpen".into(), call(link, xmp_open)),
|
||||
(
|
||||
"xmpWrite".into(),
|
||||
HostItem::FunctionWithLimits {
|
||||
limits: vectorcraft_js::DataLimits {
|
||||
bytes: 3 * vectorcraft_js::XMP_MAX_BYTES + (128 << 10),
|
||||
..vectorcraft_js::DataLimits::default()
|
||||
},
|
||||
function: call_function(link, xmp_write),
|
||||
},
|
||||
),
|
||||
];
|
||||
realm.define_file_classes(items)
|
||||
realm.define_file_classes(items)?;
|
||||
realm.define_external_object()
|
||||
}
|
||||
|
||||
/// Tests: what the next `copy` does with its source's path, as given and as its real path, after
|
||||
@@ -2501,6 +2739,13 @@ thread_local! {
|
||||
pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell<Option<AliasHook>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: while set, the bytes `flush` writes fail after the file was opened for them.
|
||||
pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: while set, `xmpWrite` fails after its checks and before it writes.
|
||||
pub(crate) static XMP_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
#[cfg(unix)]
|
||||
pub(crate) static XMP_DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: the permission bits of the last temporary file `xmpWrite` made, before it wrote to it.
|
||||
#[cfg(unix)]
|
||||
pub(crate) static XMP_TEMP_MODE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -184,6 +184,7 @@ mod script_include;
|
||||
mod script_io;
|
||||
mod script_run;
|
||||
mod script_tags;
|
||||
mod script_xmp;
|
||||
mod scripts;
|
||||
mod segment_nudge;
|
||||
mod select_effects;
|
||||
|
||||
@@ -1165,3 +1165,174 @@ fn gamut_check_refuses_colors_that_are_not_a_list() {
|
||||
assert_eq!(r, s.execute("color.gamutCheck", &json!({})).unwrap());
|
||||
assert!(r["outOfGamut"].as_array().unwrap().iter().any(|v| v["hex"] == "#0000ff"), "{r}");
|
||||
}
|
||||
|
||||
fn mode_index_swatch(name: &str, paint: Paint, global: bool) -> vectorcraft_color::Swatch {
|
||||
vectorcraft_color::Swatch { name: name.into(), paint, global, spot: false }
|
||||
}
|
||||
|
||||
fn mode_index_link(color: Color, name: &str, tint: f32) -> Paint {
|
||||
Paint::Solid { color, swatch: Some(name.into()), tint }
|
||||
}
|
||||
|
||||
fn mode_index_gradient() -> Paint {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, Color::rgb(0.1, 0.2, 0.3)), GradientStop::new(1.0, Color::rgb(0.8, 0.7, 0.6))],
|
||||
))))
|
||||
}
|
||||
|
||||
/// A later global cannot replace the first exact-name record, even when that first record
|
||||
/// cannot supply a global base. These legacy palettes exercise the public conversion command.
|
||||
#[test]
|
||||
fn document_mode_index_keeps_ineligible_first_name_shadowing() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let stored = Color::rgb(0.123_457, 0.456_789, 0.789_123);
|
||||
let shadows = [
|
||||
(Paint::solid(Color::rgb(0.8, 0.1, 0.2)), false),
|
||||
(mode_index_link(Color::rgb(0.6, 0.3, 0.4), "Underlying", 0.5), true),
|
||||
(mode_index_gradient(), true),
|
||||
];
|
||||
for grouped in [false, true] {
|
||||
for (paint, global) in &shadows {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(stored));
|
||||
s.edit("legacy duplicate palette", |d, _| {
|
||||
let first = mode_index_swatch("Shadow", paint.clone(), *global);
|
||||
let later = mode_index_swatch("Shadow", Paint::solid(Color::rgb(0.1, 0.8, 0.2)), true);
|
||||
d.swatches = vec![mode_index_swatch("Underlying", Paint::solid(Color::rgb(0.2, 0.4, 0.6)), true)].into();
|
||||
d.swatch_groups.clear();
|
||||
if grouped {
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "First".into(), swatches: vec![first] });
|
||||
} else {
|
||||
d.swatches.push(first);
|
||||
}
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Later".into(), swatches: vec![later] });
|
||||
d.node_mut(id).unwrap().appearance.set_fill(mode_index_link(stored, "Shadow", 0.25));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.global_color("Shadow"), None);
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
assert_eq!(fill_of(&s, id), mode_index_link(to_cmyk(stored), "Shadow", 0.25), "grouped={grouped}, first={paint:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A first eligible record wins over later groups, and its converted base supplies art,
|
||||
/// gradient-stop and tint-swatch colors. Undo/Redo retain the complete duplicate palette.
|
||||
#[test]
|
||||
fn document_mode_index_uses_the_first_global_base_across_groups() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let base = Color::rgb(0.271_937, 0.314_773, 0.583_119);
|
||||
let other = Color::rgb(0.812_345, 0.234_567, 0.456_789);
|
||||
for grouped in [false, true] {
|
||||
let mut s = session();
|
||||
let filled = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(base));
|
||||
let gradient = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!(other));
|
||||
s.edit("legacy grouped palette", |d, _| {
|
||||
let first = mode_index_swatch("Shared", Paint::solid(base), true);
|
||||
let later = mode_index_swatch("Shared", Paint::solid(other), true);
|
||||
d.swatches = vec![mode_index_swatch("Shared tint", mode_index_link(base.tinted(0.3), "Shared", 0.3), false)].into();
|
||||
d.swatch_groups.clear();
|
||||
if grouped {
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "First".into(), swatches: vec![first] });
|
||||
} else {
|
||||
d.swatches.push(first);
|
||||
}
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Later".into(), swatches: vec![later] });
|
||||
d.node_mut(filled).unwrap().appearance.set_fill(mode_index_link(base.tinted(0.25), "Shared", 0.25));
|
||||
let stop = GradientStop { swatch: Some("Shared".into()), tint: 0.6, ..GradientStop::new(0.0, base.tinted(0.6)) };
|
||||
d.node_mut(gradient).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![stop, GradientStop::new(1.0, other)],
|
||||
)))));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let converted = to_cmyk(base);
|
||||
assert_eq!(fill_of(&s, filled), mode_index_link(converted.tinted(0.25), "Shared", 0.25));
|
||||
assert_eq!(s.doc().unwrap().doc.swatch("Shared").unwrap().paint.color(), Some(converted));
|
||||
assert_eq!(s.doc().unwrap().doc.swatch("Shared tint").unwrap().paint, mode_index_link(converted.tinted(0.3), "Shared", 0.3));
|
||||
let Paint::Gradient(paint) = fill_of(&s, gradient) else { panic!("gradient lost") };
|
||||
assert_eq!(
|
||||
(paint.gradient.stops[0].color, paint.gradient.stops[0].swatch.as_deref(), paint.gradient.stops[0].tint),
|
||||
(converted.tinted(0.6), Some("Shared"), 0.6)
|
||||
);
|
||||
assert_eq!(paint.gradient.stops[1].color, to_cmyk(other));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
|
||||
let after = s.doc().unwrap().doc.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *after);
|
||||
}
|
||||
}
|
||||
|
||||
/// Grouped Lab spots keep their definitions; both Spot Colors choices supply their own linked
|
||||
/// base to document art, tint swatches and the new-art fill when the document mode changes.
|
||||
#[test]
|
||||
fn document_mode_index_keeps_grouped_lab_spot_options_and_new_art() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let lab = Color::Lab { l: 61.5, a: 42.25, b: -17.75 };
|
||||
for use_lab in [false, true] {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Indexed Lab", "color": lab, "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"swatch": "Indexed Lab", "tint": 70})).unwrap();
|
||||
s.edit("group the spot", |d, _| {
|
||||
let ink = d.remove_swatch("Indexed Lab").unwrap();
|
||||
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Spot group".into(), swatches: vec![ink] });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("swatch.spotOptions", &json!({"useLab": use_lab})).unwrap();
|
||||
let id = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!("#000000"));
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "swatch": "Indexed Lab", "tint": 40})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let old_paint = s.paint.clone();
|
||||
let base = if use_lab { lab } else { to_cmyk(lab) };
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let ink = s.doc().unwrap().doc.swatch("Indexed Lab").unwrap();
|
||||
assert!(ink.global && ink.spot);
|
||||
assert_eq!(ink.paint, Paint::solid(lab));
|
||||
let expected = mode_index_link(base.tinted(0.4), "Indexed Lab", 0.4);
|
||||
assert_eq!(fill_of(&s, id), expected);
|
||||
assert_eq!(s.paint.fill, expected, "new art follows the same spot choice");
|
||||
assert_eq!(s.doc().unwrap().doc.swatch("Indexed Lab 70%").unwrap().paint, mode_index_link(base.tinted(0.7), "Indexed Lab", 0.7));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *before);
|
||||
assert_eq!(s.paint, old_paint);
|
||||
}
|
||||
}
|
||||
|
||||
/// The implicit Registration lookup is not a stored palette record. Only an explicit global
|
||||
/// record supplies its tint base here; an unresolved link keeps conversion of its stored color.
|
||||
#[test]
|
||||
fn document_mode_index_keeps_registration_and_missing_link_fallbacks() {
|
||||
use vectorcraft_color::swatch::{REGISTRATION, registration};
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let stored = Color::rgb(0.321_987, 0.654_321, 0.876_543);
|
||||
for explicit in [false, true] {
|
||||
let mut s = session();
|
||||
let mark = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(stored));
|
||||
let missing = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!(stored));
|
||||
s.edit("legacy registration and missing link", |d, _| {
|
||||
d.swatches = (if explicit { vec![registration().clone()] } else { vec![] }).into();
|
||||
d.swatch_groups.clear();
|
||||
d.node_mut(mark).unwrap().appearance.set_fill(mode_index_link(stored, REGISTRATION, 0.25));
|
||||
d.node_mut(missing).unwrap().appearance.set_fill(mode_index_link(stored, "Missing", 0.5));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch(REGISTRATION).is_some(), "the implicit lookup exists in both fixtures");
|
||||
assert_eq!(s.doc().unwrap().doc.swatches_iter().count(), usize::from(explicit));
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
let color = if explicit { Color::cmyk(1.0, 1.0, 1.0, 1.0).tinted(0.25) } else { to_cmyk(stored) };
|
||||
assert_eq!(fill_of(&s, mark), mode_index_link(color, REGISTRATION, 0.25));
|
||||
assert_eq!(fill_of(&s, missing), mode_index_link(to_cmyk(stored), "Missing", 0.5));
|
||||
}
|
||||
}
|
||||
@@ -708,12 +708,17 @@ fn metadata_template_errors() {
|
||||
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
|
||||
let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err();
|
||||
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
|
||||
let encoded = "A".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES.div_ceil(3) * 4 + 1);
|
||||
let e = s.execute("file.info.applyTemplate", &json!({"dataBase64": encoded, "mode": "keep"})).unwrap_err();
|
||||
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
|
||||
for bad in [
|
||||
json!({"data": xmp, "mode": "merge"}),
|
||||
json!({"data": xmp}),
|
||||
json!({"data": xmp, "mode": 3}),
|
||||
json!({"mode": "keep"}),
|
||||
json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}),
|
||||
json!({"data": xmp, "dataBase64": "SGVsbG8=", "mode": "keep"}),
|
||||
json!({"dataBase64": "!", "mode": "keep"}),
|
||||
json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}),
|
||||
json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}),
|
||||
json!({"path": big.to_str().unwrap(), "mode": "keep"}),
|
||||
|
||||
@@ -475,6 +475,38 @@ fn duplicate_artboard_copies_its_art() {
|
||||
assert_eq!(ids(&s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap()["ids"]).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_artboard_and_alt_drag_copy_artwork_larger_than_artboard() {
|
||||
let mut s = session();
|
||||
// Default artboard is 800x600 at (0, 0).
|
||||
// An oversized background (900x700 centered at (400, 300), hanging 50pt off all 4 edges, #4479).
|
||||
let bg = s.execute("shape.rectangle", &json!({"x": -50, "y": -50, "width": 900, "height": 700})).unwrap();
|
||||
let bg_id = bg["id"].as_u64().unwrap();
|
||||
// An oversized banner across the artboard with overhang (900x100 at x: -50, y: 100).
|
||||
let banner = s.execute("shape.rectangle", &json!({"x": -50, "y": 100, "width": 900, "height": 100})).unwrap();
|
||||
let banner_id = banner["id"].as_u64().unwrap();
|
||||
|
||||
// 1. Menu duplication (artboard.duplicate with art: true).
|
||||
let dup = s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap();
|
||||
let dup_copies = ids(&dup["ids"]);
|
||||
assert_eq!(dup_copies.len(), 2, "copies both oversized background and banner artwork: {dup_copies:?}");
|
||||
assert!(!dup_copies.contains(&bg_id) && !dup_copies.contains(&banner_id));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
// 2. Alt-drag with Artboard tool (artboard.move with copy: true and moveArt: true).
|
||||
let alt_drag = s.execute("artboard.move", &json!({"index": 0, "dx": 1000, "dy": 0, "copy": true, "moveArt": true})).unwrap();
|
||||
let alt_copies = ids(&alt_drag["moved"]);
|
||||
assert_eq!(alt_copies.len(), 2, "Alt-drag copies both oversized background and banner artwork: {alt_copies:?}");
|
||||
assert!(!alt_copies.contains(&bg_id) && !alt_copies.contains(&banner_id));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
// 3. Move artboard with Artboard tool / command (artboard.move with moveArt: true).
|
||||
// Under strict containment (#890 / #1295), overhanging art stays behind during plain move.
|
||||
let moved = s.execute("artboard.move", &json!({"index": 0, "dx": 200, "dy": 100, "moveArt": true})).unwrap();
|
||||
let moved_ids = ids(&moved["moved"]);
|
||||
assert_eq!(moved_ids.len(), 0, "move leaves overhanging artwork behind: {moved_ids:?}");
|
||||
}
|
||||
|
||||
/// New Artboard and Artboard Options trim the name they are given, as the Artboards panel's rename
|
||||
/// does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard.
|
||||
#[test]
|
||||
|
||||
@@ -657,6 +657,28 @@ fn pdf_pages_and_native_artboards_place_as_clipped_groups() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Place and Set Bounds use the layout of native point type, including its alignment.
|
||||
#[test]
|
||||
fn bounding_native_placement_measures_aligned_point_type() {
|
||||
for (justify, x) in [("center", 190), ("right", 275)] {
|
||||
let mut src = session();
|
||||
let square = src.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].clone();
|
||||
src.execute("paint.setStroke", &json!({"id": square, "none": true})).unwrap();
|
||||
src.execute("text.create", &json!({"text": "Sample test", "x": x, "y": 150, "size": 18, "justify": justify})).unwrap();
|
||||
let shown = vectorcraft_render::encode::art_bounds(&src.doc().unwrap().doc).unwrap();
|
||||
let width = node(&src, &square).geometric_bounds().unwrap().width();
|
||||
assert!(close(shown.width(), width), "the {justify}-aligned text starts inside the square");
|
||||
let native = serialize(&mut src, "vectorcraft");
|
||||
|
||||
let mut placed = session();
|
||||
let r = place(&mut placed, "aligned.vectorcraft", &native, json!({"crop": "bounding", "link": false}));
|
||||
assert!(close(r["width"].as_f64().unwrap(), width), "{justify}: {r}");
|
||||
placed.execute("object.setBounds", &json!({"width": width, "proportional": true})).unwrap();
|
||||
let after = vectorcraft_render::encode::art_bounds(&placed.doc().unwrap().doc).unwrap();
|
||||
assert!(close(after.width(), shown.width()), "{justify}: {shown:?} became {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With crop "bounding", the art's box is the box of what shows, as an export measures it: a hidden
|
||||
/// member of a group does not count, and is still placed, hidden.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,815 @@
|
||||
//! `XMPFile` in a script: reading and writing a sidecar packet through the script's file places,
|
||||
//! scanning another file for its packet, and the paths and packets it refuses.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const LOAD: &str = "new ExternalObject('lib:AdobeXMPScript');\n";
|
||||
|
||||
const PACKET: &str = "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\
|
||||
<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
|
||||
<rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\
|
||||
<dc:format>image/svg+xml</dc:format><dc:subject><rdf:Bag><rdf:li>a</rdf:li><rdf:li>b</rdf:li></rdf:Bag></dc:subject>\
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>";
|
||||
|
||||
#[test]
|
||||
fn a_large_supported_packet_crosses_the_sidecar_write_transport() {
|
||||
let base = folder("large-write-transport");
|
||||
let payload = "x".repeat(6 << 20);
|
||||
let packet = PACKET.replace("image/svg+xml", &payload);
|
||||
let mut session = with_data(&base);
|
||||
let setup = logged(&mut session, &base, "vc.log(Folder.userData.fsName + '/large.xmp');");
|
||||
let path = PathBuf::from(setup[0].as_str().unwrap());
|
||||
write(&path, packet.as_bytes());
|
||||
let log = logged(
|
||||
&mut session,
|
||||
&base,
|
||||
"var p = Folder.userData.fsName + '/large.xmp'; var x = new XMPFile(p, XMPConst.FILE_XML, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'title', 'changed-for-write'); x.putXMP(m); x.closeFile(); vc.log(true);",
|
||||
);
|
||||
assert_eq!(log, json!([true]));
|
||||
let written = std::fs::read_to_string(path).unwrap();
|
||||
assert!(written.contains(&payload));
|
||||
assert!(written.contains("changed-for-write"));
|
||||
}
|
||||
|
||||
struct Folder {
|
||||
_guard: vectorcraft_testkit::TempDir,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Folder {
|
||||
type Target = PathBuf;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for Folder {
|
||||
fn as_ref(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path.
|
||||
fn folder(name: &str) -> Folder {
|
||||
let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}"));
|
||||
let base = std::fs::canonicalize(&*guard).unwrap();
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
Folder { _guard: guard, path: base }
|
||||
}
|
||||
|
||||
fn write(path: &Path, bytes: &[u8]) {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(path, bytes).unwrap();
|
||||
}
|
||||
|
||||
/// A session whose scripts keep their data folders in `base/settings/Script Data`.
|
||||
fn with_data(base: &Path) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.attach_script_data(base.join("settings/Script Data"));
|
||||
s
|
||||
}
|
||||
|
||||
/// Runs `main/main.jsx` in `base` with the XMP library loaded and the text `text` in `s`.
|
||||
fn run_in(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
|
||||
let main = base.join("main/main.jsx");
|
||||
write(&main, format!("{LOAD}{text}").as_bytes());
|
||||
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
|
||||
}
|
||||
|
||||
/// The values the run of `text` logged.
|
||||
fn logged(s: &mut Session, base: &Path, text: &str) -> Value {
|
||||
match run_in(s, base, text) {
|
||||
Ok(r) => r["log"].clone(),
|
||||
Err(e) => panic!("{text}\n{e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A sidecar in the script's data folder reads, takes a changed packet and holds it after
|
||||
/// `closeFile`; a new `XMPFile` reads it back.
|
||||
#[test]
|
||||
fn a_sidecar_packet_reads_and_writes() {
|
||||
let base = folder("sidecar");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.encoding = 'UTF-8'; f.open('w'); f.write({PACKET:?}); f.close();\n\
|
||||
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); var info = x.getFileInfo();\n\
|
||||
var out = [m.getProperty(XMPConst.NS_DC, 'format').value, m.countArrayItems(XMPConst.NS_DC, 'subject'), info.format == XMPConst.FILE_XML, x.canPutXMP(m)];\n\
|
||||
m.setProperty(XMPConst.NS_DC, 'format', 'text/plain'); m.appendArrayItem(XMPConst.NS_DC, 'subject', 'c');\n\
|
||||
x.putXMP(m); x.closeFile();\n\
|
||||
var y = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var n = y.getXMP();\n\
|
||||
out.push(n.getProperty(XMPConst.NS_DC, 'format').value, n.getArrayItem(XMPConst.NS_DC, 'subject', 3).value, y.getPacketInfo().offset, y.canPutXMP(n));\n\
|
||||
y.closeFile(); vc.log(out); vc.log(p);"
|
||||
),
|
||||
);
|
||||
assert_eq!(log[0], json!(["image/svg+xml", 2, true, true, "text/plain", "c", 0, false]));
|
||||
let path = PathBuf::from(log[1].as_str().unwrap());
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(text.contains("<dc:format>text/plain</dc:format>"), "{text}");
|
||||
let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap()).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name()).collect();
|
||||
assert_eq!(leftovers.len(), 1, "no temporary file stays: {leftovers:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A file that is not a sidecar is scanned for its packet, read only, and a file with none gives
|
||||
/// `null`.
|
||||
#[test]
|
||||
fn another_file_is_scanned_for_its_packet() {
|
||||
let base = folder("scan");
|
||||
let mut bytes = b"\x89binary\x00head".to_vec();
|
||||
bytes.extend_from_slice(PACKET.as_bytes());
|
||||
bytes.extend_from_slice(b"\x00tail");
|
||||
write(&base.join("main/art.bin"), &bytes);
|
||||
write(&base.join("main/none.bin"), b"no packet here");
|
||||
let mut s = Session::new();
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var x = new XMPFile(File('art.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var i = x.getPacketInfo();\n\
|
||||
var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, i.offset, i.length, i.writeable, x.canPutXMP(x.getXMP())];\n\
|
||||
try { x.putXMP(x.getXMP()); out.push('put'); } catch (e) { out.push(e.message); }\n\
|
||||
out.push(new XMPFile(File('none.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP());\n\
|
||||
x.closeFile(); try { x.getXMP(); } catch (e) { out.push(e.message); } vc.log(out);",
|
||||
);
|
||||
assert_eq!(
|
||||
log[0],
|
||||
json!([
|
||||
"image/svg+xml",
|
||||
12,
|
||||
PACKET.len(),
|
||||
true,
|
||||
false,
|
||||
"XMPFile.putXMP: the file cannot be updated",
|
||||
null,
|
||||
"XMPFile.getXMP: the file is closed"
|
||||
])
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `getPacketInfo().padSize` gives the bytes of whitespace before the packet's trailer: twice the
|
||||
/// characters in a UTF-16 packet, and 0 in a packet with none.
|
||||
#[test]
|
||||
fn packet_info_gives_the_padding() {
|
||||
let base = folder("pad");
|
||||
let padded = PACKET.replace("<?xpacket end=", " \n\t \n<?xpacket end=");
|
||||
write(&base.join("main/p.xmp"), padded.as_bytes());
|
||||
let mut le = vec![0xFF, 0xFE];
|
||||
le.extend(padded.encode_utf16().flat_map(u16::to_le_bytes));
|
||||
write(&base.join("main/le.xmp"), &le);
|
||||
write(&base.join("main/art.bin"), format!("\x00head{padded}\x00tail").as_bytes());
|
||||
write(&base.join("main/none.xmp"), PACKET.as_bytes());
|
||||
let mut s = Session::new();
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"vc.log(['p.xmp', 'le.xmp', 'art.bin', 'none.xmp'].map(function (n) {\n\
|
||||
var x = new XMPFile(File(n).fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var p = x.getPacketInfo().padSize; x.closeFile(); return p;\n\
|
||||
}));",
|
||||
);
|
||||
assert_eq!(log[0], json!([5, 10, 5, 0]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A sidecar opened for update with packet scanning is read only, like any scanned file.
|
||||
#[test]
|
||||
fn a_scanned_sidecar_is_read_only() {
|
||||
let base = folder("scansidecar");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var p = Folder.userData.fsName + '/s.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
|
||||
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE | XMPConst.OPEN_USE_PACKET_SCANNING); var m = x.getXMP();\n\
|
||||
var out = [m.getProperty(XMPConst.NS_DC, 'format').value, x.canPutXMP(m)];\n\
|
||||
try {{ x.putXMP(m); out.push('put'); }} catch (e) {{ out.push(e.message); }} x.closeFile(); vc.log(out);"
|
||||
),
|
||||
);
|
||||
assert_eq!(log[0], json!(["image/svg+xml", false, "XMPFile.putXMP: the file cannot be updated"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The state an `XMPFile` keeps cannot be changed by the script: a sidecar opened for reading is
|
||||
/// not written by `closeFile` after the script assigns, defines or deletes the properties that
|
||||
/// name the packet, the path and the open flags, or calls `closeFile` on another object that holds
|
||||
/// properties of the same names, plain or made from `XMPFile.prototype`.
|
||||
#[test]
|
||||
fn a_script_cannot_change_the_state_of_an_xmp_file() {
|
||||
let base = folder("state");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var p = Folder.userData.fsName + '/r.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
|
||||
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var out = [];\n\
|
||||
x.__vcXmpPending = 'not a packet'; x.__vcXmpFlags = XMPConst.OPEN_FOR_UPDATE; x.__vcXmpPath = p + '.other';\n\
|
||||
try {{ Object.defineProperty(x, '__vcXmpPending', {{ value: 'not a packet' }}); out.push('defined'); }} catch (e) {{ out.push(e.name); }}\n\
|
||||
out.push(typeof x.__vcXmpPending, x.getFileInfo().openFlags == XMPConst.OPEN_FOR_READ);\n\
|
||||
[{{}}, Object.create(XMPFile.prototype)].forEach(function (fake) {{\n\
|
||||
fake.__vcXmpPath = p; fake.__vcXmpRun = x.__vcXmpRun; fake.__vcXmpOpen = true; fake.__vcXmpPending = 'not a packet';\n\
|
||||
try {{ XMPFile.prototype.closeFile.call(fake); out.push('closed'); }} catch (e) {{ out.push(e.name); }}\n\
|
||||
}});\n\
|
||||
x.closeFile(); out.push(delete x.__vcXmpPath); vc.log(out); vc.log(p);"
|
||||
),
|
||||
);
|
||||
assert_eq!(log[0], json!(["defined", "string", true, "TypeError", "TypeError", true]));
|
||||
let text = std::fs::read_to_string(log[1].as_str().unwrap()).unwrap();
|
||||
assert_eq!(text, PACKET);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xmp_file_buffers_are_not_script_properties() {
|
||||
let base = folder("native-packet");
|
||||
let mut session = with_data(&base);
|
||||
let log = logged(
|
||||
&mut session,
|
||||
&base,
|
||||
&format!(
|
||||
"var p = Folder.userData.fsName + '/native.xmp', file = new File(p);\n\
|
||||
file.open('w'); file.write({PACKET:?}); file.close();\n\
|
||||
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE), m = x.getXMP();\n\
|
||||
m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
|
||||
vc.log([typeof x.__vcXmpPacket, typeof x.__vcXmpPending, typeof x.__vcXmpPath,\n\
|
||||
Object.getOwnPropertyNames(x).filter(function (name) {{ return name.indexOf('__vcXmp') === 0; }}).length,\n\
|
||||
x.getXMP().getProperty(XMPConst.NS_DC, 'format').value]); x.closeFile();"
|
||||
),
|
||||
);
|
||||
assert_eq!(log[0], json!(["undefined", "undefined", "undefined", 0, "changed"]));
|
||||
}
|
||||
|
||||
/// A path outside the script's places, a missing file and a file opened for update where the run
|
||||
/// may not write are refused with the file access errors, and a malformed or huge packet with an
|
||||
/// error, never a fault.
|
||||
#[test]
|
||||
fn refused_paths_and_bad_packets_throw() {
|
||||
let base = folder("refused");
|
||||
let outside = folder("refused-outside");
|
||||
write(&outside.join("x.xmp"), PACKET.as_bytes());
|
||||
write(&base.join("main/bad.xmp"), b"<x:xmpmeta><rdf:RDF");
|
||||
write(&base.join("main/ok.xmp"), PACKET.as_bytes());
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"function t(f) {{ try {{ f(); return 'no error'; }} catch (e) {{ return e.name + ': ' + e.message; }} }}\n\
|
||||
vc.log([t(function () {{ new XMPFile({:?}, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); }}),\n\
|
||||
t(function () {{ new XMPFile(File('missing.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); }}),\n\
|
||||
t(function () {{ new XMPFile(File('ok.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); }}),\n\
|
||||
t(function () {{ new XMPFile(File('bad.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP(); }}),\n\
|
||||
t(function () {{ new XMPFile(File('ok.xmp').fsName, XMPConst.FILE_UNKNOWN, 0x100); }}),\n\
|
||||
t(function () {{ var u = new XMPFile(Folder.userData.fsName + '/n.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); }})]);",
|
||||
outside.join("x.xmp").to_string_lossy()
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
log[0],
|
||||
json!([
|
||||
"Error: Script file access denied",
|
||||
"Error: Script file does not exist",
|
||||
"Error: Script file access denied",
|
||||
"Error: XMPFile.getXMP: the XMP packet is not well-formed XMP",
|
||||
"RangeError: XMPFile: the value 0x100 is not available yet",
|
||||
"Error: Script file does not exist"
|
||||
])
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
let _ = std::fs::remove_dir_all(outside);
|
||||
}
|
||||
|
||||
/// A sidecar whose write fails is left as it was and is not named in `written`.
|
||||
#[test]
|
||||
fn a_failed_write_is_not_listed_as_written() {
|
||||
let base = folder("unwritten");
|
||||
let mut s = with_data(&base);
|
||||
logged(&mut s, &base, &format!("var f = new File(Folder.userData.fsName + '/u.xmp'); f.open('w'); f.write({PACKET:?}); f.close();"));
|
||||
crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true));
|
||||
let r = run_in(
|
||||
&mut s,
|
||||
&base,
|
||||
"var x = new XMPFile(Folder.userData.fsName + '/u.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
|
||||
try { x.closeFile(); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["log"], json!(["Script file could not be written"]));
|
||||
assert_eq!(r["written"], json!([]), "a file the run did not change is not listed");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A sidecar that an open `File` has changed and not yet written is not written over: the `File`
|
||||
/// keeps its changes and writes them when it closes.
|
||||
#[test]
|
||||
fn unwritten_file_changes_are_not_written_over() {
|
||||
let base = folder("pending");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var p = Folder.userData.fsName + '/w.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
|
||||
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
|
||||
f.open('e'); f.seek(0, 2); f.write('<!-- kept -->');\n\
|
||||
function text() {{ var g = new File(p); g.open('r'); var t = g.read(); g.close(); return t; }}\n\
|
||||
var out = []; try {{ x.closeFile(); }} catch (e) {{ out.push(e.message); }} f.close(); out.push(text().indexOf('kept') > 0);\n\
|
||||
x.closeFile(); out.push(text().indexOf('changed') > 0); vc.log(out);"
|
||||
),
|
||||
);
|
||||
assert_eq!(log[0], json!(["Script file could not be written", true, true]), "the File's changes are written, then the packet");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A file with the name of the temporary file is left alone: the packet goes through another name
|
||||
/// and replaces only the sidecar.
|
||||
#[test]
|
||||
fn a_file_in_the_temporary_name_is_left_alone() {
|
||||
let base = folder("taken");
|
||||
let mut s = with_data(&base);
|
||||
let path = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("var f = new File(Folder.userData.fsName + '/t.xmp'); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(f.fsName);"),
|
||||
);
|
||||
let path = PathBuf::from(path[0].as_str().unwrap());
|
||||
let taken = path.with_file_name(format!(".t.xmp.{}.0.tmp", std::process::id()));
|
||||
write(&taken, b"someone else's");
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var x = new XMPFile(Folder.userData.fsName + '/t.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile(); vc.log('closed');",
|
||||
);
|
||||
assert_eq!(log, json!(["closed"]));
|
||||
assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's");
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("changed"));
|
||||
let names: Vec<String> =
|
||||
std::fs::read_dir(path.parent().unwrap()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(names.iter().filter(|n| n.ends_with(".tmp")).count(), 1, "no temporary file is left behind: {names:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Pumps the run until it waits for a file dialog (`None`) or ends.
|
||||
fn pump_to_picker(s: &mut Session) -> Option<Result<Value>> {
|
||||
for _ in 0..10_000 {
|
||||
if s.script_picker().is_some() {
|
||||
return None;
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
return Some(r);
|
||||
}
|
||||
}
|
||||
panic!("the run neither ended nor waited");
|
||||
}
|
||||
|
||||
/// Starts `main/main.jsx` in `base` with the XMP library loaded and the text `text`, in the app.
|
||||
fn start_framed(s: &mut Session, base: &Path, text: &str) {
|
||||
s.script_frames = true;
|
||||
let main = base.join("main/main.jsx");
|
||||
write(&main, format!("{LOAD}{text}").as_bytes());
|
||||
assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true);
|
||||
}
|
||||
|
||||
/// With only the sidecar and the first temporary name granted, a taken first name does not make
|
||||
/// the packet go to another name outside the grants: `closeFile()` throws and no file is made.
|
||||
#[test]
|
||||
fn temporary_names_outside_the_grants_are_not_made() {
|
||||
let base = folder("tempgrant");
|
||||
let (sidecar, taken) = (base.join("picked/t.xmp"), base.join(format!("picked/.t.xmp.{}.0.tmp", std::process::id())));
|
||||
write(&sidecar, PACKET.as_bytes());
|
||||
write(&taken, b"someone else's");
|
||||
let mut s = with_data(&base);
|
||||
start_framed(
|
||||
&mut s,
|
||||
&base,
|
||||
"var a = File.saveDialog('a'), b = File.saveDialog('b');\n\
|
||||
var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
|
||||
try { x.closeFile(); vc.log('closed'); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
for path in [&sidecar, &taken] {
|
||||
assert!(pump_to_picker(&mut s).is_none());
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![path.to_string_lossy().into_owned()], always: false }));
|
||||
}
|
||||
let r = pump_to_picker(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!(["Script file could not be written"]));
|
||||
assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET);
|
||||
assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's");
|
||||
let names: Vec<String> = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(names.len(), 2, "no other file is made: {names:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A `.xmp` link to another kind of file is scanned and takes no packet, and a link that leads to
|
||||
/// another kind of file by the time of `closeFile()` is not written through.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_to_another_kind_of_file_is_not_written() {
|
||||
let base = folder("link");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = Folder.userData.fsName, l = d + '/l.xmp';\n\
|
||||
function put(n) {{ var f = new File(d + '/' + n); f.open('w'); f.write({PACKET:?}); f.close(); }}\n\
|
||||
function link(n) {{ var f = new File(l); if (f.exists) f.remove(); return !!new File(l).createAlias(d + '/' + n); }}\n\
|
||||
put('other.txt'); put('real.xmp'); var out = [link('other.txt')];\n\
|
||||
var a = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); out.push(a.canPutXMP(a.getXMP())); a.closeFile();\n\
|
||||
out.push(link('real.xmp'));\n\
|
||||
var x = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\
|
||||
m.setProperty(XMPConst.NS_DC, 'format', 'changed'); out.push(x.canPutXMP(m)); x.putXMP(m);\n\
|
||||
out.push(link('other.txt'));\n\
|
||||
try {{ x.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message); }}\n\
|
||||
vc.log(out); vc.log(d);"
|
||||
),
|
||||
);
|
||||
assert_eq!(log[0], json!([true, false, true, true, true, "Script file access denied"]));
|
||||
let d = PathBuf::from(log[1].as_str().unwrap());
|
||||
assert_eq!(std::fs::read_to_string(d.join("other.txt")).unwrap(), PACKET);
|
||||
assert_eq!(std::fs::read_to_string(d.join("real.xmp")).unwrap(), PACKET);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A sidecar replaced through a temporary file keeps its permission bits.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_replaced_sidecar_keeps_its_permissions() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let base = folder("mode");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
|
||||
);
|
||||
let path = PathBuf::from(log[0].as_str().unwrap());
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
|
||||
);
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("changed"));
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A sidecar in UTF-16 is read by its byte order mark, and one that is not text is refused.
|
||||
#[test]
|
||||
fn a_utf16_sidecar_reads_by_its_byte_order_mark() {
|
||||
let base = folder("utf16");
|
||||
let mut le = vec![0xFF, 0xFE];
|
||||
le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes));
|
||||
write(&base.join("main/le.xmp"), &le);
|
||||
write(&base.join("main/bad.xmp"), &[0xFF, 0xFE, 0x00]);
|
||||
let mut s = Session::new();
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var x = new XMPFile(File('le.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ);\n\
|
||||
var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, x.getPacketInfo().charForm];\n\
|
||||
try { new XMPFile(File('bad.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); } catch (e) { out.push(e.message); } vc.log(out);",
|
||||
);
|
||||
assert_eq!(log[0], json!(["image/svg+xml", 3, "Script file cannot be decoded"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A `File` open on a UTF-16 sidecar reads the UTF-8 packet `closeFile()` wrote, from the start.
|
||||
#[test]
|
||||
fn an_open_utf16_file_reads_the_written_packet() {
|
||||
let base = folder("utf16open");
|
||||
let mut s = with_data(&base);
|
||||
let d = logged(&mut s, &base, "vc.log(Folder.userData.fsName);");
|
||||
let d = PathBuf::from(d[0].as_str().unwrap());
|
||||
let mut le = vec![0xFF, 0xFE];
|
||||
le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes));
|
||||
write(&d.join("u.xmp"), &le);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = Folder.userData.fsName + '/u.xmp'; var f = new File(p); f.open('r'); var out = [f.encoding, f.read(5)];\n\
|
||||
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\
|
||||
m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\
|
||||
var t = f.read(), e = f.encoding; f.close(); out.push(e, t.slice(0, 9), t.indexOf('<dc:format>changed</dc:format>') > 0); vc.log(out);",
|
||||
);
|
||||
assert_eq!(log[0], json!(["UTF-16LE", "<?xpa", "UTF-8", "<?xpacket", true]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_a_utf16_declared_packet_keeps_its_body_in_utf8() {
|
||||
let base = folder("utf16declaredwrite");
|
||||
let mut session = with_data(&base);
|
||||
let data = logged(&mut session, &base, "vc.log(Folder.userData.fsName);");
|
||||
let data = PathBuf::from(data[0].as_str().unwrap());
|
||||
let body = format!("<!-- retained prolog -->\n{PACKET}\n<!-- retained epilog -->");
|
||||
let packet = format!("<?xml version='1.0' encoding='UTF-16'?>{body}");
|
||||
let mut bytes = vec![0xFF, 0xFE];
|
||||
bytes.extend(packet.encode_utf16().flat_map(u16::to_le_bytes));
|
||||
write(&data.join("declared.xmp"), &bytes);
|
||||
logged(
|
||||
&mut session,
|
||||
&base,
|
||||
"var x = new XMPFile(Folder.userData.fsName + '/declared.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var packet = x.getPacketInfo().packet; x.putXMP(packet); x.closeFile();",
|
||||
);
|
||||
let written = std::fs::read_to_string(data.join("declared.xmp")).unwrap();
|
||||
assert_eq!(written, body);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_xmp_update_resets_bom_readers_and_keeps_unmarked_reader_positions() {
|
||||
for bom in [true, false] {
|
||||
let base = folder(if bom { "utf8bomopen" } else { "utf8open" });
|
||||
let mut session = with_data(&base);
|
||||
let data = logged(&mut session, &base, "vc.log(Folder.userData.fsName);");
|
||||
let data = PathBuf::from(data[0].as_str().unwrap());
|
||||
let mut bytes = if bom { vec![0xEF, 0xBB, 0xBF] } else { Vec::new() };
|
||||
bytes.extend_from_slice(PACKET.as_bytes());
|
||||
write(&data.join("u.xmp"), &bytes);
|
||||
let log = logged(
|
||||
&mut session,
|
||||
&base,
|
||||
&format!(
|
||||
"var p = Folder.userData.fsName + '/u.xmp', f = new File(p); f.open('r');\n\
|
||||
if (!{bom}) f.read(3); var before = f.tell();\n\
|
||||
var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE), m = x.getXMP();\n\
|
||||
m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\
|
||||
var after = f.tell(), text = f.read(); f.close(); vc.log([before, after, text.slice(0, 9)]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(log[0], if bom { json!([3, 0, "<?xpacket"]) } else { json!([3, 3, "packet be"]) });
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens that cannot take a packet need no write grant, even with `OPEN_FOR_UPDATE`: a scanned
|
||||
/// sidecar and another kind of file in the script's own folder open read only.
|
||||
#[test]
|
||||
fn read_only_opens_need_no_write_grant() {
|
||||
let base = folder("readonly");
|
||||
write(&base.join("main/ok.xmp"), PACKET.as_bytes());
|
||||
write(&base.join("main/art.txt"), PACKET.as_bytes());
|
||||
let mut s = Session::new();
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var u = XMPConst.OPEN_FOR_UPDATE, out = [];\n\
|
||||
[[File('ok.xmp').fsName, u | XMPConst.OPEN_USE_PACKET_SCANNING], [File('art.txt').fsName, u]].forEach(function (a) {\n\
|
||||
var x = new XMPFile(a[0], XMPConst.FILE_UNKNOWN, a[1]); var m = x.getXMP();\n\
|
||||
out.push(m.getProperty(XMPConst.NS_DC, 'format').value, x.canPutXMP(m)); x.closeFile();\n\
|
||||
}); vc.log(out);",
|
||||
);
|
||||
assert_eq!(log[0], json!(["image/svg+xml", false, "image/svg+xml", false]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A sidecar larger than a script may read is refused before it is read.
|
||||
#[test]
|
||||
fn a_huge_sidecar_is_refused_before_it_is_read() {
|
||||
let base = folder("huge");
|
||||
let file = std::fs::File::create(base.join("main/big.xmp")).unwrap();
|
||||
file.set_len(9 << 20).unwrap();
|
||||
drop(file);
|
||||
let mut s = Session::new();
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"try { new XMPFile(File('big.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); vc.log('read'); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(log, json!(["Script file exceeds 8 MiB"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The file named `name` in `dir` or a folder inside it.
|
||||
fn find_file(dir: &Path, name: &str) -> Option<PathBuf> {
|
||||
for entry in std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()) {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
if let Some(found) = find_file(&path, name) {
|
||||
return Some(found);
|
||||
}
|
||||
} else if entry.file_name() == name {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A write that fails leaves the sidecar as it was and the `XMPFile` open with its packet, so a
|
||||
/// later `closeFile` of the same object writes it.
|
||||
#[test]
|
||||
fn a_failed_write_keeps_the_packet_for_a_later_close() {
|
||||
let base = folder("fails");
|
||||
let mut s = with_data(&base);
|
||||
crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true));
|
||||
start_framed(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var p = Folder.userData.fsName + '/k.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
|
||||
var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = kept.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(m);\n\
|
||||
var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\
|
||||
File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out); vc.log(p);"
|
||||
),
|
||||
);
|
||||
let paused = pump_to_picker(&mut s);
|
||||
crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false));
|
||||
assert!(paused.is_none(), "the run waits at the dialog: {paused:?}");
|
||||
let path = find_file(&base.join("settings"), "k.xmp").unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), PACKET, "the failed write leaves the file as it was");
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Deny));
|
||||
let r = pump_to_picker(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"][0], json!(["Script file could not be written", "changed", "closed"]));
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"), "the same XMPFile writes on its next close");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_directory_flush_failure_keeps_the_written_packet_and_allows_retry() {
|
||||
struct Reset;
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
}
|
||||
}
|
||||
let _reset = Reset;
|
||||
let base = folder("directory-flush");
|
||||
let mut session = with_data(&base);
|
||||
let dir = logged(&mut session, &base, "vc.log(Folder.userData.fsName);");
|
||||
let path = PathBuf::from(dir[0].as_str().unwrap()).join("packet.xmp");
|
||||
write(&path, format!("\u{FEFF}{PACKET}").as_bytes());
|
||||
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
|
||||
start_framed(
|
||||
&mut session,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var p = {:?}, reader = new File(p); reader.open('r'); reader.read(7);\n\
|
||||
var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var meta = kept.getXMP(); meta.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(meta);\n\
|
||||
var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\
|
||||
out.push(reader.tell() === 0, reader.read().indexOf('changed') >= 0); reader.close();\n\
|
||||
File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out);",
|
||||
path.to_string_lossy()
|
||||
),
|
||||
);
|
||||
let paused = pump_to_picker(&mut session);
|
||||
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
|
||||
assert!(paused.is_none(), "the run waits before retrying: {paused:?}");
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"), "the replacement already wrote the packet");
|
||||
assert!(session.script_pick(crate::script::files::PickAnswer::Deny));
|
||||
let report = pump_to_picker(&mut session).unwrap().unwrap();
|
||||
assert_eq!(report["log"][0], json!(["Script file could not be written", "changed", true, true, "closed"]));
|
||||
assert_eq!(report["written"], json!([path.to_string_lossy()]), "the written replacement is reported once");
|
||||
}
|
||||
|
||||
/// An `XMPFile` from an earlier run of a named engine is closed.
|
||||
#[test]
|
||||
fn an_xmp_file_from_an_earlier_run_is_closed() {
|
||||
let base = folder("earlier");
|
||||
let mut s = with_data(&base);
|
||||
let engine = |text: &str| format!("#targetengine xmp\n{LOAD}{text}");
|
||||
let main = base.join("main/main.jsx");
|
||||
write(&main, engine(&format!("var f = new File(Folder.userData.fsName + '/k2.xmp'); f.open('w'); f.write({PACKET:?}); f.close();")).as_bytes());
|
||||
s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
write(
|
||||
&main,
|
||||
engine("$.global.kept = new XMPFile(Folder.userData.fsName + '/k2.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);").as_bytes(),
|
||||
);
|
||||
s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
write(&main, engine("try { kept.getXMP(); vc.log('open'); } catch (e) { vc.log(e.message); }").as_bytes());
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["log"], json!(["XMPFile.getXMP: the file is closed"]), "an XMPFile from an earlier run is closed");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The temporary file a sidecar is replaced through is readable by its owner alone while the
|
||||
/// packet is written to it, and the sidecar keeps its own permission bits.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_temporary_file_starts_private() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let base = folder("private");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
|
||||
);
|
||||
let path = PathBuf::from(log[0].as_str().unwrap());
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
crate::script::files::XMP_TEMP_MODE.with(|m| m.set(None));
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
|
||||
);
|
||||
assert_eq!(crate::script::files::XMP_TEMP_MODE.with(std::cell::Cell::get).map(|m| m & 0o777), Some(0o600));
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named
|
||||
/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.)
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_replaced_sidecar_takes_no_inherited_acl() {
|
||||
let base = folder("acl");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"),
|
||||
);
|
||||
let path = PathBuf::from(log[0].as_str().unwrap());
|
||||
let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status();
|
||||
if !set.is_ok_and(|s| s.success()) {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();",
|
||||
);
|
||||
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"));
|
||||
let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap();
|
||||
let acl = String::from_utf8_lossy(&acl.stdout);
|
||||
assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A packet argument whose conversion closes the `XMPFile` leaves it closed: `canPutXMP` and
|
||||
/// `putXMP` throw that the file is closed, and nothing is written.
|
||||
#[test]
|
||||
fn converting_the_packet_cannot_close_the_file() {
|
||||
let base = folder("reentrant");
|
||||
let mut s = with_data(&base);
|
||||
let log = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var p = Folder.userData.fsName + '/r.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\
|
||||
function closing(x) {{ var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); var s = m.serialize();\n\
|
||||
return {{ toString: function () {{ x.closeFile(); return s; }} }}; }}\n\
|
||||
var out = [], a = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
try {{ out.push(a.canPutXMP(closing(a))); }} catch (e) {{ out.push(e.message); }}\n\
|
||||
var b = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
try {{ b.putXMP(closing(b)); out.push('put'); }} catch (e) {{ out.push(e.message); }}\n\
|
||||
b.closeFile(); vc.log(out); vc.log(p);"
|
||||
),
|
||||
);
|
||||
assert_eq!(log[0], json!(["XMPFile.canPutXMP: the file is closed", "XMPFile.putXMP: the file is closed"]));
|
||||
assert_eq!(std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(), PACKET);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// With `CLOSE_UPDATE_SAFELY`, a sidecar whose folder takes no temporary file is left as it is and
|
||||
/// the `XMPFile` keeps its packet; a later `closeFile()` without the flag writes the file itself.
|
||||
#[test]
|
||||
fn a_safe_close_writes_only_through_a_temporary_file() {
|
||||
let base = folder("safely");
|
||||
let sidecar = base.join("picked/s.xmp");
|
||||
write(&sidecar, PACKET.as_bytes());
|
||||
let mut s = with_data(&base);
|
||||
start_framed(
|
||||
&mut s,
|
||||
&base,
|
||||
"var a = File.saveDialog('a');\n\
|
||||
var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
|
||||
var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\
|
||||
var out = []; try { x.closeFile(XMPConst.CLOSE_UPDATE_SAFELY); out.push('closed'); } catch (e) { out.push(e.message, x.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }\n\
|
||||
File.saveDialog('pause'); x.closeFile(); out.push('written'); vc.log(out);",
|
||||
);
|
||||
assert!(pump_to_picker(&mut s).is_none());
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![sidecar.to_string_lossy().into_owned()], always: false }));
|
||||
assert!(pump_to_picker(&mut s).is_none());
|
||||
assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET, "the safe close leaves the file as it was");
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Deny));
|
||||
let r = pump_to_picker(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([["Script file could not be written", "changed", "written"]]));
|
||||
assert!(std::fs::read_to_string(&sidecar).unwrap().contains("<dc:format>changed</dc:format>"));
|
||||
let names: Vec<String> = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(names, ["s.xmp"], "no other file is made");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -34,6 +34,39 @@ fn names(s: &mut Session) -> Vec<String> {
|
||||
const BLUR: &str = r#"<filter id="Soft"><feGaussianBlur stdDeviation="2"/></filter>"#;
|
||||
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3" dy="3"/></filter>"#;
|
||||
|
||||
#[test]
|
||||
fn byte_import_keeps_svg_encodings_and_uses_one_undo_step() {
|
||||
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg"><filter id="café"><feOffset dx="3"/></filter></svg>"#;
|
||||
let utf16: Vec<u8> = [0xff, 0xfe].into_iter().chain(svg.encode_utf16().flat_map(u16::to_le_bytes)).collect();
|
||||
let latin1: Vec<u8> = format!("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>{svg}").chars().map(|c| c as u8).collect();
|
||||
for bytes in [svg.as_bytes().to_vec(), utf16, latin1] {
|
||||
let mut s = session();
|
||||
let out = run(&mut s, "svgFilter.import", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)}));
|
||||
assert_eq!(out["added"], json!(["café"]));
|
||||
assert_eq!(names(&mut s), ["café"]);
|
||||
assert_eq!(steps(&s), 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(names(&mut s).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_import_refuses_invalid_oversized_and_compressed_files_without_an_edit() {
|
||||
let mut s = session();
|
||||
assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": "!"})).contains("dataBase64"));
|
||||
assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": 3})).contains("must be a string"));
|
||||
let mut inline = "é".repeat(8 << 20);
|
||||
inline.push(' ');
|
||||
assert!(err(&mut s, "svgFilter.import", json!({"svg": inline})).contains("larger than 16777216 bytes"));
|
||||
assert!(names(&mut s).is_empty());
|
||||
assert_eq!(steps(&s), 0);
|
||||
for bytes in [vec![0xff], vec![b' '; (16 << 20) + 1], vectorcraft_svg::compress("<svg/>")] {
|
||||
assert!(s.execute("svgFilter.import", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})).is_err());
|
||||
assert!(names(&mut s).is_empty());
|
||||
assert_eq!(steps(&s), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_are_defined_edited_and_deleted_in_one_undo_step_each() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"),
|
||||
("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"),
|
||||
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
|
||||
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
|
||||
];
|
||||
|
||||
/// The names the host adds that stay inside the document and the run, by the object that has them.
|
||||
@@ -50,6 +51,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="),
|
||||
("localize.", "length"),
|
||||
("toSource.", "length"),
|
||||
("ExternalObject.", "length prototype search"),
|
||||
("ExternalObject.prototype.", "constructor terminate"),
|
||||
(
|
||||
"$.",
|
||||
"about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \
|
||||
|
||||
@@ -1014,6 +1014,17 @@ pub(super) fn paints_apart(look: &Node) -> bool {
|
||||
}
|
||||
let mut paths = vec![];
|
||||
leaves(look, &mut paths);
|
||||
// A gradient or pattern instance (`Bb … BB`) wraps only the last path of a compound path, the paths before it
|
||||
// keep the default paint: many paths alike, then one that paints with a gradient, are one compound path's
|
||||
// subpaths and its paint (see `compound`), not several paints.
|
||||
if let [rest @ .., last] = paths.as_slice()
|
||||
&& rest.len() >= 2
|
||||
&& rest.windows(2).all(|w| matches!(w, [a, b] if a.appearance == b.appearance))
|
||||
&& last.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. }))
|
||||
&& rest.iter().all(|p| p.appearance.items.iter().all(|i| !matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. })))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
paths.windows(2).any(|w| matches!(w, [a, b] if a.appearance != b.appearance))
|
||||
}
|
||||
|
||||
|
||||
@@ -1789,6 +1789,22 @@ fn compound_path_takes_its_last_paths_paint() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_whose_last_path_has_the_gradient_is_one_gradient_filled_compound_path() {
|
||||
// GUARDS: a gradient instance wraps only the last path of a compound path (a sunburst's rays), the paths before it
|
||||
// keep the default fill. Read as a drawn look whose paths paint apart, each ray but the last became a plain black
|
||||
// path and only the last one took the gradient.
|
||||
let defs = "%AI5_BeginGradient: (Lin)\n(Lin) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
|
||||
let instance = "Bb\n1 (Lin) 0 0 0 1 1 0 0 1 0 0 1 Bg\n10 0 10 10 100 50 Xm\nf\n0 BB\n";
|
||||
let rays: String = (0..3).map(|i| format!("0 g\n{}f\n", rect_path(f64::from(i) * 30.0, 0.0, f64::from(i) * 30.0 + 20.0, 20.0))).collect();
|
||||
let art_ = format!("0 Ae\n*u\n0 Ae\nu\n{rays}{}{instance}U\n9 () XW\n*U\n", rect_path(100.0, 0.0, 120.0, 20.0));
|
||||
let a = art(&read_ok(&format!("{defs}{}", layer(&art_))).doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
let NodeKind::Compound { children, .. } = &a[0].kind else { panic!("{:#?}", a[0].kind) };
|
||||
assert_eq!(children.len(), 4, "every ray is a subpath of the compound path");
|
||||
assert!(matches!(fill(&a[0]), Paint::Gradient(_)), "{:?}", fill(&a[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_whose_state_has_no_transparency_takes_the_current_one() {
|
||||
// GUARDS: a group's own state block keeps the last `Xy`, as the PDF part draws it; a drawn look's group stays opaque.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::build::Frame;
|
||||
use super::slots::OUTLINE_REACH;
|
||||
use super::slots::{OUTLINE_REACH, drawn_box};
|
||||
use super::{Arc, Document, Node, NodeKind, Rect};
|
||||
|
||||
/// `doc` with its layers that don't print hidden, when it has any.
|
||||
@@ -756,12 +756,14 @@ fn differing_pixels(
|
||||
}
|
||||
|
||||
/// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin
|
||||
/// for the strokes round it). The type in a live envelope isn't: the envelope draws it bent, away
|
||||
/// from its text object's box, and is weighed as the art it draws, as its drawn art would be.
|
||||
/// for the strokes round it): where it draws ([`drawn_box`]), so that type made from the text
|
||||
/// document that differs from the page's counts as type whatever its alignment. The type in a
|
||||
/// live envelope isn't: the envelope draws it bent, away from its text object's box, and is
|
||||
/// weighed as the art it draws, as its drawn art would be.
|
||||
fn type_areas(nodes: &[Arc<Node>], region: Rect, scale: f64, out: &mut Vec<Rect>) {
|
||||
for n in nodes.iter().filter(|n| n.visible) {
|
||||
if let NodeKind::Text(_) = n.kind
|
||||
&& let Some(b) = n.visual_bounds()
|
||||
&& let Some(b) = drawn_box(n)
|
||||
{
|
||||
let px =
|
||||
|r: Rect| Rect::new((r.x0 - region.x0) * scale, (r.y0 - region.y0) * scale, (r.x1 - region.x0) * scale, (r.y1 - region.y0) * scale);
|
||||
@@ -780,7 +782,7 @@ fn all_type_areas(nodes: &[Arc<Node>], region: Rect, scale: f64, out: &mut Vec<R
|
||||
for n in nodes {
|
||||
let placed = matches!(&n.kind, NodeKind::Image(im) if im.link.is_some());
|
||||
if (placed || matches!(n.kind, NodeKind::Text(_)))
|
||||
&& let Some(b) = n.visual_bounds()
|
||||
&& let Some(b) = drawn_box(n)
|
||||
{
|
||||
let b = b.inflate(OUTLINE_REACH, OUTLINE_REACH);
|
||||
out.push(Rect::new((b.x0 - region.x0) * scale, (b.y0 - region.y0) * scale, (b.x1 - region.x0) * scale, (b.y1 - region.y0) * scale));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::layers::closed_where_ends_meet;
|
||||
use super::slots::{
|
||||
Content, MAX_PAIRS, OUTLINE_REACH, PAGE_TYPE_LEFT_OUT, PAGE_TYPE_UNCHECKED, SlotInfo, assign, covered, extent, join_pieces, letters, same_type,
|
||||
word_pieces, words,
|
||||
Content, MAX_PAIRS, OUTLINE_REACH, PAGE_TYPE_LEFT_OUT, PAGE_TYPE_UNCHECKED, SlotInfo, assign, covered, drawn_box, extent, join_pieces, letters,
|
||||
same_type, word_pieces, words,
|
||||
};
|
||||
use super::{Affine, Arc, Node, NodeId, NodeKind, Point, Rect, Story, TextKind};
|
||||
|
||||
@@ -145,7 +145,8 @@ pub(super) fn made_only(
|
||||
warn: &mut Vec<String>,
|
||||
) -> Vec<Content> {
|
||||
let [shown, hidden] = pages;
|
||||
let mut content = made_content(infos, made);
|
||||
// Every text object that shows has made type: each is matched with the page's type where it draws.
|
||||
let mut content = made_content(infos, made, true);
|
||||
// The page's type where no made type draws, in the copies that looks draw, is theirs (past
|
||||
// `MAX_PAIRS` comparisons it isn't looked for).
|
||||
let looks = infos.iter().any(|i| i.shown && i.look.is_some());
|
||||
@@ -315,15 +316,18 @@ fn object_words(o: &[Arc<Node>]) -> Vec<String> {
|
||||
}
|
||||
|
||||
/// Each slot's made type as its content, else nothing yet. Made type that shows has where it draws,
|
||||
/// or where its story lies when it draws nothing.
|
||||
fn made_content(infos: &[SlotInfo], made: Vec<Option<Made>>) -> Vec<Content> {
|
||||
/// or where its story lies when it draws nothing. `laid`: point type is laid out for its box
|
||||
/// ([`drawn_box`]); without it the box is that of type without a layout, as it always was.
|
||||
fn made_content(infos: &[SlotInfo], made: Vec<Option<Made>>, laid: bool) -> Vec<Content> {
|
||||
infos
|
||||
.iter()
|
||||
.zip(made)
|
||||
.map(|(info, m)| match m {
|
||||
Some((node, region)) => {
|
||||
let drawn = node.visual_bounds().filter(|b| !b.is_zero_area()).or(region);
|
||||
Content::Made(node, drawn.filter(|_| info.shown), false)
|
||||
// Type that doesn't show has no region: it isn't laid out for one.
|
||||
let own = || if laid { drawn_box(&node) } else { node.visual_bounds() };
|
||||
let drawn = info.shown.then(|| own().filter(|b| !b.is_zero_area() && b.is_finite()).or(region)).flatten();
|
||||
Content::Made(node, drawn, false)
|
||||
}
|
||||
None => Content::Empty,
|
||||
})
|
||||
@@ -391,8 +395,11 @@ pub(super) fn plan(
|
||||
// Where the made type that doesn't show lies, by slot.
|
||||
let hidden_at: Vec<(usize, Rect)> =
|
||||
infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect();
|
||||
// Type the text document makes, shown or not: the page's pieces of it aren't needed.
|
||||
let mut content = made_content(infos, made);
|
||||
// Type the text document makes, shown or not: the page's pieces of it aren't needed. Its box
|
||||
// stays that of type without a layout here: with text objects whose type isn't made stacked on
|
||||
// made type that has their words (the copies of an outlined heading), the page's pieces in the
|
||||
// box where the made type draws are theirs too, and the made type would take them all.
|
||||
let mut content = made_content(infos, made, false);
|
||||
// Is `object` the type of a text object that doesn't show, as the page draws it: in its frame,
|
||||
// with its words? (A copied object's lines are where its original's are, so they don't say.)
|
||||
let hidden_type = |object: &[Arc<Node>]| {
|
||||
|
||||
@@ -610,10 +610,64 @@ pub(super) fn extent(parts: &[Arc<Node>]) -> Option<Rect> {
|
||||
parts.iter().filter_map(|n| n.visual_bounds()).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// Where a text object draws: its visual box, point type that has no layout laid out first, in
|
||||
/// the fonts the import has ([`vectorcraft_text::FontDb::global`]), so the box depends on which
|
||||
/// fonts are installed, as the opened document's does. Any point type without a layout is laid
|
||||
/// out, not only type made from the file's text document, which is the type that has none during
|
||||
/// the import (the page's own type is measured when it is read). Without a layout the box of point
|
||||
/// type is an estimate that runs right from its anchor
|
||||
/// ([`vectorcraft_doc::TextObject::estimate_bounds`]): beside where right-aligned type draws, over
|
||||
/// one half of centered type, across vertical type, and as wide as an average font would set it,
|
||||
/// which can be wider than the type is. The node keeps no layout: the document's type is measured
|
||||
/// when it opens. Any other object's box is its visual box.
|
||||
///
|
||||
/// `made_only` matches made type with the page's type by this box; `plan` doesn't match by it yet.
|
||||
/// The page comparison's type areas use it for every file's layers, those `plan` fills included.
|
||||
pub(super) fn drawn_box(node: &Node) -> Option<Rect> {
|
||||
if let NodeKind::Text(t) = &node.kind
|
||||
&& matches!(t.kind, vectorcraft_doc::TextKind::Point)
|
||||
&& t.cached_bounds.is_none()
|
||||
{
|
||||
let mut laid = node.clone();
|
||||
if let NodeKind::Text(t) = &mut laid.kind {
|
||||
t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).bounds);
|
||||
}
|
||||
return laid.visual_bounds();
|
||||
}
|
||||
node.visual_bounds()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Made point type's box is where its alignment and orientation draw it: right-aligned type
|
||||
/// before its anchor, centered type round it, vertical type down from it. Its node keeps no
|
||||
/// layout.
|
||||
#[test]
|
||||
fn made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it() {
|
||||
use vectorcraft_doc::{CharStyle, Justify, TextObject};
|
||||
let anchor = 300.0;
|
||||
let boxed = |justify: Justify, vertical: bool| {
|
||||
let mut t = TextObject::point(Point::new(anchor, 200.0), "Wide heading", CharStyle { size: 40.0, ..CharStyle::default() });
|
||||
t.para.justify = justify;
|
||||
for p in t.para_styles_mut() {
|
||||
p.justify = justify;
|
||||
}
|
||||
t.vertical = vertical;
|
||||
let node = Node::new(NodeId(1), NodeKind::Text(Box::new(t)));
|
||||
let b = drawn_box(&node).unwrap();
|
||||
assert!(matches!(&node.kind, NodeKind::Text(t) if t.cached_bounds.is_none()));
|
||||
b
|
||||
};
|
||||
let (left, right, centered, down) =
|
||||
(boxed(Justify::Left, false), boxed(Justify::Right, false), boxed(Justify::Center, false), boxed(Justify::Left, true));
|
||||
assert!(left.x0 > anchor - 20.0 && left.width() > 100.0, "{left:?}");
|
||||
assert!(right.x1 < anchor + 20.0 && (right.width() - left.width()).abs() < 1.0, "{right:?}");
|
||||
assert!((centered.center().x - anchor).abs() < 20.0 && (centered.width() - left.width()).abs() < 1.0, "{centered:?}");
|
||||
assert!(down.height() > 2.0 * down.width() && down.height() > 100.0, "{down:?}");
|
||||
}
|
||||
|
||||
/// Past the limits, the slots of type that looks draw go, in groups too, and other slots stay.
|
||||
#[test]
|
||||
fn look_type_slots_are_dropped_from_groups() {
|
||||
|
||||
@@ -5509,6 +5509,66 @@ fn a_small_label_of_the_page_in_no_text_object_is_noted() {
|
||||
assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// Point type that isn't aligned left is matched with the page's type where it draws: right-aligned
|
||||
/// type ends at its anchor and centered type lies round it, so the page's type there is theirs and
|
||||
/// nothing is noted as left out. (The box of type that isn't laid out yet runs right from its
|
||||
/// anchor, past the page's type.)
|
||||
#[test]
|
||||
fn right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws() {
|
||||
// "Hi there" in 14 point Helvetica is about 49 points wide. The anchors are 90 and 50 across the
|
||||
// art; the page draws the line so that it ends at the first and lies round the second.
|
||||
for (align, anchor, at) in [(1, 8231.5, 41.0), (2, 8191.5, 25.5)] {
|
||||
let doc = text_document(&[("Hi there\r", align, (anchor, 8180.0), (0.0, 0.0), 0.0)]);
|
||||
let art = native_with_text(&layer("Art", true, &text_object(0)), &doc);
|
||||
let page = format!("0 1 0 0 setcmykcolor /Helvetica findfont 14 scalefont setfont {at} 61.5 moveto (Hi there) show");
|
||||
let r = import(&eps(&page, &art)).unwrap();
|
||||
assert_eq!(names(&r.document), ["Art"], "{align}: {:?}", r.warnings);
|
||||
let texts: Vec<String> = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect();
|
||||
assert_eq!(texts, ["Hi there"], "{align}: {:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{align}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// Centered point type at a heading's size, set tight, is matched with the page's type where it
|
||||
/// draws, round its anchor. (The box of type that isn't laid out yet runs right from the anchor and
|
||||
/// holds the right half of the line; with a leading under the type's size it ends at the baseline,
|
||||
/// so it holds less than the half of the page's type the match needs. At 14 points the 6 points
|
||||
/// round the box make up for it.)
|
||||
#[test]
|
||||
fn centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws() {
|
||||
// A 500 × 150 artboard, its centre (250, 75) the canvas centre 8191.5. "Hi there, hi" in 72 point
|
||||
// Helvetica on a 58 point leading is about 348 points wide; its anchor is the artboard's middle,
|
||||
// 86.5 points up.
|
||||
let doc = text_document(&[("Hi there, hi\r", 2, (8191.5, 8180.0), (0.0, 0.0), 0.0)]).replacen("/1 14.0 /53", "/1 72.0 /4 false /5 58.0 /53", 1);
|
||||
let art = native_with_text(&layer("Art", true, &text_object(0)), &doc).replace("0 0 100 100", "0 0 500 150").replacen(
|
||||
"%AI3_TemplateBox: 50 50 50 50",
|
||||
"%AI3_TemplateBox: 250 75 250 75",
|
||||
1,
|
||||
);
|
||||
let page = "0 1 0 0 setcmykcolor /Helvetica findfont 72 scalefont setfont 76 86.5 moveto (Hi there, hi) show";
|
||||
let file = String::from_utf8(eps(page, &art)).unwrap().replacen("%%BoundingBox: 0 0 100 100", "%%BoundingBox: 0 0 500 150", 1);
|
||||
let r = import(file.as_bytes()).unwrap();
|
||||
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
|
||||
let texts: Vec<String> = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect();
|
||||
assert_eq!(texts, ["Hi there, hi"], "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// Right-aligned point type that the page draws in another colour differs from the page as type,
|
||||
/// where it draws, before its anchor: the layers are read and the note says the type differs.
|
||||
/// (Counted as art, away from the box of type that isn't laid out, it sent the file to its page.)
|
||||
#[test]
|
||||
fn right_aligned_point_type_that_differs_from_the_page_differs_as_type() {
|
||||
let doc = text_document(&[("Hi there\r", 1, (8231.5, 8180.0), (0.0, 0.0), 0.0)]);
|
||||
let art = native_with_text(&layer("Art", true, &text_object(0)), &doc);
|
||||
// The text document's type is magenta; the page draws it black, ending at the anchor.
|
||||
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 41 61.5 moveto (Hi there) show";
|
||||
let r = import(&eps(page, &art)).unwrap();
|
||||
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
|
||||
assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs from the file's own page")), "{:?}", r.warnings);
|
||||
assert!(!r.warnings.iter().any(|w| w.starts_with("the art on the layers differs")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A ligature the page shows by a glyph its font's encoding names `uniE028` (a private-use
|
||||
/// character, without the letters it stands for) is the letters of its text object: the page's type
|
||||
/// has one, and nothing is noted as left out.
|
||||
|
||||
@@ -347,9 +347,10 @@ fn temp_path(target: &Path) -> io::Result<PathBuf> {
|
||||
/// mode bits mean other people when the group differs, and an ACL can narrow who reads the file.
|
||||
/// When the group or the ACL can't be kept, the replacement is readable by its owner alone rather
|
||||
/// than by people the old file didn't let in. (Unix; Windows files have none to keep beyond
|
||||
/// read-only, which makes the save fail as writing in place would.)
|
||||
/// read-only, which makes the save fail as writing in place would.) `tmp` is the file that is about
|
||||
/// to replace `target`.
|
||||
#[cfg(unix)]
|
||||
fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> {
|
||||
pub fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> {
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
// A new file: the default permissions.
|
||||
let Ok(m) = std::fs::metadata(target) else { return Ok(()) };
|
||||
@@ -385,8 +386,9 @@ fn keep_acl(_: &Path, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Windows files have no permissions to keep beyond read-only (see the Unix version).
|
||||
#[cfg(not(unix))]
|
||||
fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> {
|
||||
pub fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob};
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
pub use atomic::sync_parent;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
use craft_gzip::Gz;
|
||||
pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode};
|
||||
use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json};
|
||||
|
||||
@@ -11,6 +11,8 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
chrono = { workspace = true }
|
||||
# The XMP packets of XMPMeta and XMPFile (xmp.rs).
|
||||
craft-xml = { workspace = true }
|
||||
# Unicode 17.0 general categories for identifiers (chars.rs). 0.1.5 adds the Unicode-3.0 license,
|
||||
# which is not on the license allowlist, so the version is exact.
|
||||
unicode-properties = { version = "=0.1.4", default-features = false, features = ["general-category"] }
|
||||
|
||||
@@ -135,6 +135,29 @@ fn parse_text(i: &mut Interp, text: Value, platform: bool) -> JsResult<Value> {
|
||||
host(i, "parse", &[text, current, Value::Bool(platform)])
|
||||
}
|
||||
|
||||
/// The platform path `x` names, as `File(x).fsName` gives it: for `XMPFile`
|
||||
/// ([`crate::xmp_classes`]).
|
||||
pub(crate) fn platform_path(i: &mut Interp, x: &Value) -> JsResult<Value> {
|
||||
let p = parse(i, x)?;
|
||||
i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))
|
||||
}
|
||||
|
||||
/// Calls the host function `name` with `args`, as `File` and `Folder` call theirs: for `XMPFile`.
|
||||
pub(crate) fn call_host(i: &mut Interp, name: &str, args: &[Value]) -> JsResult<Value> {
|
||||
host(i, name, args)
|
||||
}
|
||||
|
||||
/// The field `name` of a record a host function gave ([`field`]): for `XMPFile`.
|
||||
pub(crate) fn record_field(i: &mut Interp, v: &Value, name: &str) -> JsResult<Value> {
|
||||
field(i, v, name)
|
||||
}
|
||||
|
||||
/// The count of runs the realm has begun since `File` and `Folder` were added, or `None` without
|
||||
/// them: an `XMPFile` is open only in the run that opened it.
|
||||
pub(crate) fn run_count(i: &Interp) -> Option<f64> {
|
||||
i.files.as_ref().map(|c| c.run)
|
||||
}
|
||||
|
||||
fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult<Value> {
|
||||
let (_, path) = this_path(i, this, what)?;
|
||||
let p = parse_text(i, path, true)?;
|
||||
@@ -1094,6 +1117,7 @@ fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> {
|
||||
pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> {
|
||||
let Some(c) = i.files.as_mut() else { return Ok(()) };
|
||||
c.run += 1.0;
|
||||
i.heap.reset_xmp_files();
|
||||
let start = host(i, "current", &[])?;
|
||||
if let Some(c) = i.files.as_mut() {
|
||||
c.current = start;
|
||||
@@ -1101,6 +1125,31 @@ pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod xmp_run_tests {
|
||||
use super::*;
|
||||
use crate::heap::PropMap;
|
||||
|
||||
#[test]
|
||||
fn a_failed_folder_reset_releases_native_xmp_buffers() {
|
||||
let mut interp = Interp::new(crate::Options::default(), crate::Limits::default());
|
||||
let host = interp.heap.alloc_object(Object::new(Class::Ordinary, None));
|
||||
interp.files = Some(Classes { file_proto: host, folder_proto: host, host, current: Value::str("start"), run: 0.0 });
|
||||
let mut fields = PropMap::default();
|
||||
fields.insert(key("__vcXmpPacket"), Value::str("packet"));
|
||||
fields.insert(key("__vcXmpPending"), Value::str("pending"));
|
||||
fields.insert(key("__vcXmpPath"), Value::str("kept.xmp"));
|
||||
let file = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None));
|
||||
let result = interp.rooted(&[Value::Object(file)], reset_current);
|
||||
assert!(result.is_err(), "the host has no current function");
|
||||
assert_eq!(run_count(&interp), Some(1.0));
|
||||
let Class::XmpFile(fields) = &interp.heap.object(file).unwrap().class else { panic!("native file") };
|
||||
assert!(matches!(fields.get(&key("__vcXmpPacket")), Some(Value::Null)));
|
||||
assert!(matches!(fields.get(&key("__vcXmpPending")), Some(Value::Undefined)));
|
||||
assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `File` and `Folder` to the global object, their work done by the host functions in
|
||||
/// `items` ([`crate::Realm::define_file_classes`]).
|
||||
pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> {
|
||||
|
||||
+45
-1
@@ -268,6 +268,10 @@ pub(crate) enum Class {
|
||||
},
|
||||
/// A `.( )` filter in progress.
|
||||
XmlFilter(Box<XmlFilterState>),
|
||||
/// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]).
|
||||
Xmp(Box<crate::xmp::Meta>),
|
||||
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
|
||||
XmpFile(Box<PropMap<Value>>),
|
||||
/// An object of a class a host defined ([`crate::host_classes`]).
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
@@ -339,7 +343,7 @@ impl Class {
|
||||
Class::XmlList(_) => "XMLList",
|
||||
Class::Namespace(_) => "Namespace",
|
||||
Class::QName { .. } => "QName",
|
||||
Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object",
|
||||
Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object",
|
||||
Class::Promise(_) => "Promise",
|
||||
Class::Math => "Math",
|
||||
Class::Json => "JSON",
|
||||
@@ -538,6 +542,16 @@ impl Heap {
|
||||
ids.filter_map(|(i, _)| u32::try_from(i).ok().map(ObjId)).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn reset_xmp_files(&mut self) {
|
||||
for cell in &mut self.cells {
|
||||
if let Cell::Object(object) = cell
|
||||
&& let Class::XmpFile(fields) = &mut object.class
|
||||
{
|
||||
crate::xmp_classes::reset_file_state(fields);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Live cells, for tests.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn live_cells(&self) -> usize {
|
||||
@@ -811,6 +825,14 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
work.extend(state.input.iter().chain(&state.kept).map(|o| o.0));
|
||||
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
|
||||
}
|
||||
Class::Xmp(meta) => extra = meta.heap_bytes(),
|
||||
Class::XmpFile(fields) => {
|
||||
for (name, value) in fields.iter() {
|
||||
strings.add_key(name);
|
||||
mark_value(value, work, strings);
|
||||
}
|
||||
extra = std::mem::size_of::<PropMap<Value>>() + PROP_BYTES * fields.len();
|
||||
}
|
||||
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
|
||||
Class::Promise(p) => {
|
||||
for v in p.values() {
|
||||
@@ -877,6 +899,28 @@ mod tests {
|
||||
assert_eq!(heap.bytes, OBJECT_BYTES + 2 * PROP_BYTES + string_bytes(1000) + string_bytes(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xmp_file_buffers_are_traced_and_released_at_the_file_run_boundary() {
|
||||
let mut heap = Heap::default();
|
||||
let pending = heap.alloc_object(Object::new(Class::Ordinary, None));
|
||||
let mut fields = PropMap::default();
|
||||
fields.insert(key("__vcXmpPacket"), Value::str(&"p".repeat(8192)));
|
||||
fields.insert(key("__vcXmpPending"), Value::Object(pending));
|
||||
fields.insert(key("__vcXmpPath"), Value::str("kept.xmp"));
|
||||
let file = heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None));
|
||||
let roots = Roots { objects: vec![file], ..Roots::default() };
|
||||
heap.collect(&roots);
|
||||
assert!(heap.object(pending).is_some(), "native values keep their objects reachable");
|
||||
let before = heap.bytes;
|
||||
assert!(before >= string_bytes(8192), "native packet strings count toward the heap limit");
|
||||
heap.reset_xmp_files();
|
||||
heap.collect(&roots);
|
||||
assert!(heap.object(pending).is_none(), "the prior run's pending value is released");
|
||||
assert!(before - heap.bytes >= string_bytes(8192), "the prior run's packet is released");
|
||||
let Class::XmpFile(fields) = &heap.object(file).unwrap().class else { panic!("native file") };
|
||||
assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prop_maps_keep_insertion_order_through_removals_and_growth() {
|
||||
let mut m = PropMap::default();
|
||||
|
||||
+43
-3
@@ -106,6 +106,7 @@ pub enum Arg {
|
||||
pub(crate) enum ArgRead {
|
||||
/// Each as [`Data`].
|
||||
Data,
|
||||
DataWithin(DataLimits),
|
||||
/// Each as [`Data`], with the result given frozen, as [`HostItem::Value`] gives its value.
|
||||
Frozen,
|
||||
/// Each as the string `String(value)` gives.
|
||||
@@ -126,6 +127,12 @@ pub enum HostItem {
|
||||
/// A read-only copy of a value.
|
||||
Value(Data),
|
||||
Function(HostFunction),
|
||||
/// A function whose explicit arguments use `limits`. The realm's other crossings keep their
|
||||
/// configured limits. The result uses the realm's limits.
|
||||
FunctionWithLimits {
|
||||
limits: DataLimits,
|
||||
function: HostFunction,
|
||||
},
|
||||
/// A function whose arguments arrive as strings, each the string `String(value)` gives.
|
||||
TextFunction(HostFunction),
|
||||
/// A function whose arguments arrive converted one by one as the list says. Arguments past the
|
||||
@@ -507,7 +514,10 @@ impl Interp {
|
||||
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
|
||||
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
|
||||
let mut reading = Reading {
|
||||
limits: self.data_limits,
|
||||
limits: match how {
|
||||
ArgRead::DataWithin(limits) => *limits,
|
||||
_ => self.data_limits,
|
||||
},
|
||||
bytes: 0,
|
||||
entries: 0,
|
||||
ancestors: Vec::new(),
|
||||
@@ -529,14 +539,14 @@ impl Interp {
|
||||
}
|
||||
// A conversion can run the script's own `toString`, which may collect garbage.
|
||||
let mark = self.temp_roots.len();
|
||||
if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) {
|
||||
if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Hosted) {
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
}
|
||||
let mut read = Ok(());
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX)));
|
||||
let d = match how {
|
||||
ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading),
|
||||
ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading),
|
||||
ArgRead::Text => self.read_text(a, &mut reading),
|
||||
ArgRead::Each(list) => match list.get(i) {
|
||||
Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined),
|
||||
@@ -666,6 +676,9 @@ impl Interp {
|
||||
},
|
||||
HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE },
|
||||
HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Data)), flags: ENUMERABLE },
|
||||
HostItem::FunctionWithLimits { limits, function } => {
|
||||
Prop::Data { value: Value::Object(self.host_function(function, &full, ArgRead::DataWithin(limits))), flags: ENUMERABLE }
|
||||
}
|
||||
HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Text)), flags: ENUMERABLE },
|
||||
HostItem::Converted(list, f) => {
|
||||
Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE }
|
||||
@@ -720,3 +733,30 @@ fn read_site(data: &[Data]) -> CallSite {
|
||||
};
|
||||
CallSite { source: at(0, crate::UNKNOWN_SOURCE), line: at(1, 0), column: at(2, 0) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod argument_limit_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_binding_argument_budget_does_not_change_other_crossings() {
|
||||
let mut realm = crate::Realm::with_options(crate::Options::default(), crate::Limits::default());
|
||||
let function: HostFunction = Rc::new(|_| Ok(Data::Bool(true)));
|
||||
realm
|
||||
.define_host_object(
|
||||
"h",
|
||||
vec![
|
||||
("normal".into(), HostItem::Function(function.clone())),
|
||||
("wide".into(), HostItem::FunctionWithLimits { limits: DataLimits { bytes: 64, ..DataLimits::default() }, function }),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
realm.set_data_limits(DataLimits { bytes: 16, ..DataLimits::default() });
|
||||
assert_eq!(realm.run("h.wide('abcdefgh')").unwrap(), crate::JsValue::Bool(true));
|
||||
assert_eq!(realm.run("try { h.normal('abcdefgh'); false } catch (e) { e instanceof RangeError }").unwrap(), crate::JsValue::Bool(true));
|
||||
assert_eq!(
|
||||
realm.run("try { h.wide('abcdefghijklmnopqrstuvwxyz'); false } catch (e) { e instanceof RangeError }").unwrap(),
|
||||
crate::JsValue::Bool(true)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -308,6 +308,9 @@ pub(crate) struct Interp {
|
||||
pub(crate) install_error: Option<String>,
|
||||
/// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]).
|
||||
pub(crate) files: Option<crate::file_classes::Classes>,
|
||||
/// `ExternalObject` and the XMP classes it loads, once a host has added them
|
||||
/// ([`crate::Realm::define_external_object`]).
|
||||
pub(crate) xmp: Option<crate::xmp_classes::Classes>,
|
||||
/// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them.
|
||||
pub(crate) host_classes: Vec<crate::host_classes::Entry>,
|
||||
/// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`].
|
||||
@@ -629,6 +632,7 @@ impl Interp {
|
||||
held_bytes: 0,
|
||||
install_error: None,
|
||||
files: None,
|
||||
xmp: None,
|
||||
host_classes: Vec::new(),
|
||||
write_hosted: false,
|
||||
host_objects: crate::host_classes::Made::default(),
|
||||
@@ -910,6 +914,7 @@ impl Interp {
|
||||
roots.objects.push(self.global);
|
||||
roots.objects.extend(self.intrinsics.all());
|
||||
roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects));
|
||||
roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects));
|
||||
roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects));
|
||||
roots.values.extend(self.symbols.root_values());
|
||||
roots.objects.extend(self.symbols.root_objects());
|
||||
@@ -938,6 +943,7 @@ impl Interp {
|
||||
.saturating_add(self.held_bytes)
|
||||
.saturating_add(self.held.now.get())
|
||||
.saturating_add(self.symbols.registry_bytes())
|
||||
.saturating_add(self.xmp.as_ref().map_or(0, crate::xmp_classes::Classes::bytes))
|
||||
.saturating_add(queued);
|
||||
}
|
||||
|
||||
|
||||
@@ -126,6 +126,8 @@ mod unit_value;
|
||||
mod value;
|
||||
mod xml;
|
||||
mod xml_builtins;
|
||||
mod xmp;
|
||||
mod xmp_classes;
|
||||
mod xpath;
|
||||
|
||||
pub use ast::{
|
||||
@@ -143,6 +145,7 @@ pub use realm::{
|
||||
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
|
||||
};
|
||||
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
|
||||
pub use xmp::{MAX_BYTES as XMP_MAX_BYTES, PacketSpan, find_packet as find_xmp_packet};
|
||||
|
||||
/// How a script is read.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -300,3 +303,5 @@ mod text_tests;
|
||||
mod unit_value_tests;
|
||||
#[cfg(test)]
|
||||
mod xml_tests;
|
||||
#[cfg(test)]
|
||||
mod xmp_tests;
|
||||
@@ -617,6 +617,23 @@ impl Realm {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the global `ExternalObject`. `new ExternalObject("lib:AdobeXMPScript")` defines the
|
||||
/// globals `XMPMeta`, `XMPFile` and `XMPConst`; any other library name throws. `XMPFile` reads
|
||||
/// and writes files through the host functions `xmpOpen` and `xmpWrite` of
|
||||
/// [`Realm::define_file_classes`], which the host adds first; without `File` and `Folder`,
|
||||
/// `XMPFile` throws. An `XMPFile` is open only in the run that opened it: each
|
||||
/// [`Realm::reset_folder_current`] begins a new run for it, and [`Realm::run`] and
|
||||
/// [`Realm::start`] do not. A successful close or a new file run releases its packet buffers.
|
||||
/// Registered namespace storage counts toward the realm's heap limit.
|
||||
/// After a successful installation, another call fails with an internal
|
||||
/// error and preserves `ExternalObject` and registered namespaces. A failed installation can be retried.
|
||||
pub fn define_external_object(&mut self) -> Result<(), RunError> {
|
||||
match crate::xmp_classes::install(&mut self.interp) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose
|
||||
/// prototype holds its members, and the global objects `instances`, each made from the
|
||||
/// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1096,7 +1096,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.colorPicker",
|
||||
"Color Picker…",
|
||||
"",
|
||||
"{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard",
|
||||
"{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard. Artboard preview and OK require the opening document to be active",
|
||||
),
|
||||
(
|
||||
"ui.sampleScreenColor",
|
||||
|
||||
@@ -370,38 +370,51 @@ fn long_page_warning(set: &PdfSettings, artboard: usize, w: f64, h: f64, unit: f
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGB colours and non-CMYK images a CMYK document carries, which the export separates into
|
||||
/// CMYK. Their darkest values come out as rich blacks, so the export says how many there are.
|
||||
/// The RGB colours and RGB images a CMYK document carries. Its RGB colours are always separated
|
||||
/// into CMYK; its RGB images only with a CMYK destination (Output › Color conversion, or a
|
||||
/// PDF/X-1a preset), else they are written in RGB (#1242). The export says how many of each
|
||||
/// there are: converted ones' darkest values come out as rich blacks, and kept ones aren't CMYK.
|
||||
/// Grey images stay grey either way and aren't counted.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RgbInCmyk {
|
||||
/// Distinct RGB colours, by the bits of their channels.
|
||||
pub(super) colours: HashSet<[u32; 3]>,
|
||||
/// Keys of the raster images that aren't CMYK.
|
||||
pub(super) images: HashSet<String>,
|
||||
/// Keys of the RGB images converted to CMYK.
|
||||
pub(super) converted: HashSet<String>,
|
||||
/// Keys of the RGB images written in RGB.
|
||||
pub(super) kept: HashSet<String>,
|
||||
}
|
||||
|
||||
/// `n` `thing`s, in the plural unless `n` is 1.
|
||||
fn count(n: usize, thing: &str) -> String {
|
||||
format!("{n} {thing}{}", if n == 1 { "" } else { "s" })
|
||||
}
|
||||
|
||||
impl RgbInCmyk {
|
||||
pub(super) fn merge(&mut self, other: RgbInCmyk) {
|
||||
self.colours.extend(other.colours);
|
||||
self.images.extend(other.images);
|
||||
self.converted.extend(other.converted);
|
||||
self.kept.extend(other.kept);
|
||||
}
|
||||
|
||||
/// The warning for the export report; `None` when the document has nothing of the sort.
|
||||
pub(super) fn warning(&self) -> Option<String> {
|
||||
let (c, i) = (self.colours.len(), self.images.len());
|
||||
if c == 0 && i == 0 {
|
||||
return None;
|
||||
let (c, i, k) = (self.colours.len(), self.converted.len(), self.kept.len());
|
||||
let mut sentences = vec![];
|
||||
let converted: Vec<_> = [(c, "RGB colour"), (i, "RGB image")].into_iter().filter(|(n, _)| *n > 0).map(|(n, t)| count(n, t)).collect();
|
||||
if !converted.is_empty() {
|
||||
sentences.push(format!(
|
||||
"{}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink",
|
||||
converted.join(" and ")
|
||||
));
|
||||
}
|
||||
let mut parts = vec![];
|
||||
if c > 0 {
|
||||
parts.push(format!("{c} RGB colour{}", if c == 1 { "" } else { "s" }));
|
||||
if k > 0 {
|
||||
let (it, is) = if k == 1 { ("it", "is") } else { ("them", "are") };
|
||||
sentences.push(format!(
|
||||
"{} that {is} written in RGB, not CMYK: to write {it} in CMYK, choose Output › Color conversion › Convert to destination with a CMYK destination, or the PDF/X-1a:2001 preset",
|
||||
count(k, "RGB image")
|
||||
));
|
||||
}
|
||||
if i > 0 {
|
||||
parts.push(format!("{i} RGB or grey image{}", if i == 1 { "" } else { "s" }));
|
||||
}
|
||||
Some(format!(
|
||||
"this CMYK document has {}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink",
|
||||
parts.join(" and ")
|
||||
))
|
||||
(!sentences.is_empty()).then(|| format!("this CMYK document has {}", sentences.join("; and ")))
|
||||
}
|
||||
}
|
||||
@@ -165,8 +165,12 @@ impl Exporter<'_> {
|
||||
let mut unconverted = false;
|
||||
let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| {
|
||||
let cmyk_image = blob.is_cmyk();
|
||||
if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk {
|
||||
self.rgb_in_cmyk.images.insert(key.to_string());
|
||||
// RGB images of a CMYK document go to CMYK only with a CMYK destination; grey ones stay
|
||||
// grey ([`crate::images::recode`]).
|
||||
if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk && !crate::images::is_grey(&blob.bytes) {
|
||||
let to_cmyk = matches!(out.pixels(), Some(crate::output::Pixels::Cmyk(_)));
|
||||
let set = if to_cmyk { &mut self.rgb_in_cmyk.converted } else { &mut self.rgb_in_cmyk.kept };
|
||||
set.insert(key.to_string());
|
||||
}
|
||||
let r = if cmyk_image {
|
||||
let icc = out.cmyk_image_icc(blob);
|
||||
|
||||
@@ -528,6 +528,22 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic
|
||||
}
|
||||
}
|
||||
|
||||
/// Are samples of type `t` grey (with or without alpha)? [`recode`] keeps such pixels grey.
|
||||
fn grey_type(t: ExtendedColorType) -> bool {
|
||||
use ExtendedColorType as T;
|
||||
matches!(t, T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16)
|
||||
}
|
||||
|
||||
/// Does the image in `bytes` hold grey samples, which [`recode`] keeps grey whatever the Output
|
||||
/// settings? Reads only its header; `false` for one that can't be read.
|
||||
pub(crate) fn is_grey(bytes: &[u8]) -> bool {
|
||||
ImageReader::new(Cursor::new(bytes))
|
||||
.with_guessed_format()
|
||||
.ok()
|
||||
.and_then(|r| r.into_decoder().ok())
|
||||
.is_some_and(|d| grey_type(d.original_color_type()))
|
||||
}
|
||||
|
||||
/// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask:
|
||||
/// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours
|
||||
/// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile
|
||||
@@ -554,8 +570,7 @@ pub(crate) fn recode(
|
||||
let jpeg = reader.format() == Some(ImageFormat::Jpeg);
|
||||
let Ok(mut decoder) = reader.into_decoder() else { return keep };
|
||||
let dims = decoder.dimensions();
|
||||
use ExtendedColorType as T;
|
||||
let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16);
|
||||
let grey = grey_type(decoder.original_color_type());
|
||||
// Pixels in a profile they are converted from are decoded, whatever the Compression settings.
|
||||
// Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]).
|
||||
let then = to_srgb.and_then(|t| t.then);
|
||||
|
||||
@@ -706,3 +706,61 @@ fn colours_are_in_the_profiles_assigned_to_the_document() {
|
||||
assert!(r.warnings.iter().any(|w| w.contains("No Such Press")), "{:?}", r.warnings);
|
||||
assert!(icc_streams(&r.bytes) == [cms::icc_bytes(&working).unwrap().to_vec()]);
|
||||
}
|
||||
|
||||
/// A 4 × 4 greyscale PNG of one level.
|
||||
fn grey_png(level: u8) -> Vec<u8> {
|
||||
let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![level; 16])
|
||||
.unwrap();
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// The CMYK document warning says what happens to its RGB images (#1242): with No conversion
|
||||
/// they are written in RGB, and it names the settings that write them in CMYK; with a CMYK
|
||||
/// destination they are converted. Grey images stay grey either way and aren't counted.
|
||||
#[test]
|
||||
fn the_cmyk_document_warning_says_whether_rgb_images_are_converted() {
|
||||
let warning = |d: &Document, settings: Value| {
|
||||
let r = pdf(d, settings);
|
||||
let w: Vec<_> = r.warnings.iter().filter(|w| w.contains("this CMYK document")).cloned().collect();
|
||||
assert!(w.len() <= 1, "{w:?}");
|
||||
w.into_iter().next()
|
||||
};
|
||||
let mut d = image_doc(png([200, 30, 30]));
|
||||
d.color_mode = ColorMode::Cmyk;
|
||||
|
||||
// No conversion: the image is written in RGB, and the warning doesn't say otherwise.
|
||||
let kept = warning(&d, json!({})).unwrap();
|
||||
assert!(kept.contains("1 RGB image") && kept.contains("written in RGB"), "{kept}");
|
||||
assert!(!kept.contains("converted to CMYK"), "{kept}");
|
||||
assert!(kept.contains("Convert to destination") && kept.contains("PDF/X-1a"), "{kept}");
|
||||
|
||||
// A CMYK destination converts it.
|
||||
for settings in
|
||||
[json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}), json!({"standard": "pdfX1a", "compatibility": "1.3"})]
|
||||
{
|
||||
let converted = warning(&d, settings.clone()).unwrap();
|
||||
assert!(converted.contains("1 RGB image") && converted.contains("converted to CMYK"), "{settings}: {converted}");
|
||||
assert!(!converted.contains("written in RGB"), "{settings}: {converted}");
|
||||
}
|
||||
|
||||
// A grey image is not an RGB image: nothing to warn about.
|
||||
let mut grey = image_doc(grey_png(90));
|
||||
grey.color_mode = ColorMode::Cmyk;
|
||||
for settings in [json!({}), json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})] {
|
||||
assert_eq!(warning(&grey, settings.clone()), None, "{settings}");
|
||||
}
|
||||
|
||||
// RGB colours keep their wording beside images kept in RGB.
|
||||
let mut both = image_doc(png([200, 30, 30]));
|
||||
both.color_mode = ColorMode::Cmyk;
|
||||
let l = both.layers[0].id;
|
||||
let n = Node::path(
|
||||
both.alloc_id(),
|
||||
shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)),
|
||||
Appearance::basic(Paint::solid(Color::Rgb { r: 0.1, g: 0.1, b: 0.1 }), Paint::None, 0.0),
|
||||
);
|
||||
both.insert(Some(l), 1, n).unwrap();
|
||||
let w = warning(&both, json!({})).unwrap();
|
||||
assert!(w.contains("1 RGB colour") && w.contains("converted to CMYK") && w.contains("rich blacks"), "{w}");
|
||||
assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}");
|
||||
}
|
||||
@@ -94,6 +94,15 @@ impl crate::Renderer {
|
||||
/// renderer draws copies of the objects (`proof::prepare`), so they are measured afresh and
|
||||
/// nothing is held.
|
||||
pub fn changed(&mut self, old: &Document, new: &Document, opts: &crate::RenderOptions) -> Changed {
|
||||
// Trim View clips each draw when blending reaches the page and clips one composited
|
||||
// layer otherwise. Changing modes can change unchanged art at an artboard edge.
|
||||
if opts.trim && !old.artboards.is_empty() {
|
||||
let before = crate::proof::prepare(old, opts, &mut self.proof_art);
|
||||
let after = crate::proof::prepare(new, opts, &mut self.proof_art);
|
||||
if self.children_blend(&before.layers) != self.children_blend(&after.layers) {
|
||||
return Changed::Everything;
|
||||
}
|
||||
}
|
||||
let renderer = (!crate::proof::overprints(opts)).then_some(self);
|
||||
changed_with(old, new, renderer, opts)
|
||||
}
|
||||
|
||||
@@ -167,6 +167,8 @@ pub struct FrameStats {
|
||||
/// group or an effect's raster. A part of the frame rendered on its own can draw that art with
|
||||
/// other pixels than the whole frame does.
|
||||
pub view_sized: usize,
|
||||
bounded_view_sized: usize,
|
||||
view_sized_bounds: Option<Rect>,
|
||||
/// How many threads composed the frame from its two ink planes, in a CMYK document that shows
|
||||
/// transparency; 0 for other frames.
|
||||
pub ink_threads: usize,
|
||||
@@ -183,10 +185,35 @@ pub struct FrameStats {
|
||||
pub micros: u64,
|
||||
}
|
||||
|
||||
impl FrameStats {
|
||||
/// A conservative enclosure in the frame's output pixels, when every view-sized operation has
|
||||
/// a known bound. `None` leaves the choice to render the whole frame.
|
||||
pub fn view_sized_bounds(&self) -> Option<Rect> {
|
||||
self.view_sized_bounds.filter(|_| self.bounded_view_sized == self.view_sized)
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Renderer {
|
||||
/// Records an operation bounded by its own output clip. A nested effect can affect more than
|
||||
/// its own clip once an ancestor filters or composites it, so only bound direct RGB output.
|
||||
pub(crate) fn note_view_sized_clip(&mut self, f: &Frame, clip: Rect) {
|
||||
self.stats.view_sized += 1;
|
||||
if self.nested == 0 && self.offscreen_live == 0 && f.view == f.output && f.doc.color_mode == vectorcraft_doc::ColorMode::Rgb {
|
||||
let bound = f.output.transform_rect_bbox(clip).inflate(1.0, 1.0);
|
||||
if bound.is_finite() {
|
||||
self.stats.bounded_view_sized += 1;
|
||||
self.stats.view_sized_bounds = vectorcraft_geom::union_opt(self.stats.view_sized_bounds, Some(bound));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Frame<'a> {
|
||||
/// Drawing into a multithreaded context: vello filter layers must be rendered offscreen.
|
||||
pub(crate) mt: bool,
|
||||
/// Set the flag if the incomplete paint would need a full render.
|
||||
pub(crate) patch: Option<&'a std::cell::Cell<bool>>,
|
||||
pub(crate) doc: &'a Document,
|
||||
/// `doc`'s symbol art boxes, which culling measures symbol instances by ([`SymbolBoxes::quick`]).
|
||||
pub(crate) symbols: &'a SymbolBoxes<'a>,
|
||||
@@ -208,6 +235,17 @@ pub(crate) struct Frame<'a> {
|
||||
}
|
||||
|
||||
impl Frame<'_> {
|
||||
pub(crate) fn reject_patch(&self) -> bool {
|
||||
self.patch.is_some_and(|hit| {
|
||||
hit.set(true);
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn patch_rejected(&self) -> bool {
|
||||
self.patch.is_some_and(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// Text space → device pixels when type is snapped to the pixel grid (Type anti-aliasing).
|
||||
pub(crate) fn text_snap(&self, t: &TextObject) -> Option<Affine> {
|
||||
(self.opts.anti_alias == AntiAlias::Type).then(|| self.view * t.xf)
|
||||
|
||||
@@ -11,6 +11,12 @@ use super::{
|
||||
RasterFx, Rect, RenderContext, Renderer, Shape, blend_mode, effects, fill_rule, paint, peniko,
|
||||
};
|
||||
|
||||
/// The content to filter. An inner glow's output has an enclosing clip, while a shadow can spread beyond its content.
|
||||
pub(super) enum FilterReach {
|
||||
Clipped(Rect),
|
||||
Spreads(Rect),
|
||||
}
|
||||
|
||||
/// A hash of the names of `doc`'s swatches and patterns, of the paints and spot flags of its global
|
||||
/// swatches, and of the Spot Colors option those colors depend on.
|
||||
pub(crate) fn paint_names(doc: &Document) -> u64 {
|
||||
@@ -596,15 +602,25 @@ impl Renderer {
|
||||
&mut self,
|
||||
ctx: &mut RenderContext,
|
||||
f: &Frame,
|
||||
reach: Rect,
|
||||
reach: FilterReach,
|
||||
blur: f64,
|
||||
composite: Option<(vectorcraft_doc::color::BlendMode, f32)>,
|
||||
draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame, Option<(vectorcraft_doc::color::BlendMode, f32)>),
|
||||
) {
|
||||
// A filter layer's coarser grid starts where its context does: at the corner of a context
|
||||
// drawn single-threaded, and at the frame's edge for a region cropped to the frame.
|
||||
let (reach, clipped) = match reach {
|
||||
FilterReach::Clipped(rect) => (rect, true),
|
||||
FilterReach::Spreads(rect) => (rect, false),
|
||||
};
|
||||
let screen = Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
|
||||
self.stats.view_sized += usize::from(!f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen);
|
||||
if !f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen {
|
||||
if clipped {
|
||||
self.note_view_sized_clip(f, reach);
|
||||
} else {
|
||||
self.stats.view_sized += 1;
|
||||
}
|
||||
}
|
||||
if !f.mt {
|
||||
return self.inside_layer(|r| draw(r, ctx, f, composite));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage};
|
||||
use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry};
|
||||
use super::pixels::FilterReach;
|
||||
use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted};
|
||||
use super::raster::{
|
||||
DRAG_PIXEL_BUDGET, MAX_RASTERIZE, PIXEL_BUDGET, ViewCrop, content_changing, doc_raster_ppi, image_size, linear_key, pan_margin, pcolor,
|
||||
@@ -134,6 +135,9 @@ impl Renderer {
|
||||
// During a drag, a larger shadow on a multithreaded context is filtered within the
|
||||
// drag's budget (`with_filters`), and no raster is kept.
|
||||
if f.opts.dragging && f.mt && w * h > DRAG_PIXEL_BUDGET {
|
||||
// The fallback can differ from a still raster (a glow blurs soft alpha here).
|
||||
// A patch over a still frame cannot splice these pictures together.
|
||||
self.stats.view_sized += 1;
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (w as u16, h as u16);
|
||||
@@ -258,7 +262,7 @@ impl Renderer {
|
||||
let reach = reach + Vec2::new(dx, dy);
|
||||
#[cfg(test)]
|
||||
note_silhouette();
|
||||
self.with_filters(ctx, f, reach, blur, Some((mode, opacity)), |r, c, fr, comp| {
|
||||
self.with_filters(ctx, f, FilterReach::Spreads(reach), blur, Some((mode, opacity)), |r, c, fr, comp| {
|
||||
c.set_transform(fr.view);
|
||||
c.push_layer(None, comp.map(|m| blend_mode(m.0)), comp.map(|m| m.1), None, Some(filter));
|
||||
let ink = darkness.map_or(fr.ink, |d| fr.ink.darkened(d));
|
||||
@@ -470,7 +474,7 @@ impl Renderer {
|
||||
let opacity = self.opacity_of(a);
|
||||
if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_doc::color::BlendMode::Normal || a.isolate) {
|
||||
let blends = self.blends_through(a);
|
||||
let bounds = if blends { self.bounds_of(f.symbols, a) } else { None };
|
||||
let bounds = if blends { self.frame_bounds_of(f, a) } else { None };
|
||||
let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() };
|
||||
self.group(ctx, f, comp, &mut |r, c, fr| r.draw_object_fx_art(c, fr, a, cache));
|
||||
} else {
|
||||
@@ -816,6 +820,9 @@ impl Renderer {
|
||||
rfx: &[RasterFx],
|
||||
paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame),
|
||||
) {
|
||||
if !rfx.is_empty() && f.reject_patch() {
|
||||
return;
|
||||
}
|
||||
// Only the last MAX_RASTERIZE Rasterize effects are drawn.
|
||||
let count = rfx.iter().filter(|fx| matches!(fx, RasterFx::Rasterize(_))).count();
|
||||
let capped: Vec<RasterFx>;
|
||||
@@ -995,7 +1002,7 @@ impl Renderer {
|
||||
let RasterFx::InnerGlow { mode, opacity, blur, color, center } = fx else { continue };
|
||||
let filter = shadow_filter(0.0, 0.0, *blur, pcolor(f.ink, color));
|
||||
if pixels {
|
||||
self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |r, c, fr, comp| {
|
||||
self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |r, c, fr, comp| {
|
||||
if let Some((m, o)) = comp {
|
||||
c.set_transform(Affine::IDENTITY);
|
||||
c.push_layer(None, Some(blend_mode(m)), Some(o), None, None);
|
||||
@@ -1029,7 +1036,7 @@ impl Renderer {
|
||||
});
|
||||
continue;
|
||||
}
|
||||
self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |_, c, fr, comp| {
|
||||
self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |_, c, fr, comp| {
|
||||
// The blend layer goes outside the clip: a clip layer is isolated, so a blend
|
||||
// inside it would mix with nothing instead of the content below.
|
||||
if let Some((m, o)) = comp {
|
||||
@@ -1128,6 +1135,7 @@ mod tests {
|
||||
let opts = RenderOptions::default();
|
||||
let frame = Frame {
|
||||
mt: false,
|
||||
patch: None,
|
||||
doc: &doc,
|
||||
symbols: &symbols,
|
||||
view: Affine::IDENTITY,
|
||||
|
||||
@@ -1530,6 +1530,78 @@ fn moved_objects_draw_their_effect_rasters_while_interacting() {
|
||||
/// 1600 × 1000 view near its corner needs more than the drag's budget. The
|
||||
/// frame after the drag, of the same document, is what a fresh renderer draws, as is a frame
|
||||
/// rendered while interacting without a drag (a dialog's preview).
|
||||
#[test]
|
||||
fn a_plain_patch_stops_at_a_raster_effect() {
|
||||
let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("texture.texturizer", json!({}))]);
|
||||
let plain = Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::rectangle(Rect::new(94.0, 3.0, 96.0, 6.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap();
|
||||
let (width, height) = (2000, 1600);
|
||||
let view = Affine::scale(20.0);
|
||||
let still = RenderOptions::default();
|
||||
let mut renderer = Renderer::new();
|
||||
renderer.threads = 0;
|
||||
renderer.render(&doc, width, height, view, &still);
|
||||
let total_drawn = renderer.stats.drawn;
|
||||
let mut scratch = Renderer::new();
|
||||
scratch.threads = 0;
|
||||
let patch_view = Affine::translate((-1850.0, -50.0)) * view;
|
||||
assert!(scratch.render_plain_patch(&doc, 100, 100, patch_view, &still).is_some(), "the distant patch does not draw the effect");
|
||||
assert!(scratch.render_plain_patch(&doc, width, height, view, &still).is_none(), "a patch that draws the effect needs the full render");
|
||||
assert!(scratch.stats.drawn < total_drawn, "the rejected patch does not draw the artwork after the effect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_patch_does_not_build_unrelated_3d_art_to_cull_it() {
|
||||
let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("threeD.extrude", json!({"depth": 10}))]);
|
||||
let plain = Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::rectangle(Rect::new(290.0, 10.0, 300.0, 20.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap();
|
||||
let opts = RenderOptions::default();
|
||||
let mut whole = Renderer::new();
|
||||
whole.threads = 0;
|
||||
whole.render(&doc, 350, 150, Affine::IDENTITY, &opts);
|
||||
assert!(whole.stats.three_d_built > 0, "the fixture generates 3D art");
|
||||
let mut scratch = Renderer::new();
|
||||
scratch.threads = 0;
|
||||
let patch = Affine::translate((-280.0, 0.0));
|
||||
let result = scratch.render_plain_patch(&doc, 40, 30, patch, &opts);
|
||||
assert_eq!(scratch.stats.three_d_built, 0, "fall back before rebuilding 3D art");
|
||||
assert!(result.is_none());
|
||||
|
||||
let layer = doc.layers[0].id;
|
||||
let art = doc.layers[0].children().unwrap()[0].clone();
|
||||
doc.remove(art.id).unwrap();
|
||||
let mut group = Node::group(doc.alloc_id(), vec![art.clone()]);
|
||||
group.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.innerGlow".into(), params: json!({"blur": 4}), visible: true });
|
||||
assert!(super::has_object_fx(&group), "this group uses the alternate bounds path");
|
||||
let group = doc.insert(Some(layer), 0, group).unwrap();
|
||||
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "alternate group bounds also need the 3D child");
|
||||
doc.remove(group).unwrap();
|
||||
|
||||
let mut template = Node::layer(doc.alloc_id(), "Template", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let vectorcraft_doc::NodeKind::Layer { template: flag, children, .. } = &mut template.kind {
|
||||
*flag = true;
|
||||
children.push(art.clone());
|
||||
}
|
||||
let template = doc.insert(Some(layer), 0, template).unwrap();
|
||||
let hidden = RenderOptions { hide_templates: true, ..opts.clone() };
|
||||
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &hidden).is_none(), "layer bounds conservatively include hidden templates");
|
||||
assert_eq!(scratch.stats.three_d_built, 0);
|
||||
|
||||
doc.remove(template).unwrap();
|
||||
doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Solid".into(), art });
|
||||
let instance = Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Solid".into(), xf: Affine::IDENTITY });
|
||||
doc.insert(Some(layer), 0, instance).unwrap();
|
||||
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "a symbol's definition also needs 3D bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_renders_raster_effects_within_the_drag_budget() {
|
||||
let effects = vec![("stylize.dropShadow", json!({"x": 4, "y": 3, "blur": 7, "opacity": 80})), ("texture.texturizer", json!({}))];
|
||||
@@ -1581,6 +1653,31 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() {
|
||||
assert!(after == threaded().render(&scaled, 1600, 1000, view, &still).pixels, "the frame after the drag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() {
|
||||
let doc = doc_with(
|
||||
Rect::new(20.0, 20.0, 40.0, 40.0),
|
||||
Color::BLACK,
|
||||
vec![
|
||||
("stylize.outerGlow", json!({"blur": 1.3, "color": "#ff0000", "opacity": 100, "mode": "normal"})),
|
||||
("stylize.outerGlow", json!({"blur": 1.0, "color": "#0000ff", "opacity": 100, "mode": "normal"})),
|
||||
],
|
||||
);
|
||||
let view = Affine::translate((600.0, 600.0)) * Affine::scale(40.0) * Affine::translate((-30.0, -30.0));
|
||||
let mut still = Renderer::new();
|
||||
still.threads = 2;
|
||||
let still_pixels = still.render(&doc, 1200, 1200, view, &RenderOptions::default()).pixels;
|
||||
assert_eq!(still.stats.view_sized, 0, "the still frame draws both whole rasters");
|
||||
|
||||
let mut drag = Renderer::new();
|
||||
drag.threads = 2;
|
||||
let opts = RenderOptions { interacting: true, dragging: true, ..Default::default() };
|
||||
let drag_pixels = drag.render(&doc, 1200, 1200, view, &opts).pixels;
|
||||
assert_eq!(drag.stats.previewed, 0, "the fallback filter fits the drag budget without downsampling");
|
||||
assert!(drag_pixels != still_pixels, "a glow over the first glow differs from the fallback filter");
|
||||
assert!(drag.stats.view_sized > 0, "the fallback must replace the whole frame");
|
||||
}
|
||||
|
||||
/// While interacting, a group holding a symbol instance whose art lies outside the 20 × 20
|
||||
/// square around the origin draws its drop shadow from the raster of an earlier frame. The
|
||||
/// shadow is made from the instance's art, which the renderer measures the group's content by.
|
||||
|
||||
@@ -114,6 +114,9 @@ impl Renderer {
|
||||
}
|
||||
|
||||
fn group_offscreen(&mut self, ctx: &mut RenderContext, f: &Frame, c: Composite, r: Region, draw: &mut Content) {
|
||||
if f.reject_patch() {
|
||||
return;
|
||||
}
|
||||
let Composite { clip, blend, opacity, mask, isolated, .. } = c;
|
||||
// A group that blends with its backdrop is drawn twice (over the backdrop, and alone for
|
||||
// its coverage), and so is everything in it, so such groups nested in each other cost 2ⁿ.
|
||||
@@ -309,7 +312,10 @@ impl Renderer {
|
||||
/// `c` over the backdrop and its shape are drawn offscreen over `c`'s bounds, and `c` is drawn
|
||||
/// as in the other knockout passes (groups in it can't copy their backdrop).
|
||||
pub(crate) fn knockout_over(&mut self, ctx: &mut RenderContext, f: &Frame, c: &Arc<Node>, backdrop: &Arc<Pixmap>) {
|
||||
let bounds = self.bounds_of(f.symbols, c);
|
||||
let bounds = self.frame_bounds_of(f, c);
|
||||
if f.patch_rejected() {
|
||||
return;
|
||||
}
|
||||
let Some(r) = region(ctx, f, bounds) else { return };
|
||||
let view = Affine::translate((-(r.x as f64), -(r.y as f64))) * f.view;
|
||||
let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, r.w as f64, r.h as f64));
|
||||
|
||||
@@ -583,7 +583,7 @@ impl Renderer {
|
||||
let enclosing = std::mem::replace(&mut self.knockout, knockout);
|
||||
if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) {
|
||||
let blends = self.blends_through(a);
|
||||
let bounds = if blends { self.bounds_of(f.symbols, a) } else { None };
|
||||
let bounds = if blends { self.frame_bounds_of(f, a) } else { None };
|
||||
let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() };
|
||||
self.group(ctx, f, comp, &mut |r, c, fr| r.draw_live_body(c, fr, a, true));
|
||||
} else {
|
||||
@@ -636,6 +636,10 @@ impl Renderer {
|
||||
if !m.is_valid() {
|
||||
return;
|
||||
}
|
||||
// A cropped mesh may lose a covered neighbor that supplied a color at its fringe.
|
||||
if f.reject_patch() {
|
||||
return;
|
||||
}
|
||||
if f.opts.outline {
|
||||
let bp = m.lines().to_bezpath();
|
||||
self.hairline(ctx, f, &bp, [0, 0, 0, 255]);
|
||||
|
||||
@@ -198,6 +198,7 @@ fn rasterize(
|
||||
let v = view * def.instance_xf(o);
|
||||
let frame = Frame {
|
||||
mt: false,
|
||||
patch: None,
|
||||
doc,
|
||||
symbols: &symbols,
|
||||
view: v,
|
||||
|
||||
@@ -113,9 +113,32 @@ impl Renderer {
|
||||
/// set in one of the document's composite fonts draws in the document's definition, also when
|
||||
/// no session has registered it (a document that is not in front, or read from a file).
|
||||
pub fn render(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered {
|
||||
self.render_document(doc, width, height, view, opts, None)
|
||||
}
|
||||
|
||||
/// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen
|
||||
/// group compositing require the full render.
|
||||
pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option<Rendered> {
|
||||
if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample {
|
||||
return None;
|
||||
}
|
||||
let hit = std::cell::Cell::new(false);
|
||||
let image = self.render_document(doc, width, height, view, opts, Some(&hit));
|
||||
(!hit.get()).then_some(image)
|
||||
}
|
||||
|
||||
fn render_document(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
width: u32,
|
||||
height: u32,
|
||||
view: Affine,
|
||||
opts: &RenderOptions,
|
||||
patch: Option<&std::cell::Cell<bool>>,
|
||||
) -> Rendered {
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
|
||||
self.render_as(doc, width, height, view, opts, false, 1)
|
||||
self.render_as(doc, width, height, view, opts, false, 1, patch)
|
||||
}
|
||||
|
||||
/// [`Self::render`], or with `inks` the ink amounts in the working CMYK space instead of
|
||||
@@ -123,14 +146,24 @@ impl Renderer {
|
||||
/// pixel of the output in pixels of this render: the supersampling factor while an export
|
||||
/// draws its art at several times its size, else 1 ([`Frame::output`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_as(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions, inks: bool, cell: u32) -> Rendered {
|
||||
fn render_as(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
width: u32,
|
||||
height: u32,
|
||||
view: Affine,
|
||||
opts: &RenderOptions,
|
||||
inks: bool,
|
||||
cell: u32,
|
||||
patch: Option<&std::cell::Cell<bool>>,
|
||||
) -> Rendered {
|
||||
let start = now();
|
||||
if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() {
|
||||
let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE));
|
||||
if let Some(k) = supersample_factor(w, h) {
|
||||
let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() };
|
||||
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
|
||||
let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k);
|
||||
let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
|
||||
self.hairline = hairline;
|
||||
let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize);
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
@@ -164,7 +197,7 @@ impl Renderer {
|
||||
let symbols = doc.symbol_boxes().quick();
|
||||
let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view;
|
||||
let plates = proof::plate_lut(opts, doc);
|
||||
let frame = Frame { mt: threads > 0, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() };
|
||||
let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() };
|
||||
self.begin_frame();
|
||||
// View Opacity Mask: the mask's coverage in greyscale instead of the artwork.
|
||||
if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) {
|
||||
@@ -199,7 +232,7 @@ impl Renderer {
|
||||
self.draw_frame(&frame, w, h)
|
||||
};
|
||||
self.end_frame();
|
||||
if !inks {
|
||||
if !inks && !pixels.is_empty() {
|
||||
proof::post(&mut pixels, opts);
|
||||
}
|
||||
self.stats.symbol_art = symbols.art_measured();
|
||||
@@ -218,9 +251,8 @@ impl Renderer {
|
||||
self.placed_frame = None;
|
||||
}
|
||||
|
||||
/// End a frame: drop cache entries not used for a few frames (every render, thumbnails too,
|
||||
/// so the nodes they hold go with them).
|
||||
fn end_frame(&mut self) {
|
||||
/// Drop stale bounds and paths, including old versions of edited nodes.
|
||||
fn sweep_node_geometry(&mut self) {
|
||||
let g = self.stamp;
|
||||
// Swept however few the entries: each keeps its node alive, and an object dragged or
|
||||
// edited makes a new node (with its layer) in every frame. Kept until there were 1,024 of
|
||||
@@ -230,6 +262,23 @@ impl Renderer {
|
||||
// A kept path stays while its object is in `geom`, which keeps the objects still drawn.
|
||||
let geom = &self.geom;
|
||||
self.kept.retain(|_, e| g - e.stamp <= 3 || geom.get(&(Arc::as_ptr(&e.node) as usize)).is_some_and(|k| Arc::ptr_eq(&k.node, &e.node)));
|
||||
}
|
||||
|
||||
/// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update.
|
||||
/// Age the measurement caches and keep the previous draw's effect rasters available.
|
||||
pub fn finish_measurement_only(&mut self) {
|
||||
self.stamp += 1;
|
||||
self.sweep_node_geometry();
|
||||
let g = self.stamp;
|
||||
self.blends.retain(|_, e| g - e.2 <= 3);
|
||||
self.let_go_of_measured();
|
||||
}
|
||||
|
||||
/// End a frame: drop cache entries not used for a few frames (every render, thumbnails too,
|
||||
/// so the nodes they hold go with them).
|
||||
fn end_frame(&mut self) {
|
||||
let g = self.stamp;
|
||||
self.sweep_node_geometry();
|
||||
if self.strokes.len() > 1024 {
|
||||
self.strokes.retain(|_, e| g - e.stamp <= 3);
|
||||
let strokes = &self.strokes;
|
||||
@@ -309,11 +358,17 @@ impl Renderer {
|
||||
} else {
|
||||
self.draw_page(&mut ctx, f);
|
||||
}
|
||||
let pm = self.finish(&mut ctx, self.raster);
|
||||
let pm = if f.patch_rejected() {
|
||||
self.picture = None;
|
||||
None
|
||||
} else {
|
||||
Some(self.finish(&mut ctx, self.raster))
|
||||
};
|
||||
self.contexts.push((threads, ctx));
|
||||
if self.contexts.len() > 2 {
|
||||
self.contexts.remove(0);
|
||||
}
|
||||
let Some(pm) = pm else { return Vec::new() };
|
||||
let mut pixels = pm.data_as_u8_slice().to_vec();
|
||||
if let Some(bg) = opts.background {
|
||||
over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg)));
|
||||
@@ -370,7 +425,7 @@ impl Renderer {
|
||||
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
|
||||
self.render_as(doc, w, h, view, opts, true, 1).pixels
|
||||
self.render_as(doc, w, h, view, opts, true, 1, None).pixels
|
||||
}
|
||||
|
||||
/// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels.
|
||||
@@ -427,7 +482,7 @@ impl Renderer {
|
||||
ctx.set_aliasing_threshold(opts.anti_alias.threshold());
|
||||
let symbols = doc.symbol_boxes().quick();
|
||||
let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view;
|
||||
let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None };
|
||||
let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None };
|
||||
let raster = std::mem::replace(&mut self.raster, raster_settings(opts));
|
||||
self.begin_frame();
|
||||
(self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None);
|
||||
|
||||
@@ -7,10 +7,33 @@ use super::{
|
||||
use crate::kept_paths::{self, KeptPath};
|
||||
use crate::node_checks::{holds_measured_three_d, measures_three_d};
|
||||
|
||||
fn needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool {
|
||||
measures_three_d(node)
|
||||
|| matches!(&node.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.symbol(symbol).is_some_and(
|
||||
|s| holds_measured_three_d(&s.art) || holds_instance(&s.art) && symbols.has_effects(symbol)
|
||||
))
|
||||
}
|
||||
|
||||
fn subtree_needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool {
|
||||
needs_three_d_bounds(symbols, node)
|
||||
|| node.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child)))
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
/// Cached cull bounds of a node (containers union their cached children), symbol instances
|
||||
/// measured by their art box from `symbols`.
|
||||
pub(crate) fn bounds_of(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<Rect> {
|
||||
self.bounds_with_patch(symbols, a, None)
|
||||
}
|
||||
|
||||
pub(crate) fn frame_bounds_of(&mut self, f: &Frame, a: &Arc<Node>) -> Option<Rect> {
|
||||
self.bounds_with_patch(f.symbols, a, f.patch.map(|_| f))
|
||||
}
|
||||
|
||||
fn bounds_with_patch(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, patch: Option<&Frame<'_>>) -> Option<Rect> {
|
||||
if patch.is_some_and(Frame::patch_rejected) {
|
||||
return None;
|
||||
}
|
||||
let key = Arc::as_ptr(a) as usize;
|
||||
if let Some(e) = self.geom.get_mut(&key)
|
||||
&& Arc::ptr_eq(&e.node, a)
|
||||
@@ -18,6 +41,11 @@ impl Renderer {
|
||||
e.stamp = self.stamp;
|
||||
return e.bounds;
|
||||
}
|
||||
// The full renderer can reuse its 3D art. A cold scratch renderer may otherwise
|
||||
// build it while calculating cull bounds, including bounds of symbol definitions.
|
||||
if patch.is_some_and(|f| needs_three_d_bounds(symbols, a) && f.reject_patch()) {
|
||||
return None;
|
||||
}
|
||||
let b = match &a.kind {
|
||||
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(a) => {
|
||||
let mut acc: Option<Rect> = None;
|
||||
@@ -25,7 +53,10 @@ impl Renderer {
|
||||
let source = a.extras().trace.is_some().then(|| children.first()).flatten();
|
||||
for c in children {
|
||||
if c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)) {
|
||||
acc = vectorcraft_geom::union_opt(acc, self.bounds_of(symbols, c));
|
||||
acc = vectorcraft_geom::union_opt(acc, self.bounds_with_patch(symbols, c, patch));
|
||||
if patch.is_some_and(Frame::patch_rejected) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
acc
|
||||
@@ -48,6 +79,14 @@ impl Renderer {
|
||||
let pad = brush_fx::pad(symbols, a);
|
||||
b.map(|b| fx::with_own_raster_reach(symbols, a, b).inflate(pad, pad))
|
||||
}
|
||||
// The fallback measures the whole subtree without going through the cached
|
||||
// child traversal above. Reject cold measurement before entering it.
|
||||
_ if patch.is_some_and(|f| {
|
||||
a.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child))) && f.reject_patch()
|
||||
}) =>
|
||||
{
|
||||
return None;
|
||||
}
|
||||
_ => self.kept_bounds(symbols, a).unwrap_or_else(|| brush_fx::cull_bounds(symbols, a)),
|
||||
};
|
||||
self.geom.insert(key, GeomEntry { node: a.clone(), bounds: b, path: None, stamp: self.stamp });
|
||||
@@ -227,7 +266,11 @@ impl Renderer {
|
||||
if crate::node_checks::left_out(f.opts, f.doc, a) {
|
||||
return true;
|
||||
}
|
||||
match self.bounds_of(f.symbols, a) {
|
||||
let bounds = self.frame_bounds_of(f, a);
|
||||
if f.patch_rejected() {
|
||||
return true;
|
||||
}
|
||||
match bounds {
|
||||
Some(b) => {
|
||||
let pad = f.px * 2.0;
|
||||
// Level of detail: leaves smaller than a quarter pixel are invisible.
|
||||
@@ -241,7 +284,7 @@ impl Renderer {
|
||||
}
|
||||
|
||||
pub(crate) fn draw_arc(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>) {
|
||||
if self.skipped(f, a) {
|
||||
if f.patch_rejected() || self.skipped(f, a) {
|
||||
return;
|
||||
}
|
||||
// An image masked by one white shape painted straight into the shape, as an image in a
|
||||
@@ -272,7 +315,10 @@ impl Renderer {
|
||||
let Some(m) = a.extras().mask.as_deref().filter(|m| !m.disabled && !f.opts.outline && !self.is_shape(a)) else { return false };
|
||||
// A masked object is a non-isolated group of its own, drawn over its own pixels: the
|
||||
// mask is rendered over those only.
|
||||
let bounds = self.bounds_of(f.symbols, a);
|
||||
let bounds = self.frame_bounds_of(f, a);
|
||||
if f.patch_rejected() {
|
||||
return true;
|
||||
}
|
||||
let Some((r, sub)) = group::area(ctx, f, bounds) else { return true };
|
||||
let Some(mask) = self.mask_values(&sub, m, r.w, r.h) else { return true };
|
||||
let blends = a.blend != vectorcraft_color::BlendMode::Normal || (!a.isolate && self.blends_through(a));
|
||||
@@ -296,6 +342,9 @@ impl Renderer {
|
||||
/// The coverage of opacity mask `m` per output pixel (row-major): its art rendered offscreen,
|
||||
/// as luminance ([`mask_value`]).
|
||||
pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Option<Vec<u8>> {
|
||||
if f.reject_patch() {
|
||||
return None;
|
||||
}
|
||||
let mut mctx = f.offscreen_context(w, h);
|
||||
// Mask art is a picture of its own: it takes no part in a knockout group around the object,
|
||||
// and its luminance is that of its screen colours.
|
||||
@@ -393,7 +442,7 @@ impl Renderer {
|
||||
return;
|
||||
}
|
||||
// A cancelled export stops drawing; whoever asked for the picture drops it (see `cancel`).
|
||||
if vectorcraft_doc::cancel::is_cancelled() {
|
||||
if f.patch_rejected() || f.patch.is_some() && measures_three_d(n) && f.reject_patch() || vectorcraft_doc::cancel::is_cancelled() {
|
||||
return;
|
||||
}
|
||||
if force {
|
||||
@@ -679,7 +728,7 @@ impl Renderer {
|
||||
let inverse = im.xf.inverse();
|
||||
let (mut x0, mut x1, mut y0, mut y1) = (0.0_f64, w, 0.0_f64, h);
|
||||
for c in shapes {
|
||||
if let Some(b) = self.bounds_of(f.symbols, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) {
|
||||
if let Some(b) = self.frame_bounds_of(f, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) {
|
||||
for q in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] {
|
||||
let p = inverse * kurbo::Point::new(q.0, q.1);
|
||||
if p.x.is_finite() && p.y.is_finite() {
|
||||
@@ -742,7 +791,11 @@ impl Renderer {
|
||||
if crate::node_checks::left_out(f.opts, f.doc, c) {
|
||||
return;
|
||||
}
|
||||
match self.bounds_of(f.symbols, c) {
|
||||
let bounds = self.frame_bounds_of(f, c);
|
||||
if f.patch_rejected() {
|
||||
return;
|
||||
}
|
||||
match bounds {
|
||||
Some(b) => {
|
||||
let pad = f.px * 2.0;
|
||||
if !rects_overlap(b.inflate(pad, pad), f.visible) {
|
||||
@@ -781,7 +834,7 @@ impl Renderer {
|
||||
self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n)));
|
||||
}
|
||||
} else {
|
||||
for c in children {
|
||||
for c in children.iter().take_while(|_| !f.patch_rejected()) {
|
||||
self.draw_arc(ctx, f, c);
|
||||
}
|
||||
}
|
||||
@@ -804,6 +857,9 @@ impl Renderer {
|
||||
/// over the elements below it (the art below the group when the group is non-isolated and
|
||||
/// drawn over a copy of it, see [`Self::group`] and [`Self::knockout_over`]).
|
||||
pub(crate) fn draw_knockout(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc<Node>]) {
|
||||
if f.reject_patch() {
|
||||
return;
|
||||
}
|
||||
let backdrop = self.backdrop.take();
|
||||
for c in Node::knockout_elements(children) {
|
||||
if self.skipped(f, c) {
|
||||
|
||||
@@ -327,6 +327,10 @@ impl Renderer {
|
||||
/// characters'. It also returns false for type whose offscreen drawing would be more than
|
||||
/// [`MAX_RASTER_SIDE`] pixels a side or more than [`fx::PIXEL_BUDGET`] pixels in all.
|
||||
fn draw_type_edges(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, t: &TextObject, g: &Arc<TextGeom>, geom_kept: bool) -> bool {
|
||||
// A smaller frame can fit the offscreen type that a full frame draws as Sharp.
|
||||
if f.reject_patch() {
|
||||
return true;
|
||||
}
|
||||
if proof::overprints(f.opts) && t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -99,6 +99,42 @@ fn area(c: Changed) -> Rect {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_last_blend_in_trim_view_repaints_the_artboard_edges() {
|
||||
use vectorcraft_color::BlendMode;
|
||||
|
||||
let mut before = Document::new(110.0, 80.0);
|
||||
let layer = before.layers[0].id;
|
||||
for color in [Color::BLACK, Color::WHITE] {
|
||||
let shape = rect(&mut before, Rect::new(-10.0, 18.0, 25.0, 44.0), color);
|
||||
before.insert(Some(layer), usize::MAX, shape).unwrap();
|
||||
}
|
||||
let mut blend = rect(&mut before, Rect::new(70.0, 35.0, 85.0, 50.0), Color::rgb(0.7, 0.4, 0.3));
|
||||
blend.blend = BlendMode::Multiply;
|
||||
let id = before.insert(Some(layer), usize::MAX, blend).unwrap();
|
||||
let mut after = before.clone();
|
||||
after.node_mut(id).unwrap().blend = BlendMode::Normal;
|
||||
|
||||
let opts = RenderOptions { trim: true, ..Default::default() };
|
||||
let mut r = Renderer::new();
|
||||
let first = r.render(&before, W, H, view(), &opts);
|
||||
let change = r.changed(&before, &after, &opts);
|
||||
let last = Renderer::new().render(&after, W, H, view(), &opts);
|
||||
patched(&mut r, &first, &after, change, &last, &opts);
|
||||
assert_eq!(change, Changed::Everything);
|
||||
assert!(matches!(r.changed(&before, &after, &RenderOptions::default()), Changed::Area(_)));
|
||||
|
||||
// An overprinting fill gets its blend while preparing the proof.
|
||||
let mut overprinting = after.clone();
|
||||
overprinting.node_mut(id).unwrap().appearance.fill_mut().unwrap().overprint = true;
|
||||
let proof = RenderOptions { overprint_preview: true, ..opts };
|
||||
let first = r.render(&overprinting, W, H, view(), &proof);
|
||||
let change = r.changed(&overprinting, &after, &proof);
|
||||
let last = Renderer::new().render(&after, W, H, view(), &proof);
|
||||
patched(&mut r, &first, &after, change, &last, &proof);
|
||||
assert_eq!(change, Changed::Everything, "the proofed fill changes the clipping mode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_object_changes_where_it_was_and_is() {
|
||||
let (old, [loose, ..]) = document();
|
||||
|
||||
@@ -10,6 +10,30 @@ use crate::blobs::blob_key;
|
||||
use crate::tests_fontchange::fonts_steady;
|
||||
use crate::*;
|
||||
|
||||
#[test]
|
||||
fn geometry_from_measurement_only_frames_releases_old_node_versions() {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let id = doc.alloc_id();
|
||||
let path = Node::path(
|
||||
id,
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)),
|
||||
vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
doc.insert(Some(layer), 0, path).unwrap();
|
||||
let oldest = Arc::downgrade(&doc.layers[0].children().unwrap()[0]);
|
||||
let mut renderer = Renderer::new();
|
||||
let opts = RenderOptions::default();
|
||||
for _ in 0..12 {
|
||||
let mut next = doc.clone();
|
||||
next.node_mut(id).unwrap().transform(Affine::translate((1.0, 0.0)), false);
|
||||
assert!(matches!(renderer.changed(&doc, &next, &opts), Changed::Area(_)));
|
||||
renderer.finish_measurement_only();
|
||||
doc = next;
|
||||
}
|
||||
assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw");
|
||||
}
|
||||
|
||||
/// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by
|
||||
/// the tests running alongside).
|
||||
fn png(w: u32, h: u32, seed: u8) -> Vec<u8> {
|
||||
|
||||
@@ -43,6 +43,17 @@ fn partial(a: &[u8]) -> usize {
|
||||
a.iter().filter(|v| **v > 0 && **v < 255).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_patch_defers_frame_sensitive_type_edges() {
|
||||
let mut renderer = Renderer::new();
|
||||
renderer.threads = 0;
|
||||
let opts = RenderOptions::default();
|
||||
let sharp = page(TypeAntiAlias::Sharp, None);
|
||||
let crisp = page(TypeAntiAlias::Crisp, None);
|
||||
assert!(renderer.render_plain_patch(&sharp, W, H, Affine::IDENTITY, &opts).is_some());
|
||||
assert!(renderer.render_plain_patch(&crisp, W, H, Affine::IDENTITY, &opts).is_none());
|
||||
}
|
||||
|
||||
/// The first pixels of `drawn` (type drawn with `m`) that are not the share `edge_coverage` gives
|
||||
/// the same pixel of `sharp` (the type drawn with Sharp), within a step of rounding: (pixel,
|
||||
/// Sharp, drawn).
|
||||
|
||||
@@ -276,6 +276,10 @@ fn a_frame_counts_the_art_it_draws_by_its_size() {
|
||||
let mut r = Renderer::new();
|
||||
r.render(&mesh(100.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default());
|
||||
assert_eq!(r.stats.view_sized, 0, "a mesh within the mesh buffer");
|
||||
assert!(
|
||||
r.render_plain_patch(&mesh(100.0), 60, 60, Affine::translate((-50.0, -50.0)), &RenderOptions::default()).is_none(),
|
||||
"a patch through a mesh must fall back even when the full mesh fits"
|
||||
);
|
||||
r.render(&mesh(3000.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default());
|
||||
assert!(r.stats.view_sized > 0, "a mesh past the mesh buffer");
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::mem;
|
||||
|
||||
use craft::ui::dialog::{DialogResult, StackDialog};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, StackDialog};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog};
|
||||
use egui::Context;
|
||||
use serde_json::{Value, json};
|
||||
@@ -32,13 +32,27 @@ pub(crate) struct Spec {
|
||||
/// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct AddonDialogs {
|
||||
open: Option<(craft::ui::dialog::DialogId, &'static Spec)>,
|
||||
open: Option<Open>,
|
||||
preview: LivePreview,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Open {
|
||||
id: DialogId,
|
||||
spec: &'static Spec,
|
||||
document: Option<u64>,
|
||||
}
|
||||
|
||||
impl Open {
|
||||
fn on_document(self, app: &VectorcraftApp) -> bool {
|
||||
self.document == app.session.active().map(|state| state.uid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the open add-on dialog without an answer and rolls its preview back.
|
||||
fn close_open(app: &mut VectorcraftApp) {
|
||||
let Some((id, _)) = app.addon_dialogs.open.take() else { return };
|
||||
let Some(open) = app.addon_dialogs.open.take() else { return };
|
||||
let id = open.id;
|
||||
if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) {
|
||||
host.with(|h| {
|
||||
h.cancel_by_id(&ctx, id);
|
||||
@@ -46,7 +60,10 @@ fn close_open(app: &mut VectorcraftApp) {
|
||||
let _ = h.take_by_id::<HostedParamDialog>(id);
|
||||
});
|
||||
}
|
||||
mem::take(&mut app.addon_dialogs.preview).cancel(app);
|
||||
let preview = mem::take(&mut app.addon_dialogs.preview);
|
||||
if open.on_document(app) {
|
||||
preview.cancel(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the dialog `spec` describes over `fields`, built each pass by `build`.
|
||||
@@ -62,7 +79,7 @@ pub(crate) fn open(
|
||||
close_open(app);
|
||||
let id = dialog.id();
|
||||
host.with(|h| h.open(dialog));
|
||||
app.addon_dialogs.open = Some((id, spec));
|
||||
app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) });
|
||||
Ok(json!({ "dialog": spec.command }))
|
||||
}
|
||||
|
||||
@@ -94,10 +111,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
|
||||
}
|
||||
|
||||
fn pump_commit(app: &mut VectorcraftApp) {
|
||||
let Some((id, spec)) = app.addon_dialogs.open else { return };
|
||||
let Some(open) = app.addon_dialogs.open else { return };
|
||||
let Some(host) = app.dialogs() else { return };
|
||||
let Open { id, spec, .. } = open;
|
||||
let on_document = open.on_document(app);
|
||||
if !on_document {
|
||||
// Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing.
|
||||
app.addon_dialogs.preview = LivePreview::default();
|
||||
}
|
||||
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), (spec.params)(d.fields()))));
|
||||
if let Some((previewing, params)) = &live {
|
||||
if on_document && let Some((previewing, params)) = &live {
|
||||
let mut preview = mem::take(&mut app.addon_dialogs.preview);
|
||||
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
|
||||
let answer = preview.run(app, *previewing, label, spec.command, params);
|
||||
@@ -115,7 +138,9 @@ fn pump_commit(app: &mut VectorcraftApp) {
|
||||
app.addon_dialogs.open = None;
|
||||
let preview = mem::take(&mut app.addon_dialogs.preview);
|
||||
// The dialog is closed already, so a refusal can only go to the status line.
|
||||
if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
|
||||
if !on_document {
|
||||
app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned());
|
||||
} else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
|
||||
app.status(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,13 +76,29 @@ fn new_app() -> VectorcraftApp {
|
||||
/// Two rectangles without a stroke, both selected.
|
||||
fn two_rects() -> VectorcraftApp {
|
||||
let mut app = new_app();
|
||||
select_two_rects(&mut app);
|
||||
app
|
||||
}
|
||||
|
||||
fn select_two_rects(app: &mut VectorcraftApp) {
|
||||
app.run("paint.setStroke", json!({"none": true})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
}
|
||||
|
||||
fn two_drawings() -> VectorcraftApp {
|
||||
let mut app = two_rects();
|
||||
app.run("file.new", json!({"width": 700, "height": 500})).unwrap();
|
||||
select_two_rects(&mut app);
|
||||
activate(&mut app, 0);
|
||||
app
|
||||
}
|
||||
|
||||
fn activate(app: &mut VectorcraftApp, index: usize) {
|
||||
app.run("document.activate", json!({"index": index})).unwrap();
|
||||
}
|
||||
|
||||
fn two_circles() -> VectorcraftApp {
|
||||
let mut app = new_app();
|
||||
let ids: Vec<u64> = [100.0, 160.0]
|
||||
@@ -280,3 +296,68 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview()
|
||||
assert_eq!(app.dialogs().unwrap().with(|h| h.open_dialogs().len()), 1);
|
||||
assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_preview_waits_for_its_opening_drawing() {
|
||||
let mut app = two_drawings();
|
||||
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
|
||||
let id = dialog_id(&app);
|
||||
set(&app, id, "layout", json!("row"));
|
||||
set(&app, id, "preview", json!(true));
|
||||
frame(&mut app);
|
||||
assert_eq!(x0(&app, 1), 30.0, "previewed in the opening drawing");
|
||||
|
||||
activate(&mut app, 1);
|
||||
let undo = undo_len(&app);
|
||||
frame(&mut app);
|
||||
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, undo), "the other drawing never shows the preview");
|
||||
assert!(!app.session.in_interaction());
|
||||
|
||||
activate(&mut app, 0);
|
||||
assert_eq!(x0(&app, 1), 100.0, "the old preview rolled back when leaving the drawing");
|
||||
frame(&mut app);
|
||||
assert_eq!(x0(&app, 1), 30.0, "the retained settings preview again on the original drawing");
|
||||
cancel(&app, id);
|
||||
frame(&mut app);
|
||||
assert_eq!(x0(&app, 1), 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() {
|
||||
let mut app = two_drawings();
|
||||
let source_undo = undo_len(&app);
|
||||
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
|
||||
let id = dialog_id(&app);
|
||||
set(&app, id, "layout", json!("row"));
|
||||
set(&app, id, "preview", json!(false));
|
||||
assert!(confirm(&app, id));
|
||||
activate(&mut app, 1);
|
||||
let target_undo = undo_len(&app);
|
||||
frame(&mut app);
|
||||
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, target_undo), "the other drawing is never rearranged or given an undo step");
|
||||
assert_eq!(app.session.active_index(), Some(1));
|
||||
activate(&mut app, 0);
|
||||
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() {
|
||||
let mut app = two_drawings();
|
||||
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
|
||||
let id = dialog_id(&app);
|
||||
set(&app, id, "layout", json!("row"));
|
||||
set(&app, id, "preview", json!(true));
|
||||
frame(&mut app);
|
||||
assert_eq!(x0(&app, 1), 30.0);
|
||||
|
||||
activate(&mut app, 1);
|
||||
app.session.begin_interaction("Other drawing's edit").unwrap();
|
||||
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
|
||||
let other = app.session.active().unwrap().doc.clone();
|
||||
cancel(&app, id);
|
||||
let context = ctx(&app);
|
||||
super::pump(&mut app, &context);
|
||||
let active = app.session.active().unwrap();
|
||||
assert_eq!(active.interaction.as_ref().map(|edit| edit.label.as_str()), Some("Other drawing's edit"));
|
||||
assert_eq!(active.doc, other);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! circles selected; Keep Originals), which previews on the canvas and runs
|
||||
//! `addon.pathtools.bridge` on OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use serde_json::{Value, json};
|
||||
@@ -50,7 +51,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
("many", FieldValue::Bool(many)),
|
||||
]);
|
||||
let lengths = general_lengths(app);
|
||||
dialogs::open(app, &SPEC, fields, move |_| {
|
||||
dialogs::open(app, &SPEC, fields, move |fields| {
|
||||
let rows = vec![
|
||||
Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)),
|
||||
Param::number("gap", tl!("Gap:"), GAP, 1.0, 2)
|
||||
@@ -67,7 +68,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
.enabled_when("many", FieldValue::Bool(true)),
|
||||
Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)),
|
||||
];
|
||||
ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true)
|
||||
ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -83,6 +84,80 @@ mod tests {
|
||||
app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn bridge_app(xs: &[f64]) -> VectorcraftApp {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let ids: Vec<u64> = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect();
|
||||
app.run("select.set", json!({"ids": ids})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn geometry(app: &VectorcraftApp) -> Vec<vectorcraft_doc::NodeKind> {
|
||||
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect()
|
||||
}
|
||||
|
||||
fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) {
|
||||
panel.click(label);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(text);
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_bridge_controls_change_the_preview_and_confirmed_geometry() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs);
|
||||
let before = panel.app().session.doc().unwrap().history.undo.len();
|
||||
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
|
||||
panel.frame();
|
||||
assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance");
|
||||
panel.click("Keep Originals");
|
||||
type_number(&mut panel, "Radius", "150");
|
||||
let id = dialog_id(&panel.app());
|
||||
assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0));
|
||||
let mut expected = bridge_app(&[100.0, 124.0]);
|
||||
expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap();
|
||||
assert_eq!(geometry(&panel.app()), geometry(&expected));
|
||||
assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge");
|
||||
|
||||
panel.click("Constant Gap");
|
||||
type_number(&mut panel, "Gap", "6");
|
||||
let params = read(&panel.app(), id, super::params);
|
||||
assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true}));
|
||||
let mut expected = bridge_app(&[100.0, 124.0]);
|
||||
expected.session.execute(super::COMMAND, ¶ms).unwrap();
|
||||
let preview = geometry(&panel.app());
|
||||
assert_eq!(preview, geometry(&expected));
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
assert_eq!(geometry(&panel.app()), preview);
|
||||
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1);
|
||||
assert!(!panel.app().any_dialog_open());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs);
|
||||
let original = geometry(&panel.app());
|
||||
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
|
||||
panel.frame();
|
||||
assert!(panel.enabled("Reach"));
|
||||
type_number(&mut panel, "Reach", "5");
|
||||
let id = dialog_id(&panel.app());
|
||||
let params = read(&panel.app(), id, super::params);
|
||||
assert_eq!(params["reach"], 5.0);
|
||||
let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]);
|
||||
expected.session.execute(super::COMMAND, ¶ms).unwrap();
|
||||
assert_eq!(geometry(&panel.app()), geometry(&expected));
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
assert_eq!(geometry(&panel.app()), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Divide into Dashes in the interface: its dialog (dash and gap lengths, Fit to Corners and Ends,
|
||||
//! Remove Gaps), which previews on the canvas and runs `addon.pathtools.divideDashes` on OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -36,7 +37,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
("removeGaps", FieldValue::Bool(true)),
|
||||
]);
|
||||
let lengths = general_lengths(app);
|
||||
dialogs::open(app, &SPEC, fields, move |_| {
|
||||
dialogs::open(app, &SPEC, fields, move |fields| {
|
||||
let rows = vec![
|
||||
Param::number("dash", tl!("Dash:"), 10.0, 1.0, 2).length(lengths).bounds(Some(*DASHES.start()), Some(*DASHES.end())),
|
||||
Param::number("gap", tl!("Gap:"), 0.0, 1.0, 2).length(lengths).bounds(Some(*GAPS.start()), Some(*GAPS.end())),
|
||||
@@ -45,6 +46,95 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
// PLAN: assumed `Param::enabled_above(key, threshold)` (pl.F4, forms-w1)
|
||||
Param::new("removeGaps", tl!("Remove Gaps"), ParamKind::bool(true)).enabled_above("gap", 0.0),
|
||||
];
|
||||
ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).previews(true)
|
||||
ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).values(Bind::bound(fields)).previews(true)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::addons::dialogs::tests::{dialog_id, open_item, read};
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::Role;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
let path = app.run("path.create", json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}]})).unwrap();
|
||||
app.run("select.set", json!({"ids": [path["id"]]})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
|
||||
if let Some(dialogs) = app.dialogs() {
|
||||
dialogs.with(|host| host.run(ui));
|
||||
}
|
||||
crate::dialogs::host::pump(app, ui.ctx());
|
||||
}
|
||||
|
||||
fn spans(app: &VectorcraftApp) -> Vec<(f64, f64)> {
|
||||
app.session.active().unwrap().doc.layers[0]
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let bounds = node.geometric_bounds().unwrap();
|
||||
(bounds.x0, bounds.x1)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Real input controls the preview and approval; Cancel restores the undivided path.
|
||||
#[test]
|
||||
fn keyboard_and_toggle_edits_control_dashes_preview_cancel_and_ok() {
|
||||
let mut expected = app();
|
||||
expected.run(COMMAND, json!({"dash": 30, "gap": 10, "fit": true, "removeGaps": false})).unwrap();
|
||||
let expected = spans(&expected);
|
||||
assert!(expected.len() > 1);
|
||||
|
||||
for cancel in [true, false] {
|
||||
let app = app();
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let selection = app.session.active().unwrap().selection.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, draw);
|
||||
panel.room(egui::vec2(800.0, 600.0));
|
||||
open_item(&mut panel.app(), "Path Precision Tools", "Divide into Dashes…");
|
||||
panel.frame();
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
let id = dialog_id(&panel.app());
|
||||
for (label, key, text, value) in [("Dash", "dash", "30 pt", 30.0), ("Gap", "gap", "10 pt", 10.0)] {
|
||||
panel.click_role(label, Role::SPIN_BUTTON);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(text);
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
assert_eq!(read(&panel.app(), id, |fields| fields.number(key)), Some(value));
|
||||
}
|
||||
panel.click_role("Fit to Corners and Ends", Role::CHECK_BOX);
|
||||
panel.click_role("Remove Gaps", Role::CHECK_BOX);
|
||||
assert_eq!(read(&panel.app(), id, |fields| fields.bool("fit")), Some(true));
|
||||
assert_eq!(read(&panel.app(), id, |fields| fields.bool("removeGaps")), Some(false));
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
let preview = spans(&panel.app());
|
||||
assert_eq!(preview.len(), expected.len());
|
||||
assert!(preview.iter().zip(&expected).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6));
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
panel.click(if cancel { "Cancel" } else { "OK" });
|
||||
assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty()));
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
if cancel {
|
||||
let app = panel.app();
|
||||
let state = app.session.active().unwrap();
|
||||
assert_eq!(state.doc, original);
|
||||
assert_eq!(state.selection, selection);
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
} else {
|
||||
assert_eq!(spans(&panel.app()), preview);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, original);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! circle to draw, or all), which previews the circles on the canvas and runs
|
||||
//! `addon.pathtools.tangentCircle` on OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -71,7 +72,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
.enabled_when("twoShapes", FieldValue::Bool(true)),
|
||||
Param::new("circle", tl!("Circle:"), ParamKind::choice(options, Some("0".into()))),
|
||||
];
|
||||
ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).previews(true)
|
||||
ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -87,6 +88,97 @@ mod tests {
|
||||
app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_radius_and_circle_edits_control_preview_cancel_and_ok() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::patterns::form_dialogs::HostedParamDialog;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = circle(&mut app, 100.0, 100.0, 10.0);
|
||||
let b = circle(&mut app, 130.0, 100.0, 10.0);
|
||||
app.run("select.set", json!({"ids": [a, b]})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
|
||||
if let Some(dialogs) = app.dialogs() {
|
||||
dialogs.with(|host| host.run(ui));
|
||||
}
|
||||
crate::dialogs::host::pump(app, ui.ctx());
|
||||
}
|
||||
|
||||
fn previewing(app: &VectorcraftApp) -> bool {
|
||||
let id = dialog_id(app);
|
||||
app.dialogs().unwrap().with(|host| host.get_by_id::<HostedParamDialog>(id).unwrap().is_previewing())
|
||||
}
|
||||
|
||||
fn count(app: &VectorcraftApp) -> usize {
|
||||
app.session.active().unwrap().doc.layers[0].children().unwrap().len()
|
||||
}
|
||||
|
||||
fn last_bounds(app: &VectorcraftApp) -> vectorcraft_geom::Rect {
|
||||
app.session.active().unwrap().doc.layers[0].children().unwrap().last().unwrap().geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
let mut expected = app();
|
||||
expected.run(super::COMMAND, json!({"radius": 20, "circle": 2})).unwrap();
|
||||
let expected = last_bounds(&expected);
|
||||
|
||||
for cancel in [true, false] {
|
||||
let app = app();
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let selection = app.session.active().unwrap().selection.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, draw);
|
||||
panel.room(egui::vec2(800.0, 600.0));
|
||||
crate::addons::dialogs::tests::open_item(&mut panel.app(), "Path Precision Tools", "Tangent Circle…");
|
||||
panel.frame();
|
||||
let id = dialog_id(&panel.app());
|
||||
assert!(previewing(&panel.app()), "the hosted dialog starts with Preview on");
|
||||
assert_eq!(count(&panel.app()), 10);
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert!(!previewing(&panel.app()));
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, original);
|
||||
panel.click_role("Radius", Role::SPIN_BUTTON);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text("20 pt");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
assert_eq!(read(&panel.app(), id, |fields| fields.number("radius")), Some(20.0));
|
||||
assert_eq!(count(&panel.app()), 2, "editing with Preview off keeps the originals");
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert!(previewing(&panel.app()));
|
||||
assert_eq!(count(&panel.app()), 8);
|
||||
assert_eq!(read(&panel.app(), id, |fields| fields.int("found")), Some(6));
|
||||
panel.click("Circle");
|
||||
panel.click("2");
|
||||
assert_eq!(read(&panel.app(), id, |fields| fields.text("circle").map(str::to_owned)), Some("2".into()));
|
||||
assert_eq!(count(&panel.app()), 3);
|
||||
let actual = last_bounds(&panel.app());
|
||||
assert!((actual.x0 - expected.x0).abs() < 1e-6 && (actual.y0 - expected.y0).abs() < 1e-6);
|
||||
assert!((actual.x1 - expected.x1).abs() < 1e-6 && (actual.y1 - expected.y1).abs() < 1e-6);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
panel.click(if cancel { "Cancel" } else { "OK" });
|
||||
assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty()));
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
if cancel {
|
||||
let app = panel.app();
|
||||
let state = app.session.active().unwrap();
|
||||
assert_eq!(state.doc, original);
|
||||
assert_eq!(state.selection, selection);
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
} else {
|
||||
assert_eq!(count(&panel.app()), 3);
|
||||
assert_eq!(last_bounds(&panel.app()), actual);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, original);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangent_circle_previews_picks_one_cancels_and_runs_on_ok() {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
|
||||
@@ -200,10 +200,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[(String, String)], go_to: &mut
|
||||
});
|
||||
let relations: Vec<Entry<String>> = RELATIONS.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect();
|
||||
Field::new(label(tl!("Select:"))).show(ui, |ui, _| {
|
||||
let picked = Select::new(label(tl!("Select:")), Bind::given(fields.relation.clone()), &relations).show(ui).value().cloned();
|
||||
if let Some(relation) = picked {
|
||||
fields.relation = relation;
|
||||
}
|
||||
Select::new(label(tl!("Select:")), Bind::bound(&mut fields.relation), &relations).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -290,10 +290,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[Value]) {
|
||||
TextField::search(label(tl!("Search images")), Bind::bound(&mut fields.search)).show(ui);
|
||||
let shows: Vec<Entry<String>> = SHOW.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect();
|
||||
Field::new(label(tl!("Show:"))).show(ui, |ui, _| {
|
||||
let picked = Select::new(label(tl!("Show:")), Bind::given(fields.show.clone()), &shows).show(ui).value().cloned();
|
||||
if let Some(show) = picked {
|
||||
fields.show = show;
|
||||
}
|
||||
Select::new(label(tl!("Show:")), Bind::bound(&mut fields.show), &shows).show(ui);
|
||||
});
|
||||
let visible = shown(rows, &fields.search, &fields.show, &Env::of(ui).folder());
|
||||
let lines: Vec<Line> = visible
|
||||
|
||||
@@ -95,6 +95,43 @@ fn selected(app: &VectorcraftApp) -> Vec<u64> {
|
||||
ids
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canceling_a_keyboard_show_filter_restores_all_rows_before_selecting() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let dir = Folder::new("cancel-show-filter");
|
||||
let (app, river, harbour, stamp) = app(&dir);
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 600.0));
|
||||
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
|
||||
panel.frame();
|
||||
panel.click_role("Show", Role::COMBO_BOX);
|
||||
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "linked");
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "all");
|
||||
for name in ["river.png", "harbour.png", "stamp.png"] {
|
||||
assert!(panel.shows(name), "canceling the filter restores {name}");
|
||||
}
|
||||
panel.click_role("All", Role::BUTTON);
|
||||
panel.click_role("Zoom to Selection", Role::CHECK_BOX);
|
||||
panel.click("Select");
|
||||
let mut want = vec![river, harbour, stamp];
|
||||
want.sort_unstable();
|
||||
assert_eq!(selected(&panel.app()), want);
|
||||
|
||||
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
|
||||
panel.frame();
|
||||
panel.click_role("Show", Role::COMBO_BOX);
|
||||
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "linked");
|
||||
assert!(panel.shows("river.png"));
|
||||
assert!(!panel.shows("harbour.png") && !panel.shows("stamp.png"));
|
||||
panel.click("Cancel");
|
||||
assert_eq!(selected(&panel.app()), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_message_says_what_was_selected_and_what_was_left_out() {
|
||||
assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images");
|
||||
|
||||
@@ -39,6 +39,41 @@ fn names(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canceling_a_keyboard_relation_choice_restores_the_original_selection_rule() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let mut app = new_app();
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let inside = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
let edge = app.run("shape.rectangle", json!({"x": 90, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 600.0));
|
||||
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
|
||||
panel.frame();
|
||||
panel.click_role("Select", Role::COMBO_BOX);
|
||||
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "inside");
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "overlap");
|
||||
panel.click("OK");
|
||||
let mut actual = panel.app().session.active().unwrap().selection.objects.clone();
|
||||
let mut expected = vec![vectorcraft_doc::NodeId(inside), vectorcraft_doc::NodeId(edge)];
|
||||
actual.sort_unstable();
|
||||
expected.sort_unstable();
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
|
||||
panel.frame();
|
||||
panel.click_role("Select", Role::COMBO_BOX);
|
||||
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "inside");
|
||||
panel.click("OK");
|
||||
assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]);
|
||||
}
|
||||
|
||||
/// A 100 × 100 document with a Banner artboard at x 150, an object in each artboard, and nothing selected.
|
||||
fn banner() -> (VectorcraftApp, u64) {
|
||||
let mut app = new_app();
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! and runs `addon.type.textTweaker` on OK.
|
||||
|
||||
use craft::menu::Node;
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use serde_json::{Value, json};
|
||||
@@ -116,7 +117,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
.enabled_when("shape", FieldValue::Text("random".into())),
|
||||
Param::new("skipSpaces", tl!("Skip Spaces"), ParamKind::bool(true)),
|
||||
]);
|
||||
ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).previews(true)
|
||||
ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).values(Bind::bound(fields)).previews(true)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -6,13 +6,91 @@ use crate::addons::dialogs::tests::{dialog_id, frame, open_item, read, set};
|
||||
|
||||
/// A window's app with one type object, selected.
|
||||
fn app() -> VectorcraftApp {
|
||||
app_with_text("abc")
|
||||
}
|
||||
|
||||
fn app_with_text(text: &str) -> VectorcraftApp {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 40, "y": 100, "text": "abc", "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
let id = app.run("text.create", json!({"x": 40, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// The real form controls the same text changes as the command, including attribute-dependent
|
||||
/// defaults, random seed and whether a space is included. Cancel restores the original text.
|
||||
#[test]
|
||||
fn keyboard_and_choice_edits_reach_text_tweaker_preview_and_approval() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::patterns::form_dialogs::HostedParamDialog;
|
||||
|
||||
fn text(app: &VectorcraftApp) -> vectorcraft_doc::TextObject {
|
||||
let state = app.session.active().unwrap();
|
||||
let node = state.doc.node(state.selection.objects[0]).unwrap();
|
||||
match &node.kind {
|
||||
vectorcraft_doc::NodeKind::Text(text) => (**text).clone(),
|
||||
_ => panic!("selected object is not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn type_number(panel: &mut Panel, label: &str, input: &str) {
|
||||
panel.click_role(label, Role::SPIN_BUTTON);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(input);
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
}
|
||||
|
||||
let params = json!({"attribute": "rotation", "from": 10.0, "to": 40.0, "shape": "random", "seed": 42, "skipSpaces": false});
|
||||
let mut expected = app_with_text("a b");
|
||||
expected.run(super::COMMAND, params.clone()).unwrap();
|
||||
let expected = text(&expected);
|
||||
for cancel in [true, false] {
|
||||
let app = app_with_text("a b");
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let selection = app.session.active().unwrap().selection.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 700.0));
|
||||
open_item(&mut panel.app(), "Type Tools", "Text Tweaker…");
|
||||
panel.frame();
|
||||
let id = dialog_id(&panel.app());
|
||||
assert!(panel.app().dialogs().unwrap().with(|host| host.get_by_id::<HostedParamDialog>(id).unwrap().is_previewing()));
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, original);
|
||||
panel.click("Attribute");
|
||||
panel.click("Character Rotation");
|
||||
assert_eq!(read(&panel.app(), id, |fields| (fields.number("from"), fields.number("to"))), (Some(0.0), Some(30.0)));
|
||||
type_number(&mut panel, "From", "10");
|
||||
type_number(&mut panel, "To", "40");
|
||||
panel.click("Shape");
|
||||
panel.click("Random");
|
||||
assert!(panel.enabled("Seed"));
|
||||
type_number(&mut panel, "Seed", "42");
|
||||
panel.click_role("Skip Spaces", Role::CHECK_BOX);
|
||||
assert_eq!(read(&panel.app(), id, super::params), params);
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, original, "Preview off leaves the text unchanged");
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert_eq!(text(&panel.app()), expected, "the real controls reach the same text formatting as automation");
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
panel.click(if cancel { "Cancel" } else { "OK" });
|
||||
assert!(!panel.app().any_dialog_open());
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
if cancel {
|
||||
let app = panel.app();
|
||||
let state = app.session.active().unwrap();
|
||||
assert_eq!(state.doc, original);
|
||||
assert_eq!(state.selection, selection);
|
||||
assert_eq!(state.history.undo.len(), undo);
|
||||
} else {
|
||||
assert_eq!(text(&panel.app()), expected);
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(panel.app().session.active().unwrap().doc, original);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_attribute_starts_from_its_own_values() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -120,7 +120,9 @@ impl VectorcraftApp {
|
||||
last_ms: 0.0,
|
||||
moved: false,
|
||||
from_worker: false,
|
||||
worker_parts: false,
|
||||
whole_frames: false,
|
||||
view_sized_bounds: None,
|
||||
web_patch_renderer: None,
|
||||
reused: None,
|
||||
waits_for_still: cfg!(target_arch = "wasm32"),
|
||||
still: None,
|
||||
@@ -242,6 +244,7 @@ impl VectorcraftApp {
|
||||
three_d_dialog: None,
|
||||
three_d: Default::default(),
|
||||
export_dialogs: Default::default(),
|
||||
package_document: None,
|
||||
web_export: Default::default(),
|
||||
flattener_preview: Default::default(),
|
||||
flatten_dialog: Default::default(),
|
||||
|
||||
@@ -25,10 +25,16 @@ pub struct CanvasCache {
|
||||
/// The frame shown was rendered on the worker: an interaction's frames stay there
|
||||
/// ([`canvas::show`]).
|
||||
pub from_worker: bool,
|
||||
/// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn
|
||||
/// again on this thread would not have matched the frame around it: until the worker's next
|
||||
/// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]).
|
||||
pub worker_parts: bool,
|
||||
/// The frame shown drew art in a way that depends on its size, or a part of it drawn again on
|
||||
/// this thread would not have matched the frame around it. Edits that reach the affected area
|
||||
/// render whole, on the worker when the frame is heavy ([`canvas::show`]).
|
||||
pub whole_frames: bool,
|
||||
/// The shown web frame can still be patched outside this enclosure in its own raster pixels.
|
||||
/// Present only when all frame-size-dependent output has a known bound.
|
||||
pub view_sized_bounds: Option<vectorcraft_geom::Rect>,
|
||||
/// Draws for a patch against a web frame with bounded view-sensitive art.
|
||||
/// The renderer of the whole frame keeps its raster and derived-art caches across these patches.
|
||||
pub web_patch_renderer: Option<Box<vectorcraft_render::Renderer>>,
|
||||
/// The frame shown holds pixels the worker copied from its last frame, and when it was shown
|
||||
/// (seconds, egui's input time): it renders whole once it has been shown for
|
||||
/// [`canvas::STILL_SECS`] with the view unmoved.
|
||||
|
||||
@@ -74,7 +74,7 @@ pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool {
|
||||
|
||||
/// Whether a 3D effect is edited in its dialog: the selection's marks and widgets give way to the dialog's gizmo.
|
||||
pub(crate) fn revolve_editing(app: &VectorcraftApp) -> bool {
|
||||
app.three_d_dialog.is_some()
|
||||
crate::dialogs::three_d::editing_current_drawing(app)
|
||||
}
|
||||
|
||||
/// The arrows the canvas takes with nothing in the window focused, as it takes every arrow while it has the focus:
|
||||
|
||||
@@ -173,7 +173,9 @@ impl Component for CanvasDrops<'_> {
|
||||
let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone())));
|
||||
let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone())));
|
||||
let symbol = Target::new(rect, view, covered, |d: &ListDrag<SymbolKey>| Some(Payload::Symbol(d.grabbed.clone())));
|
||||
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| Some(Payload::Brush(d.grabbed.clone())));
|
||||
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| {
|
||||
(d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone()))
|
||||
});
|
||||
let library = Target::new(rect, view, covered, |d: &ListDrag<LibraryKey>| Some(Payload::Library(d.grabbed.clone())));
|
||||
let panel = cx.drop_target::<PanelDrag, _>(&panel);
|
||||
let style = cx.drop_target::<StyleDrag, _>(&style);
|
||||
@@ -336,7 +338,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
|
||||
Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => {
|
||||
run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]}))
|
||||
}
|
||||
Payload::Brush(key) => match hit() {
|
||||
Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() {
|
||||
None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})),
|
||||
None => Ok(()),
|
||||
Some(hit) => {
|
||||
@@ -344,13 +346,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
|
||||
run(app, "brush.apply", json!({"name": key.name, "ids": [owner]}))
|
||||
}
|
||||
},
|
||||
Payload::Brush(_) => Ok(()),
|
||||
Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => {
|
||||
let Some(hit) = hit() else { return Ok(()) };
|
||||
let top = top_object(app, &hit)?;
|
||||
run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy}))
|
||||
}
|
||||
Payload::Style(_) => Ok(()),
|
||||
Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => {
|
||||
Payload::Panel(drag @ PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => {
|
||||
if let Some(color) = paint.color()
|
||||
&& crate::panels::proxy_cmd(app, false) == "paint.setFill"
|
||||
&& let Some((id, points)) = selected_mesh_drop(app, at, zoom)
|
||||
@@ -359,7 +362,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
|
||||
return run(app, "object.mesh.setPointColor", params);
|
||||
}
|
||||
let Some(hit) = hit() else { return Ok(()) };
|
||||
let mut params = params.clone();
|
||||
let destination = app.session.active().map(|st| st.uid);
|
||||
if rows.as_ref().is_some_and(|rows| !rows.unlinked_process_color && destination.is_some_and(|uid| uid != rows.document))
|
||||
&& paint.color().is_some()
|
||||
&& !paint.is_registration()
|
||||
{
|
||||
return Err(tl!("A linked color swatch can only be applied in its own document.").into());
|
||||
}
|
||||
let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) };
|
||||
params["ids"] = json!([owner(app, &hit)?]);
|
||||
params["focus"] = json!(false);
|
||||
let cmd = crate::panels::proxy_cmd(app, false);
|
||||
|
||||
@@ -10,7 +10,7 @@ use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::{CarriedArt, Dropped, Payload, apply_drop};
|
||||
use crate::panel_drag::PanelDrag;
|
||||
use crate::panel_drag::{PanelDrag, SwatchRows};
|
||||
use crate::panels::brushes::{BrushKey, BrushLibraries};
|
||||
use crate::panels::graphic_styles::StyleDrag;
|
||||
use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _};
|
||||
@@ -202,6 +202,32 @@ fn a_drop_runs_the_effect_of_its_payload() {
|
||||
symbol_at(&app, empty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() {
|
||||
let (mut app, ctx) = app_with_canvas();
|
||||
let make_brush = |app: &mut VectorcraftApp, width| {
|
||||
app.run("shape.rectangle", json!({"x": 15, "y": 15, "width": width, "height": 30})).unwrap();
|
||||
app.run("brush.new", json!({"name": "Shared Brush", "type": "art"})).unwrap();
|
||||
};
|
||||
make_brush(&mut app, 30);
|
||||
let document = app.session.active().unwrap().uid;
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
make_brush(&mut app, 60);
|
||||
app.run("brush.setCurrent", json!({"name": null})).unwrap();
|
||||
let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap());
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
|
||||
let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone());
|
||||
let before = brush_of(&app);
|
||||
assert!(before.is_none());
|
||||
let history = undo_len(&app);
|
||||
let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false });
|
||||
drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap();
|
||||
assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone");
|
||||
drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap();
|
||||
assert_eq!(undo_len(&app), history, "no artwork is placed on empty canvas either");
|
||||
}
|
||||
|
||||
/// A symbol of another document is added here and placed in one undo step, the source is unchanged, and a symbol of
|
||||
/// a closed document places nothing.
|
||||
#[test]
|
||||
@@ -230,6 +256,138 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() {
|
||||
|
||||
/// A colour dropped on a selected mesh recolors the point under the pointer, else the patch's four points; the same
|
||||
/// colour again records no step.
|
||||
#[test]
|
||||
fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() {
|
||||
let (mut app, ctx) = app_with_canvas();
|
||||
let name = "Shared Swatch";
|
||||
let at = Point::new(250.0, 70.0);
|
||||
let add_target = |app: &mut VectorcraftApp| {
|
||||
NodeId(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
let fill = |app: &VectorcraftApp, target| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint();
|
||||
|
||||
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
|
||||
let source = app.session.active().unwrap();
|
||||
let paint = source.doc.swatch(name).unwrap().paint.clone();
|
||||
let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true };
|
||||
let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None };
|
||||
|
||||
let local_target = add_target(&mut app);
|
||||
app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap();
|
||||
let edited = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
|
||||
drop_at(&mut app, Payload::Panel(payload.clone()), at, DropOperation::Move).unwrap();
|
||||
assert_eq!(fill(&app, local_target), edited, "a same-document drop still resolves the swatch by name");
|
||||
assert_ne!(edited, paint);
|
||||
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap();
|
||||
let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
|
||||
let target = add_target(&mut app);
|
||||
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
|
||||
drop_at(&mut app, Payload::Panel(payload), at, DropOperation::Move).unwrap();
|
||||
assert_eq!(fill(&app, target), paint);
|
||||
assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_drag_keeps_its_color_after_next_document() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::runtime::drag;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let name = "Shared Swatch";
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
|
||||
let source = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap();
|
||||
let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
|
||||
let destination = app.session.active().unwrap().uid;
|
||||
app.run("window.previousDocument", json!({})).unwrap();
|
||||
|
||||
let mut panel = Panel::new(app, |app, ui| {
|
||||
app.sync_views();
|
||||
ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
crate::panels::swatches::show(app, ui);
|
||||
});
|
||||
canvas::show(app, ui);
|
||||
});
|
||||
let label = "Shared Swatch, #ff0000";
|
||||
let from = panel.rect(label).center();
|
||||
let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0));
|
||||
panel.drag_hold_role(label, Role::LIST_ITEM, to - from);
|
||||
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the Swatches row starts a paint drag");
|
||||
panel.key(Key::F6, Modifiers::COMMAND);
|
||||
assert_eq!(panel.app().session.active().unwrap().uid, destination);
|
||||
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the drag stays held during Next Document");
|
||||
panel.release();
|
||||
|
||||
let app = panel.app();
|
||||
assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_swatch_drops_stay_in_their_source_document() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::runtime::drag;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
for spot in [false, true] {
|
||||
for (different_drawing, same_name) in [(false, false), (true, false), (true, true)] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let name = "Shared Swatch";
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap();
|
||||
if different_drawing {
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
}
|
||||
if same_name {
|
||||
app.run("swatch.new", json!({"name": name, "color": "#0000ff", "global": true})).unwrap();
|
||||
}
|
||||
let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
|
||||
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
|
||||
let destination = app.session.active().unwrap().uid;
|
||||
if different_drawing {
|
||||
app.run("window.previousDocument", json!({})).unwrap();
|
||||
}
|
||||
let mut panel = Panel::new(app, |app, ui| {
|
||||
app.sync_views();
|
||||
ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
crate::panels::swatches::show(app, ui);
|
||||
});
|
||||
canvas::show(app, ui);
|
||||
});
|
||||
let label = "Shared Swatch, #ff0000";
|
||||
let from = panel.rect(label).center();
|
||||
let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0));
|
||||
panel.drag_hold_role(label, Role::LIST_ITEM, to - from);
|
||||
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the Swatches row starts a paint drag");
|
||||
if different_drawing {
|
||||
panel.key(Key::F6, Modifiers::COMMAND);
|
||||
}
|
||||
assert_eq!(panel.app().session.active().unwrap().uid, destination);
|
||||
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the drag stays active");
|
||||
panel.release();
|
||||
let app = panel.app();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let fill = doc.node(target).unwrap().appearance.fill_paint();
|
||||
if different_drawing {
|
||||
assert_eq!(fill, Paint::solid(Color::rgb8(0, 255, 0)), "the destination fill stays unchanged");
|
||||
assert_eq!(app.ui.status, "A linked color swatch can only be applied in its own document.");
|
||||
assert_eq!(doc.swatch(name).and_then(|s| s.paint.color()), same_name.then_some(Color::rgb8(0, 0, 255)));
|
||||
} else {
|
||||
assert_eq!(fill, doc.tint_paint(name, 1.0).unwrap(), "the fill remains linked to its swatch");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() {
|
||||
use vectorcraft_doc::GradientMesh;
|
||||
|
||||
@@ -87,6 +87,8 @@ fn thumbnails(ctx: &egui::Context) -> Thumbnails<PaneKey> {
|
||||
pub struct Panes {
|
||||
/// The panes the last frame drew, as (window, pane rect).
|
||||
pub(crate) last: Vec<(Win, egui::Rect)>,
|
||||
/// The UI layer that drew the last tiled canvases.
|
||||
last_layer: Option<egui::LayerId>,
|
||||
/// The slots of `last`'s windows, in the same order: which windows they were, as document
|
||||
/// indices shift when a document closes.
|
||||
last_slots: Vec<Option<Slot>>,
|
||||
@@ -110,6 +112,7 @@ impl Panes {
|
||||
/// Forget every pane. The pictures go with the next frame that does not tile.
|
||||
fn clear(&mut self) {
|
||||
self.last.clear();
|
||||
self.last_layer = None;
|
||||
self.last_slots.clear();
|
||||
self.fits.clear();
|
||||
self.at = SplitAt::default();
|
||||
@@ -322,6 +325,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
app.canvas.panes.fits.clear();
|
||||
}
|
||||
app.canvas.panes.last.clear();
|
||||
app.canvas.panes.last_layer = None;
|
||||
app.canvas.panes.last_slots.clear();
|
||||
return false;
|
||||
}
|
||||
@@ -361,8 +365,10 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
let mut lines = std::mem::take(&mut app.canvas.panes.at);
|
||||
let placed = lines.clone();
|
||||
let mut cells: Vec<(Win, egui::Rect)> = vec![];
|
||||
let mut layer = None;
|
||||
let split = SplitViews::new("Documents", arranged, Bind::bound(&mut lines)).count(shown.len()).active(active_pane).show(ui, |ui, body| {
|
||||
cells = shown.iter().copied().zip(placed.placed(arranged, shown.len(), body.rect, body.env.direction().is_rtl())).collect();
|
||||
layer = Some(ui.layer_id());
|
||||
let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, art_area(app, *w, *cell))).collect();
|
||||
let unfitted = refit_resized(app, &areas);
|
||||
// The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar)
|
||||
@@ -381,6 +387,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
let activated = split.output.activated;
|
||||
app.canvas.panes.at = lines;
|
||||
app.canvas.panes.last = cells;
|
||||
app.canvas.panes.last_layer = layer;
|
||||
if let Some(&(w, _)) = activated.and_then(|i| app.canvas.panes.last.get(i)) {
|
||||
crate::doc_windows::show_window(app, w);
|
||||
}
|
||||
@@ -410,6 +417,20 @@ fn slot(app: &VectorcraftApp, (i, n): Win) -> Option<Slot> {
|
||||
app.session.documents().get(i).map(|d| (d.uid, n))
|
||||
}
|
||||
|
||||
/// The drawing and document point under a browser file drop in the last shown tiled panes.
|
||||
pub(crate) fn file_drop_at(app: &VectorcraftApp, pos: egui::Pos2) -> Option<(u64, Point)> {
|
||||
let panes = &app.canvas.panes;
|
||||
let layer = panes.last_layer?;
|
||||
if app.ui_ctx.as_ref().and_then(|ctx| ctx.layer_id_at(pos)).is_some_and(|front| front != layer) {
|
||||
return None;
|
||||
}
|
||||
panes.last.iter().zip(&panes.last_slots).find_map(|(&(win, cell), &shown)| {
|
||||
let (doc, _) = shown.filter(|&shown| Some(shown) == slot(app, win) && cell.contains(pos))?;
|
||||
let view = crate::doc_windows::view(app, win)?;
|
||||
view.rect.contains(pos).then(|| (doc, view.canvas(app.ui_scaling(), view.rect).to_doc(pos)))
|
||||
})
|
||||
}
|
||||
|
||||
/// The area window `w`'s view shows its art in: what its body last showed, `cell` before the first.
|
||||
fn art_area(app: &VectorcraftApp, w: Win, cell: egui::Rect) -> egui::Rect {
|
||||
crate::doc_windows::view(app, w).map(|v| v.rect).filter(|r| r.is_positive()).unwrap_or(cell)
|
||||
|
||||
@@ -55,12 +55,16 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo
|
||||
/// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve)
|
||||
/// shows in the frame it is made in, when the part's share of the frame's last whole render time
|
||||
/// is at most 8 ms, and except when that frame drew raster effects from rasters made before their
|
||||
/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame
|
||||
/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn
|
||||
/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]):
|
||||
/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What
|
||||
/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to
|
||||
/// draw the part again.
|
||||
/// objects moved ([`crate::CanvasCache::moved`]) or holds pixels copied from the worker's last frame
|
||||
/// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects,
|
||||
/// and this thread's doesn't. A web frame with known view-sensitive output bounds can still be
|
||||
/// patched outside them, accounting for the patch's rounding. Otherwise view-sensitive art or
|
||||
/// an earlier rejected patch requires a whole render ([`crate::CanvasCache::whole_frames`]).
|
||||
/// A frame that drew nothing from moved rasters or at a
|
||||
/// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction
|
||||
/// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change.
|
||||
/// Leaving an interaction still replaces the whole frame. What changed is measured by this thread's renderer: it keeps what
|
||||
/// it measures (a 3D effect's art) to draw the part again.
|
||||
pub(super) fn changed_pixels(
|
||||
app: &mut VectorcraftApp,
|
||||
key: &CacheKey,
|
||||
@@ -70,14 +74,20 @@ pub(super) fn changed_pixels(
|
||||
w: u32,
|
||||
h: u32,
|
||||
) -> Option<Option<[u32; 4]>> {
|
||||
let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| o == opts)?;
|
||||
let shown_key = app.canvas.key.as_ref()?;
|
||||
// The worker keeps its still rasters while the UI thread draws the first edit. Rendering only
|
||||
// part of a UI-thread frame could evict its own still rasters before a drag needs them.
|
||||
let starting = app.canvas.from_worker && !app.canvas.moved && key.interacting && !shown_key.interacting;
|
||||
let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| {
|
||||
o == opts || starting && vectorcraft_render::RenderOptions { interacting: opts.interacting, dragging: opts.dragging, ..o.clone() } == *opts
|
||||
})?;
|
||||
// A viewed opacity mask shows its coverage wherever its art reaches, past its object's bounds.
|
||||
if opts.mask_view.is_some() {
|
||||
return None;
|
||||
}
|
||||
let shown_key = app.canvas.key.as_ref()?;
|
||||
let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() };
|
||||
let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some());
|
||||
let (interacting, dragging) = if starting { (shown_key.interacting, shown_key.dragging) } else { (key.interacting, key.dragging) };
|
||||
let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, interacting, dragging, ..key.clone() };
|
||||
let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.reused.is_some());
|
||||
// A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]).
|
||||
let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision);
|
||||
if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way {
|
||||
@@ -94,6 +104,14 @@ pub(super) fn changed_pixels(
|
||||
None => Some(None),
|
||||
Some([x0, y0, x1, y1]) => {
|
||||
let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h));
|
||||
let patch = Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1));
|
||||
if app.canvas.whole_frames && app.canvas.view_sized_bounds.is_none_or(|bounds| !bounds.intersect(patch).is_zero_area()) {
|
||||
return None;
|
||||
}
|
||||
// A full draw can use 3D art measured here. Do not rebuild it in the scratch renderer.
|
||||
if app.canvas.view_sized_bounds.is_some() && app.canvas.renderer.measured_bytes() > 0 {
|
||||
return None;
|
||||
}
|
||||
let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h));
|
||||
(share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1]))
|
||||
}
|
||||
@@ -102,6 +120,14 @@ pub(super) fn changed_pixels(
|
||||
}
|
||||
}
|
||||
|
||||
fn web_patch_renderer(slot: &mut Option<Box<vectorcraft_render::Renderer>>) -> &mut vectorcraft_render::Renderer {
|
||||
slot.get_or_insert_with(|| {
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
renderer.threads = 0;
|
||||
Box::new(renderer)
|
||||
})
|
||||
}
|
||||
|
||||
/// `a..b` of `0..n`, grown to whole eighths of `n` and moved back into `0..n`: the parts of a
|
||||
/// frame rendered again come in few sizes, which keep the contexts the renderer keeps.
|
||||
fn in_steps(a: u32, b: u32, n: u32) -> (u32, u32) {
|
||||
@@ -597,7 +623,9 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate:
|
||||
app.canvas.reused = done.reused.then(|| frame::clock(ctx));
|
||||
app.canvas.moved = done.moved > 0;
|
||||
app.canvas.from_worker = true;
|
||||
app.canvas.worker_parts = done.view_sized;
|
||||
app.canvas.whole_frames = done.view_sized;
|
||||
app.canvas.view_sized_bounds = None;
|
||||
app.canvas.web_patch_renderer = None;
|
||||
}
|
||||
|
||||
/// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas.
|
||||
@@ -686,25 +714,38 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f
|
||||
/// key: only the document changed since the frame shown, in that part of it
|
||||
/// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's.
|
||||
///
|
||||
/// Over a frame the worker rendered, a part that drew raster effects from rasters made before
|
||||
/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]),
|
||||
/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]),
|
||||
/// would not match the frame around it: it is not drawn, false is returned, and the edits after it
|
||||
/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]).
|
||||
/// A part that drew art in a way that depends on the frame's size
|
||||
/// ([`vectorcraft_render::FrameStats::view_sized`]), draws effects at a drag's lower resolution
|
||||
/// ([`vectorcraft_render::FrameStats::previewed`]), or uses this thread's moved rasters over a
|
||||
/// worker frame, could differ from the frame around it. It is not drawn, false is returned,
|
||||
/// and the edits after it render whole until the next whole frame is
|
||||
/// shown ([`crate::CanvasCache::whole_frames`]).
|
||||
fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool {
|
||||
let Frame { key, doc, effects, view, opts, pixel, .. } = frame;
|
||||
let t0 = monotonic_ms();
|
||||
if region.is_none() {
|
||||
// Nothing in view to draw again: what was made to measure the edit isn't drawn.
|
||||
app.canvas.renderer.let_go_of_measured();
|
||||
app.canvas.renderer.finish_measurement_only();
|
||||
}
|
||||
let display = app.display_profile.transform(app.session.prefs.monitor_profile_display);
|
||||
if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) {
|
||||
let renderer = &mut app.canvas.renderer;
|
||||
let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view;
|
||||
let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts));
|
||||
if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) {
|
||||
app.canvas.worker_parts = true;
|
||||
let plain_patch = app.canvas.view_sized_bounds.is_some();
|
||||
let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer };
|
||||
let part = effects.view(|| {
|
||||
if plain_patch {
|
||||
renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts)
|
||||
} else {
|
||||
Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts))
|
||||
}
|
||||
});
|
||||
let Some(mut part) = part else {
|
||||
app.canvas.view_sized_bounds = None;
|
||||
return false;
|
||||
};
|
||||
if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 {
|
||||
app.canvas.whole_frames = true;
|
||||
app.canvas.view_sized_bounds = None;
|
||||
return false;
|
||||
}
|
||||
let width = part.width;
|
||||
@@ -712,7 +753,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
|
||||
let color = color_image(&part);
|
||||
let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
|
||||
tex.set_partial([x0 as usize, y0 as usize], color, options);
|
||||
app.canvas.moved |= app.canvas.renderer.stats.moved > 0;
|
||||
app.canvas.moved |= renderer.stats.moved > 0;
|
||||
if plain_patch {
|
||||
app.canvas.renderer.finish_measurement_only();
|
||||
}
|
||||
}
|
||||
app.canvas.key = Some((*key).clone());
|
||||
app.canvas.shown = Some(((*doc).clone(), opts.clone()));
|
||||
@@ -768,6 +812,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
|
||||
// thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a
|
||||
// part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]).
|
||||
let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc);
|
||||
if !same_doc {
|
||||
app.canvas.web_patch_renderer = None;
|
||||
}
|
||||
let settling = app.canvas.moved && !key.interacting;
|
||||
let staying = key.interacting && app.canvas.from_worker;
|
||||
// A document's first frame (opened, or its tab chosen) renders on the worker too: how long it
|
||||
@@ -791,7 +838,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
|
||||
(Some(worker), true, false) => {
|
||||
// The worker draws the frame: what this thread's renderer made to measure the edit
|
||||
// isn't drawn here.
|
||||
app.canvas.renderer.let_go_of_measured();
|
||||
app.canvas.renderer.finish_measurement_only();
|
||||
let queued = worker.submit(crate::render_worker::Job {
|
||||
key: key.clone(),
|
||||
doc: doc.clone(),
|
||||
@@ -824,6 +871,12 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
|
||||
app.perf.render_ms = monotonic_ms() - t0;
|
||||
app.canvas.last_ms = app.perf.render_ms;
|
||||
app.canvas.moved = app.canvas.renderer.stats.moved > 0;
|
||||
let stats = app.canvas.renderer.stats;
|
||||
app.canvas.whole_frames = stats.view_sized > 0 || stats.previewed > 0;
|
||||
app.canvas.view_sized_bounds = if app.canvas.waits_for_still && stats.previewed == 0 { stats.view_sized_bounds() } else { None };
|
||||
if app.canvas.view_sized_bounds.is_none() {
|
||||
app.canvas.web_patch_renderer = None;
|
||||
}
|
||||
app.canvas.from_worker = false;
|
||||
app.canvas.reused = None;
|
||||
}
|
||||
|
||||
@@ -899,6 +899,48 @@ fn halftone_preview_hides_dot_outlines_and_keeps_selection_bounds() {
|
||||
assert!(outlined(&mut app), "OK brings ordinary outlines back on the applied dots");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halftone_waits_for_the_drawing_that_opened_the_preview() {
|
||||
use crate::dialogs::{halftone, host};
|
||||
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let draw = |app: &mut VectorcraftApp, x| {
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("shape.ellipse", json!({"x": x, "y": 40, "width": 60, "height": 40})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#000000"})).unwrap();
|
||||
};
|
||||
draw(&mut app, 40);
|
||||
let first = app.session.doc().unwrap().doc.clone();
|
||||
draw(&mut app, 200);
|
||||
let second = app.session.doc().unwrap().doc.clone();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("ui.menuDialog", json!({"command": halftone::CMD})).unwrap();
|
||||
host::pump(&mut app, &ctx);
|
||||
assert!(halftone::previewing(&app));
|
||||
let id = app.effect_dialogs.halftone.as_ref().unwrap().id;
|
||||
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
app.session.begin_interaction("Other drawing's edit").unwrap();
|
||||
let dialogs = app.dialogs().unwrap();
|
||||
dialogs.with(|h| h.set_json_field(&ctx, id, "frequency", json!(25))).unwrap();
|
||||
host::pump(&mut app, &ctx);
|
||||
assert_eq!(app.session.doc().unwrap().doc, second);
|
||||
assert_eq!(app.session.doc().unwrap().interaction.as_ref().unwrap().label, "Other drawing's edit");
|
||||
dialogs.with(|h| h.confirm_by_id(&ctx, id));
|
||||
host::pump(&mut app, &ctx);
|
||||
assert!(app.any_dialog_open());
|
||||
assert_eq!(app.session.doc().unwrap().doc, second);
|
||||
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
host::pump(&mut app, &ctx);
|
||||
assert!(halftone::previewing(&app));
|
||||
crate::tests::picks::answer_dialog(&mut app, id, &[], true);
|
||||
assert!(!app.any_dialog_open());
|
||||
assert_ne!(app.session.doc().unwrap().doc, first);
|
||||
assert_eq!(app.session.documents()[1].doc, second);
|
||||
}
|
||||
|
||||
// One headless canvas frame → the shapes drawn, `Shape::Vec`s flattened.
|
||||
fn shapes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Shape> {
|
||||
let (shapes, mut delta) = frame_output(app, ctx);
|
||||
@@ -964,6 +1006,144 @@ fn an_edit_renders_only_its_part_of_the_canvas() {
|
||||
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "a new view renders all of it");
|
||||
}
|
||||
|
||||
/// An edit over art that a part of the canvas would draw with other pixels than the whole canvas
|
||||
/// does ([`vectorcraft_render::FrameStats::view_sized`]) renders all of it, on this thread too,
|
||||
/// and shows what a fresh renderer draws: a blur cropped to the view, which the frame shown drew,
|
||||
/// and an inner glow that fits the view but not the part the edit changed.
|
||||
#[test]
|
||||
fn an_edit_over_art_drawn_for_the_frames_size_renders_all_of_it() {
|
||||
keeping_color_settings(an_edit_over_art_drawn_for_the_frames_size);
|
||||
}
|
||||
|
||||
fn an_edit_over_art_drawn_for_the_frames_size() {
|
||||
for cropped in [true, false] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.ui.task_bar = false;
|
||||
app.ui.view.rulers = false;
|
||||
app.canvas.worker_started = true; // every frame on this thread, however long it takes
|
||||
app.canvas.renderer.threads = 2;
|
||||
let (rect, effect) = if cropped {
|
||||
(json!({"x": 0, "y": 0, "width": 400, "height": 300}), json!({"effect": "blur.gaussian", "params": {"radius": 8}}))
|
||||
} else {
|
||||
(json!({"x": 150, "y": 110, "width": 100, "height": 80}), json!({"effect": "stylize.innerGlow", "params": {"blur": 8}}))
|
||||
};
|
||||
let art = app.run("shape.rectangle", rect).unwrap()["id"].clone();
|
||||
let mut effect = effect;
|
||||
effect["ids"] = json!([art]);
|
||||
app.run("effect.apply", effect).unwrap();
|
||||
let id = app.run("shape.rectangle", json!({"x": 145, "y": 105, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let outside = app.run("shape.rectangle", json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
shapes(&mut app, &ctx);
|
||||
// A new view: the next frame renders whole.
|
||||
if let Some(vm) = app.view_mut() {
|
||||
(vm.zoom, vm.center) = if cropped { (16.0, Point::new(150.0, 110.0)) } else { (1.5, Point::new(200.0, 150.0)) };
|
||||
}
|
||||
// Where the canvas texture changed in a frame, and its pixels there.
|
||||
let canvas = |app: &VectorcraftApp, mut delta: egui::TexturesDelta| {
|
||||
let tex = app.canvas.texture.as_ref().map(|t| t.id());
|
||||
let set = delta.set.iter().find(|(t, _)| tex == Some(**t)).and_then(|(_, d)| d.last()).map(|d| {
|
||||
let egui::ImageData::Color(img) = &d.image;
|
||||
(d.pos, img.pixels.clone())
|
||||
});
|
||||
delta.clear();
|
||||
set
|
||||
};
|
||||
let (_, delta) = frame_output(&mut app, &ctx);
|
||||
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it");
|
||||
assert_eq!(app.canvas.renderer.stats.view_sized > 0, cropped, "the frame shown drew art for its size: {cropped}");
|
||||
assert_eq!(app.canvas.whole_frames, cropped, "the frame records whether its art depends on its size");
|
||||
app.run("paint.setFill", json!({"color": "#00ff00", "ids": [outside]})).unwrap();
|
||||
let (_, delta) = frame_output(&mut app, &ctx);
|
||||
assert!(canvas(&app, delta).is_none(), "an edit outside the view does not upload a new canvas");
|
||||
app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap();
|
||||
let (_, delta) = frame_output(&mut app, &ctx);
|
||||
let (pos, edited) = canvas(&app, delta).expect("the edit shows");
|
||||
assert!(pos.is_none(), "the edit renders all of it, cropped: {cropped}");
|
||||
assert_eq!(app.canvas.whole_frames, cropped, "the replacement records its own render stats");
|
||||
app.canvas.renderer = vectorcraft_render::Renderer::new();
|
||||
app.canvas.renderer.threads = 2;
|
||||
app.canvas.key = None;
|
||||
let (_, delta) = frame_output(&mut app, &ctx);
|
||||
let fresh = canvas(&app, delta).map(|(_, px)| px);
|
||||
assert!(fresh.as_ref() == Some(&edited), "what a fresh renderer draws, cropped {cropped}: {}", differing(&edited, fresh.as_deref()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_partial_redraws_skip_unchanged_view_sensitive_art() {
|
||||
keeping_color_settings(|| {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
|
||||
app.ui.task_bar = false;
|
||||
app.ui.view.rulers = false;
|
||||
app.canvas.worker_started = true;
|
||||
app.canvas.waits_for_still = true;
|
||||
app.canvas.renderer.threads = 0;
|
||||
let glow = app.run("shape.rectangle", json!({"x": 55, "y": 70, "width": 55, "height": 55})).unwrap()["id"].clone();
|
||||
app.run("effect.apply", json!({"ids": [glow], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap();
|
||||
let large = app.run("shape.rectangle", json!({"x": -980, "y": -700, "width": 965, "height": 1010})).unwrap()["id"].clone();
|
||||
app.run("effect.apply", json!({"ids": [large], "effect": "texture.texturizer", "params": {}})).unwrap();
|
||||
let far = app.run("shape.rectangle", json!({"x": 300, "y": 200, "width": 12, "height": 12})).unwrap()["id"].clone();
|
||||
let near = app.run("shape.rectangle", json!({"x": 60, "y": 80, "width": 12, "height": 12})).unwrap()["id"].clone();
|
||||
app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
shapes(&mut app, &ctx);
|
||||
if let Some(vm) = app.view_mut() {
|
||||
(vm.zoom, vm.center) = (1.2, Point::new(200.0, 150.0));
|
||||
}
|
||||
// Start from a full raster at the chosen view rather than waiting for the reprojected view to settle.
|
||||
app.canvas.key = None;
|
||||
let read = |app: &mut VectorcraftApp| {
|
||||
let (_, mut delta) = frame_output(app, &ctx);
|
||||
let tex = app.canvas.texture.as_ref().unwrap().id();
|
||||
delta.set.remove(&tex).and_then(|mut uploads| uploads.pop()).expect("the edit uploads canvas pixels")
|
||||
};
|
||||
let first = read(&mut app);
|
||||
assert!(first.pos.is_none());
|
||||
assert!(app.canvas.renderer.stats.view_sized > 0, "single-threaded filter layers depend on the frame size");
|
||||
let egui::ImageData::Color(first) = first.image;
|
||||
let mut composed = (*first).clone();
|
||||
for color in ["#ff0000", "#00ff00"] {
|
||||
app.run("paint.setFill", json!({"ids": [far], "color": color})).unwrap();
|
||||
let delta = read(&mut app);
|
||||
let [x, y] = delta.pos.expect("an edit away from the glow uploads only a patch");
|
||||
let egui::ImageData::Color(patch) = delta.image;
|
||||
for row in 0..patch.height() {
|
||||
let start = (y + row) * composed.width() + x;
|
||||
composed.pixels[start..start + patch.width()].copy_from_slice(&patch.pixels[row * patch.width()..(row + 1) * patch.width()]);
|
||||
}
|
||||
}
|
||||
let key = app.canvas.key.as_ref().unwrap();
|
||||
let view = app.canvas_view().unwrap();
|
||||
let (w, h, view) = frame_view(key.pixel, (key.w, key.h), &view, key.ppp);
|
||||
let (doc, still) = app.canvas.shown.as_ref().unwrap();
|
||||
let drag = vectorcraft_render::RenderOptions { interacting: true, dragging: true, ..still.clone() };
|
||||
let mut cold = vectorcraft_render::Renderer::new();
|
||||
cold.threads = 0;
|
||||
cold.render(doc, w, h, view, &drag);
|
||||
assert!(cold.stats.previewed > 0, "a cold renderer draws the large effect at drag resolution");
|
||||
app.canvas.renderer.render(doc, w, h, view, &drag);
|
||||
assert_eq!(app.canvas.renderer.stats.previewed, 0, "distant canvas patches left the full-resolution effect available for the drag");
|
||||
|
||||
// The old glow's bounds survive successive partial renders, even though neither draws it.
|
||||
app.run("paint.setFill", json!({"ids": [near], "color": "#0202ee"})).unwrap();
|
||||
let overlap = read(&mut app);
|
||||
assert!(overlap.pos.is_none(), "editing inside the old glow's bounds renders the whole frame");
|
||||
app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap();
|
||||
let restored = read(&mut app);
|
||||
assert!(restored.pos.is_none());
|
||||
let egui::ImageData::Color(restored) = restored.image;
|
||||
assert_eq!(restored.size, composed.size);
|
||||
assert!(restored.pixels == composed.pixels, "partial updates equal a full redraw: {}", differing(&composed.pixels, Some(&restored.pixels)));
|
||||
app.run("effect.apply", json!({"ids": [far], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap();
|
||||
assert!(read(&mut app).pos.is_none(), "the new glow in the part also requires a whole frame");
|
||||
});
|
||||
}
|
||||
|
||||
/// A canvas more device pixels across than the largest texture side the display supports renders
|
||||
/// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel
|
||||
/// Preview's region of document pixels stays within it too.
|
||||
@@ -1737,10 +1917,15 @@ fn dragging_with_raster_effects() {
|
||||
/// without a drag, renders without `dragging` and draws the same.
|
||||
#[test]
|
||||
fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() {
|
||||
keeping_color_settings(a_drag_at_a_lower_resolution);
|
||||
keeping_color_settings(|| a_drag_at_a_lower_resolution(false));
|
||||
}
|
||||
|
||||
fn a_drag_at_a_lower_resolution() {
|
||||
#[test]
|
||||
fn a_whole_drag_preview_keeps_the_next_canvas_render_whole() {
|
||||
keeping_color_settings(|| a_drag_at_a_lower_resolution(true));
|
||||
}
|
||||
|
||||
fn a_drag_at_a_lower_resolution(fits_frame: bool) {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.canvas.worker_started = true; // render on this thread
|
||||
@@ -1763,7 +1948,7 @@ fn a_drag_at_a_lower_resolution() {
|
||||
};
|
||||
run(&mut app, vec![]);
|
||||
if let Some(vm) = app.view_mut() {
|
||||
(vm.zoom, vm.center) = (32.0, Point::new(200.0, 155.0));
|
||||
(vm.zoom, vm.center) = (if fits_frame { 6.4 } else { 32.0 }, Point::new(200.0, 155.0));
|
||||
}
|
||||
let still = run(&mut app, vec![]).expect("the zoomed view renders");
|
||||
assert_eq!(app.canvas.renderer.stats.previewed, 0, "a still frame");
|
||||
@@ -1771,10 +1956,19 @@ fn a_drag_at_a_lower_resolution() {
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
run(&mut app, vec![egui::Event::PointerMoved(at)]);
|
||||
run(&mut app, vec![button(at, true)]);
|
||||
if fits_frame {
|
||||
// Force the first move to draw a whole frame without a previous effect raster.
|
||||
app.canvas.renderer = vectorcraft_render::Renderer::new();
|
||||
app.canvas.key = None;
|
||||
}
|
||||
for step in [1.0, 2.0] {
|
||||
let drawn = run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]).expect("each frame of the drag renders");
|
||||
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}");
|
||||
assert_eq!(app.canvas.renderer.stats.previewed, 1, "the filtered content, step {step}");
|
||||
if fits_frame {
|
||||
assert_eq!(app.canvas.renderer.stats.view_sized, 0, "only the drag budget reduced the raster");
|
||||
assert!(app.canvas.whole_frames, "a whole drag preview cannot accept a full-resolution patch");
|
||||
}
|
||||
assert!(app.canvas.moved);
|
||||
assert!(drawn != still, "the rectangle moved, step {step}");
|
||||
}
|
||||
@@ -1788,9 +1982,15 @@ fn a_drag_at_a_lower_resolution() {
|
||||
assert!(fresh.as_ref() == Some(&after), "the frame after the drag is what a fresh renderer draws: {}", differing(&after, fresh.as_deref()));
|
||||
// A dialog's preview: an interaction, and no drag.
|
||||
app.session.begin_interaction("Texturizer").unwrap();
|
||||
assert!(run(&mut app, vec![]) == Some(after), "a dialog's preview draws the effect at full resolution");
|
||||
app.session.preview("effect.setParams", &json!({"index": 0, "item": null, "ids": [id], "params": {"relief": 20}})).unwrap();
|
||||
let preview = run(&mut app, vec![]).expect("the preview renders");
|
||||
assert!(preview != after, "the preview changes the art");
|
||||
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && !k.dragging));
|
||||
assert_eq!(app.canvas.renderer.stats.previewed, 0);
|
||||
app.canvas.renderer = vectorcraft_render::Renderer::new();
|
||||
app.canvas.key = None;
|
||||
let fresh = run(&mut app, vec![]);
|
||||
assert!(fresh.as_ref() == Some(&preview), "a dialog's preview draws the effect at full resolution: {}", differing(&preview, fresh.as_deref()));
|
||||
}
|
||||
|
||||
/// Where frame `b` differs from `a`: how many pixels, the first, and the largest channel difference.
|
||||
@@ -1885,10 +2085,10 @@ fn a_drag_over_a_wide_blur() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An interaction's frames stay on the worker once it drew the frame shown, however fast that
|
||||
/// frame was: the worker's renderer keeps the effect rasters that made it fast, and this
|
||||
/// thread's renderer, without them, would draw the next frame slowly. Without a frame from the
|
||||
/// worker, a fast frame renders on this thread as before.
|
||||
/// An interaction's whole frames (here after a new zoom) stay on the worker once it drew the frame
|
||||
/// shown, however fast that frame was: the worker's renderer keeps the effect rasters that made it
|
||||
/// fast, and this thread's renderer, without them, would draw the next frame slowly. Without a
|
||||
/// frame from the worker, a fast frame renders on this thread as before.
|
||||
#[test]
|
||||
fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
@@ -1901,6 +2101,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
|
||||
app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone());
|
||||
(app.canvas.from_worker, app.canvas.last_ms) = (from_worker, 1.0);
|
||||
app.session.begin_interaction("Preview").unwrap();
|
||||
if let Some(vm) = app.view_mut() {
|
||||
vm.zoom *= 1.25;
|
||||
}
|
||||
shapes(&mut app, &ctx);
|
||||
let pending = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| k.interacting);
|
||||
assert_eq!(pending, from_worker, "sent to the worker: {from_worker}");
|
||||
@@ -1913,9 +2116,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the
|
||||
/// frame of the move: once the press's frame arrives from the worker, every move shows the
|
||||
/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters
|
||||
/// A Pen drag over a frame the worker drew draws the press's anchor and each move's curve into
|
||||
/// that frame, here, in the frame of the press or the move: each shows the document's revision and
|
||||
/// queues nothing on the worker. When the frame shown drew effect rasters
|
||||
/// from before their objects moved, when a part drawn here would have differed from it, or when
|
||||
/// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker,
|
||||
/// and the moves after the worker's frame are drawn here again. A frame of an older revision on
|
||||
@@ -1936,6 +2139,14 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
|
||||
let (worker, mut side) = WorkerSide::start();
|
||||
app.canvas.worker = Some(worker);
|
||||
app.canvas.last_ms = 50.0;
|
||||
// A new zoom: the frame shown is the worker's.
|
||||
if let Some(vm) = app.view_mut() {
|
||||
vm.zoom *= 1.25;
|
||||
}
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(side.render());
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.canvas.from_worker, "the worker drew the frame shown");
|
||||
app.select_tool("pen");
|
||||
let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision);
|
||||
let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision);
|
||||
@@ -1943,8 +2154,9 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
|
||||
let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
frame(&mut app, &ctx, vec![button(at, true)]);
|
||||
assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker");
|
||||
assert!(side.render());
|
||||
assert_eq!(shown(&app), revision(&app), "the press's anchor, the first frame of the drag, is drawn in its own frame");
|
||||
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting), "the press's frame is the interaction's");
|
||||
assert!(side.jobs.try_recv().is_err(), "the press queues nothing on the worker");
|
||||
let mut drag = |app: &mut VectorcraftApp| {
|
||||
at += vec2(9.0, 5.0);
|
||||
frame(app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
@@ -1957,7 +2169,7 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
|
||||
for case in ["moved", "differs", "slow"] {
|
||||
match case {
|
||||
"moved" => app.canvas.moved = true,
|
||||
"differs" => app.canvas.worker_parts = true,
|
||||
"differs" => app.canvas.whole_frames = true,
|
||||
_ => app.canvas.last_ms = 10_000.0,
|
||||
}
|
||||
drag(&mut app);
|
||||
@@ -1965,26 +2177,26 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
|
||||
assert!(side.render(), "{case}: the move renders on the worker");
|
||||
drag(&mut app);
|
||||
assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here");
|
||||
assert!(!app.canvas.worker_parts, "{case}");
|
||||
assert!(!app.canvas.whole_frames, "{case}");
|
||||
}
|
||||
// A worker's frame that drew art in a way that depends on its size: the move after it renders
|
||||
// on the worker too.
|
||||
app.canvas.worker_parts = true;
|
||||
app.canvas.whole_frames = true;
|
||||
drag(&mut app);
|
||||
let job = side.jobs.try_iter().last().expect("the move is on the worker");
|
||||
let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job);
|
||||
side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap();
|
||||
drag(&mut app);
|
||||
assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size");
|
||||
assert!(app.canvas.whole_frames, "the frame shown drew art that depends on its size");
|
||||
assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker");
|
||||
drag(&mut app);
|
||||
assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here");
|
||||
// A frame on its way of an older revision: the next move is drawn here, and that frame is not
|
||||
// shown when it arrives.
|
||||
app.canvas.worker_parts = true;
|
||||
app.canvas.whole_frames = true;
|
||||
drag(&mut app);
|
||||
assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way");
|
||||
app.canvas.worker_parts = false;
|
||||
app.canvas.whole_frames = false;
|
||||
for late in [false, true] {
|
||||
if late {
|
||||
assert!(side.render());
|
||||
|
||||
@@ -9,6 +9,7 @@ use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::menu::Menu;
|
||||
use craft::ui::pickers::{Select, SelectLook};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::TypeRole;
|
||||
use craft::ui::text::ZoomField;
|
||||
|
||||
@@ -47,6 +48,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let busy = busy_labels(app);
|
||||
|
||||
let (mut zoom_to, mut rotate_to, mut go, mut show_pick, mut stop) = (None, None, None, None, false);
|
||||
let mut invalid_zoom = None;
|
||||
// The readouts end the bar, the pointer's position and then the timings; a narrow bar leaves out the timings
|
||||
// first, then the position, before the message.
|
||||
let readouts = |ui: &mut Ui, _: &mut BodyCx<'_>| {
|
||||
@@ -73,8 +75,11 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
.side(SideLabel::new().kind(LabelKind::Hidden))
|
||||
.show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui));
|
||||
// The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom.
|
||||
if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) {
|
||||
zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print));
|
||||
if let Some(zoom) = zoom.inner {
|
||||
if let Some(view) = zoom.view.committed() {
|
||||
zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, app.ui_scaling()), print));
|
||||
}
|
||||
invalid_zoom = zoom.invalid_zoom.map(|invalid| invalid.message(&Env::of(ui)));
|
||||
}
|
||||
Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| {
|
||||
// Entries are keyed by index: an angle is not a hashable value.
|
||||
@@ -156,6 +161,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
if let Some(message) = invalid_zoom {
|
||||
app.status(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the bar shows as work in progress: the running script, then background jobs, opens and places. The first
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
//! Options also holds the action's function key and color (`key`, `cmd`, `shift`, `color`,
|
||||
//! `automaticAlignTo`, see [`ActionOptions`]). OK adds the set and makes it the current one,
|
||||
//! renames the set, or changes the action's name, function key and color (`ui.action.options`).
|
||||
//! An invalid `set`, `action` or function key is an error, and so is a name the list refuses. OK
|
||||
//! then changes no set or action, and the dialog stays open.
|
||||
//! An invalid `set`, `action` or function key is an error, as are a name the list refuses and a
|
||||
//! library change while editing an existing set or action. The dialog stays open with the error.
|
||||
|
||||
use craft::ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id};
|
||||
@@ -67,12 +67,14 @@ pub struct SetOptionsDialog {
|
||||
pub set: Option<usize>,
|
||||
/// The index of the action in its set; only for Action Options.
|
||||
pub action: Option<usize>,
|
||||
/// The action library revision these addresses described when Options opened.
|
||||
revision: Option<u64>,
|
||||
form: Form<SetOptionsFields>,
|
||||
}
|
||||
|
||||
impl SetOptionsDialog {
|
||||
fn new(kind: SetOptionsKind, set: Option<usize>, action: Option<usize>, fields: SetOptionsFields) -> Self {
|
||||
SetOptionsDialog { id: dialog_id(KEY), kind, set, action, form: Form::new(fields, check) }
|
||||
fn new(kind: SetOptionsKind, set: Option<usize>, action: Option<usize>, revision: Option<u64>, fields: SetOptionsFields) -> Self {
|
||||
SetOptionsDialog { id: dialog_id(KEY), kind, set, action, revision, form: Form::new(fields, check) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,14 +83,15 @@ pub fn open_new(app: &mut VectorcraftApp) {
|
||||
let sets = app.ui.actions.sets();
|
||||
let n = (1..).find(|n| !sets.contains(&format!("Set {n}").as_str())).unwrap_or(1);
|
||||
let fields = SetOptionsFields { name: format!("Set {n}"), ..SetOptionsFields::default() };
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, fields));
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, None, fields));
|
||||
}
|
||||
|
||||
/// Open Set Options for the set at `set`, if there is one.
|
||||
pub fn open(app: &mut VectorcraftApp, set: usize) {
|
||||
if let Some(name) = model::set_name(&app.ui.actions, set) {
|
||||
let fields = SetOptionsFields { name: name.to_owned(), ..SetOptionsFields::default() };
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, fields));
|
||||
let revision = app.ui.actions.revision();
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, Some(revision), fields));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,22 +108,26 @@ pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) {
|
||||
automatic_align_to: model::automatic_align_to(a),
|
||||
};
|
||||
let fields = SetOptionsFields { name: a.name.clone(), options };
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), fields));
|
||||
let revision = app.ui.actions.revision();
|
||||
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), Some(revision), fields));
|
||||
}
|
||||
|
||||
impl ActionDialog for SetOptionsDialog {
|
||||
/// What OK files, with the kind and place the dialog had.
|
||||
type Answer = (SetOptionsKind, Option<usize>, Option<usize>, SetOptionsFields);
|
||||
/// What OK files, with the kind, place and library revision the dialog had.
|
||||
type Answer = (SetOptionsKind, Option<usize>, Option<usize>, Option<u64>, SetOptionsFields);
|
||||
|
||||
fn take_ok(&mut self) -> Option<Self::Answer> {
|
||||
self.form.take().map(|fields| (self.kind, self.set, self.action, fields))
|
||||
self.form.take().map(|fields| (self.kind, self.set, self.action, self.revision, fields))
|
||||
}
|
||||
|
||||
fn answer_ok(&mut self, answer: Result<(), Label>) {
|
||||
self.form.answer(answer);
|
||||
}
|
||||
|
||||
fn run(app: &mut VectorcraftApp, (kind, set, action, fields): Self::Answer) -> Result<(), String> {
|
||||
fn run(app: &mut VectorcraftApp, (kind, set, action, revision, fields): Self::Answer) -> Result<(), String> {
|
||||
if revision.is_some_and(|revision| app.ui.actions.revision() != revision) {
|
||||
return Err("The action library changed. Reopen Options to edit it.".into());
|
||||
}
|
||||
match kind {
|
||||
SetOptionsKind::NewSet => edits::new_set(app, &fields.name),
|
||||
SetOptionsKind::Set => {
|
||||
|
||||
@@ -154,6 +154,7 @@ struct Setup {
|
||||
#[derive(Clone, Copy)]
|
||||
struct Target {
|
||||
document: u64,
|
||||
reverts: u64,
|
||||
/// The current artboard's ID, or no ID while creating a new artboard.
|
||||
artboard: Option<u32>,
|
||||
}
|
||||
@@ -556,7 +557,7 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize {
|
||||
fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option<u32>) -> Result<Value, String> {
|
||||
let host = app.dialogs().ok_or("no window")?;
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let target = Target { document: st.uid, artboard };
|
||||
let target = Target { document: st.uid, reverts: st.reverts, artboard };
|
||||
let artwork = vectorcraft_render::encode::art_bounds(&st.doc);
|
||||
let [(_, fade), (_, update_while_dragging)] = global_fields(app);
|
||||
(value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point);
|
||||
@@ -652,6 +653,9 @@ fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -
|
||||
.active()
|
||||
.filter(|st| st.uid == target.document)
|
||||
.ok_or(tl!("Artboard Options can only change the document where it was opened."))?;
|
||||
if st.reverts != target.reverts {
|
||||
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
|
||||
}
|
||||
let globals = global_changes(app, v);
|
||||
if v.new {
|
||||
let r = confirm_new(app, v)?;
|
||||
@@ -1063,4 +1067,39 @@ mod tests {
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(*app.session.doc().unwrap().doc, *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_options_refuses_a_stale_draft_after_confirmed_revert() {
|
||||
let file = std::env::temp_dir().join(format!("vectorcraft-artboard-options-revert-{}.vectorcraft", std::process::id()));
|
||||
let path = file.to_string_lossy();
|
||||
let mut app = app();
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
|
||||
app.run("file.saveAs", json!({"path": path})).unwrap();
|
||||
let original = app.session.active().unwrap();
|
||||
let (uid, reverts, artboard) = (original.uid, original.reverts, original.doc.artboards[0].id);
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
|
||||
open(&mut app).unwrap();
|
||||
set(&app, &[("name", json!("Stale Draft"))]).unwrap();
|
||||
app.run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
let _ = std::fs::remove_file(&file);
|
||||
let reverted = app.session.active().unwrap();
|
||||
assert_eq!((reverted.uid, reverted.reverts, reverted.doc.artboards[0].id), (uid, reverts + 1, artboard));
|
||||
let undo = undo_len(&app);
|
||||
|
||||
let answer = ok(&mut app);
|
||||
assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 1");
|
||||
assert_eq!(undo_len(&app), undo);
|
||||
assert_eq!(answer, Err("The document was reverted. Reopen this dialog to continue.".into()));
|
||||
assert!(is_open(&app));
|
||||
let host = app.dialogs().unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
assert_eq!(host.with(|h| h.get::<ArtboardOptionsDialog>().unwrap().value.name.clone()), "Stale Draft");
|
||||
host.with(|h| h.cancel_by_id(&ctx, id()));
|
||||
open(&mut app).unwrap();
|
||||
set(&app, &[("name", json!("Fresh Draft"))]).unwrap();
|
||||
ok(&mut app).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Fresh Draft");
|
||||
}
|
||||
}
|
||||
@@ -130,7 +130,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
let state = app
|
||||
.dialogs()
|
||||
.and_then(|d| d.with(|host| host.get_by_id::<HostedParamDialog>(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields())))));
|
||||
if let Some((previewing, p)) = state {
|
||||
if let Some((previewing, p)) = state
|
||||
&& (!previewing || app.session.has_selected_blend())
|
||||
{
|
||||
// With no blend selected, the command sets application defaults instead of previewing artwork.
|
||||
// The answer only reports the preview's status, which the preview itself shows.
|
||||
let _ = preview.run(app, previewing, PREVIEW_LABEL, CMD, &p);
|
||||
}
|
||||
@@ -139,8 +142,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
|
||||
/// OK: keeps the preview as one undo step on a blend; sets the defaults otherwise.
|
||||
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
|
||||
let on_blend = result.fields.text("__target") == Some("blend");
|
||||
if on_blend != app.session.has_selected_blend() {
|
||||
let reason = if on_blend {
|
||||
tl!("Select a blend before applying these options.")
|
||||
} else {
|
||||
tl!("Deselect any selected blends before applying the options for new blends.")
|
||||
};
|
||||
return Err(reason.to_owned());
|
||||
}
|
||||
let p = params(&result.fields);
|
||||
if result.fields.text("__target") != Some("blend") {
|
||||
if !on_blend {
|
||||
return app.run(CMD, p).map(|_| ());
|
||||
}
|
||||
let preview = app.object_dialogs.blend.take().unwrap_or_default();
|
||||
@@ -212,6 +224,62 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn app_with_smooth_blend() -> (VectorcraftApp, u64) {
|
||||
let mut app = app();
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
for x in [0, 200] {
|
||||
app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
}
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let id = app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap();
|
||||
(app, id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_blend_defaults_does_not_edit_a_later_selected_blend() {
|
||||
let (mut app, id) = app_with_smooth_blend();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.run("ui.blendOptions", json!({})).unwrap();
|
||||
assert_eq!(fields(&app).text("__target"), Some("defaults"));
|
||||
set(&app, "spacing", json!("steps"));
|
||||
set(&app, "steps", json!(7));
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
confirm(&mut app);
|
||||
assert_eq!(spec(&app, id).spacing, BlendSpacing::SmoothColor, "a newly selected blend keeps its spacing");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
assert!(is_open(&app));
|
||||
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(app.session.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_blend_options_for_a_selection_does_not_write_defaults() {
|
||||
let (mut app, id) = app_with_smooth_blend();
|
||||
let defaults = app.session.prefs.blend_options;
|
||||
app.run("ui.blendOptions", json!({})).unwrap();
|
||||
assert_eq!(fields(&app).text("__target"), Some("blend"));
|
||||
set(&app, "spacing", json!("steps"));
|
||||
set(&app, "steps", json!(7));
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
|
||||
frame(&mut app);
|
||||
assert_eq!(app.session.prefs.blend_options, defaults, "the blend preview leaves new-blend defaults intact");
|
||||
assert!(!app.session.in_interaction());
|
||||
confirm(&mut app);
|
||||
assert_eq!(app.session.prefs.blend_options, defaults);
|
||||
assert!(is_open(&app));
|
||||
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(spec(&app, id).spacing, BlendSpacing::Steps(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_on_the_blend_previews_and_keeps_smooth_color() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -21,7 +21,7 @@ super::confirm::wrapped_dialog!(BrushDeleteQuestion, StandardPrompt, KIND);
|
||||
/// What the question is about: the document it was asked in, the `brush.delete` params and whether a
|
||||
/// stroke uses one of the brushes.
|
||||
struct BrushDeleteAsk {
|
||||
doc: Option<u64>,
|
||||
doc: Option<(u64, u64)>,
|
||||
params: Value,
|
||||
used: bool,
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) {
|
||||
return;
|
||||
};
|
||||
let (message, yes, no) = words(used);
|
||||
let doc = app.session.active().map(|d| d.uid);
|
||||
let doc = app.session.active().map(|d| (d.uid, d.reverts));
|
||||
let prompt =
|
||||
StandardPrompt::custom(message).button(PromptChoice::Proceed, yes).button(PromptChoice::Cancel, no).tag(BrushDeleteAsk { doc, params, used });
|
||||
dialogs.with(|host| host.open(BrushDeleteQuestion(prompt)));
|
||||
@@ -89,7 +89,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
/// Yes on brushes that a stroke has started to use since the question opened asks again with Remove
|
||||
/// Strokes and Cancel. When another document has become the active one, nothing is deleted.
|
||||
fn confirm(app: &mut VectorcraftApp, question: BrushDeleteAsk) {
|
||||
if question.doc != app.session.active().map(|doc| doc.uid) {
|
||||
if !confirmation_is_current(app, question.doc) {
|
||||
return;
|
||||
}
|
||||
if !question.used {
|
||||
@@ -111,5 +111,19 @@ pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, bool)> {
|
||||
Some((words(used).0.to_string(), used))
|
||||
}
|
||||
|
||||
/// Whether the opening Brush confirmation still owns the active drawing's contents.
|
||||
pub(super) fn confirmation_is_current(app: &mut VectorcraftApp, opening: Option<(u64, u64)>) -> bool {
|
||||
let current = app.session.active().map(|st| (st.uid, st.reverts));
|
||||
if opening == current {
|
||||
return true;
|
||||
}
|
||||
if let (Some((document, _)), Some((active, _))) = (opening, current)
|
||||
&& document == active
|
||||
{
|
||||
app.status(tl!("The document was reverted. Reopen this dialog to continue."));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) mod tests;
|
||||
@@ -10,6 +10,15 @@ pub(in crate::dialogs) fn app() -> VectorcraftApp {
|
||||
crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()))
|
||||
}
|
||||
|
||||
/// Writes a native file for the test to revert to.
|
||||
pub(in crate::dialogs) fn save_for_revert(app: &mut VectorcraftApp, tag: &str) -> std::path::PathBuf {
|
||||
let file = std::env::temp_dir().join(format!("vectorcraft-brush-{tag}-{}.vectorcraft", std::process::id()));
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
|
||||
app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
/// Answers the open question `D` the way its button does (`Some(choice)`: the button of that choice,
|
||||
/// `None`: Cancel's close), then runs the module's `pump`.
|
||||
pub(in crate::dialogs) fn answer<D: StackDialog>(app: &mut VectorcraftApp, choice: Option<&str>, pump: fn(&mut VectorcraftApp, &egui::Context)) {
|
||||
@@ -84,3 +93,36 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() {
|
||||
assert!(stroke.width > 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_delete_approval_keeps_the_saved_brush_after_revert() {
|
||||
let mut app = app();
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
let slim = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 8})).unwrap()["id"].as_u64().unwrap();
|
||||
let tall = app.run("shape.rectangle", json!({"x": 10, "y": 30, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [slim]})).unwrap();
|
||||
let file = save_for_revert(&mut app, "delete-revert");
|
||||
let brush_height = |app: &mut VectorcraftApp| {
|
||||
let brush = app.run("brush.get", json!({"name": "Bar"})).expect("the saved brush still exists");
|
||||
let art: vectorcraft_doc::Node = serde_json::from_value(brush["art"].clone()).unwrap();
|
||||
art.geometric_bounds().unwrap().height()
|
||||
};
|
||||
let saved = brush_height(&mut app);
|
||||
let st = app.session.active().unwrap();
|
||||
let (uid, reverts) = (st.uid, st.reverts);
|
||||
|
||||
app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap();
|
||||
assert!((brush_height(&mut app) - saved).abs() > 1e-6);
|
||||
ask(&mut app, json!({"names": ["Bar"]}), false);
|
||||
app.run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
let _ = std::fs::remove_file(file);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
|
||||
assert!((brush_height(&mut app) - saved).abs() < 1e-6);
|
||||
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
answer::<BrushDeleteQuestion>(&mut app, Some("proceed"), pump);
|
||||
assert!((brush_height(&mut app) - saved).abs() < 1e-6);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
|
||||
}
|
||||
@@ -163,12 +163,13 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result<Value, Strin
|
||||
/// `object_keys` are the option keys of Options of Selected Object, which the dialog then records
|
||||
/// with the values it opened with. OK reaches [`ok`] once the dialog's own rows accept it.
|
||||
fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Option<&[&str]>) -> Result<Value, String> {
|
||||
let source = app.session.active().ok_or("no document open")?;
|
||||
let (document, reverts) = (source.uid, source.reverts);
|
||||
let ty = f.get("__type").and_then(Value::as_str).unwrap_or_default();
|
||||
let object = object_keys.is_some();
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window")?;
|
||||
// Modal: no edit changes the document while the dialog is open, so the previews read this snapshot.
|
||||
let doc = app.session.active().map(|st| st.doc.clone());
|
||||
let rows = rows(ty, object, doc, crate::canvas::rulers::unit_kind(app.session.general_unit()));
|
||||
let rows = rows(ty, object, Some(source.doc.clone()), crate::canvas::rulers::unit_kind(app.session.general_unit()));
|
||||
let title = Label::from(title(ty, object));
|
||||
let mut initial = form::fields_of(&rows, f);
|
||||
// The hidden values the rows read whole stay JSON: an untagged read makes an array a list of values.
|
||||
@@ -192,7 +193,19 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
|
||||
}
|
||||
})
|
||||
.held_ok();
|
||||
app.ui.brush_options = Some(host::open_held(app, dialog, ok).ok_or("no window")?);
|
||||
app.ui.brush_options = Some(
|
||||
host::open_held(app, dialog, move |app, result: &ParamResult| {
|
||||
match app.session.active().filter(|st| st.uid == document) {
|
||||
Some(source) if source.reverts != reverts => {
|
||||
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
|
||||
}
|
||||
None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()),
|
||||
_ => {}
|
||||
}
|
||||
ok(app, result)
|
||||
})
|
||||
.ok_or("no window")?,
|
||||
);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -672,3 +685,27 @@ fn confirm(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod document_tests {
|
||||
use super::*;
|
||||
use crate::dialogs::tests_export;
|
||||
|
||||
#[test]
|
||||
fn brush_options_does_not_rename_the_other_drawings_brush() {
|
||||
let (mut app, _) = tests_export::app(1);
|
||||
open(&mut app, Some("Diamonds")).unwrap();
|
||||
tests_export::set(&mut app, "name", json!("Source diamonds"));
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let previous = app.run("brush.get", json!({"name": "Diamonds"})).unwrap();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let error = tests_export::try_confirm(&mut app).expect_err("Brush Options must refuse the other drawing");
|
||||
assert!(error.contains("original drawing"), "{error}");
|
||||
assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap(), previous);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(tests_export::fields(&app)["name"], "Source diamonds");
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
tests_export::try_confirm(&mut app).unwrap();
|
||||
assert_eq!(app.run("brush.get", json!({"name": "Source diamonds"})).unwrap()["name"], "Source diamonds");
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ super::confirm::wrapped_dialog!(ReplaceArtQuestion, StandardPrompt, KIND);
|
||||
|
||||
/// What the question is about: the document it was asked in, the brush and the art.
|
||||
struct ReplaceArtAsk {
|
||||
doc: Option<u64>,
|
||||
doc: Option<(u64, u64)>,
|
||||
name: String,
|
||||
ids: Vec<u64>,
|
||||
}
|
||||
@@ -59,7 +59,7 @@ pub fn ask(app: &mut VectorcraftApp, name: &str, ids: &[u64]) {
|
||||
app.status("no window");
|
||||
return;
|
||||
};
|
||||
let doc = app.session.active().map(|d| d.uid);
|
||||
let doc = app.session.active().map(|d| (d.uid, d.reverts));
|
||||
let prompt = StandardPrompt::custom(tl!(
|
||||
"Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?"
|
||||
))
|
||||
@@ -86,7 +86,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
|
||||
/// Runs `brush.replaceArt`. When another document has become the active one, no brush changes.
|
||||
fn confirm(app: &mut VectorcraftApp, question: ReplaceArtAsk, apply: bool) {
|
||||
if question.doc != app.session.active().map(|doc| doc.uid) {
|
||||
if !super::brush_delete::confirmation_is_current(app, question.doc) {
|
||||
return;
|
||||
}
|
||||
let params = json!({"name": question.name, "ids": question.ids, "applyToStrokes": apply});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
use super::super::brush_delete::tests::{answer, app};
|
||||
use super::super::brush_delete::tests::{answer, app, save_for_revert};
|
||||
use super::*;
|
||||
|
||||
fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> u64 {
|
||||
@@ -95,3 +95,30 @@ fn a_button_changes_no_brush_after_another_document_became_active() {
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_replace_approval_keeps_the_saved_brush_art_after_revert() {
|
||||
let mut app = app();
|
||||
let (_, tall) = used_brush(&mut app);
|
||||
let thick = rect(&mut app, 10.0, 65.0, 40.0, 30.0);
|
||||
let file = save_for_revert(&mut app, "replace-revert");
|
||||
let st = app.session.active().unwrap();
|
||||
let (uid, reverts) = (st.uid, st.reverts);
|
||||
|
||||
app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap();
|
||||
assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6);
|
||||
replace(&mut app, "Bar", &[thick]);
|
||||
assert!(asks(&app));
|
||||
app.run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
let _ = std::fs::remove_file(file);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
|
||||
assert!(st.doc.node(NodeId(thick)).is_some(), "the restored drawing shares the same local source ID");
|
||||
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6);
|
||||
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
answer::<ReplaceArtQuestion>(&mut app, Some("proceed"), pump);
|
||||
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6, "the stale answer leaves the restored brush intact");
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
|
||||
}
|
||||
@@ -25,18 +25,21 @@
|
||||
//! <https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html>.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use craft::behavior::{Mixed, Selection, SelectionChange, keyed};
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::primitives::{HAlign, IconSpec, TextRun};
|
||||
use craft::ui::runtime::env::{Env, LengthUnits};
|
||||
use craft::ui::runtime::env::{Env, Label, LengthUnits};
|
||||
use craft::ui::runtime::measure;
|
||||
use craft::ui::runtime::overlay::CloseReason;
|
||||
use craft::ui::runtime::words::CommonWords;
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::tabs::{Tab, TabKind, TabStrip};
|
||||
@@ -44,11 +47,14 @@ use craft::ui::text::NumberField;
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
use egui::{Context, Ui};
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Selection as ArtworkSelection;
|
||||
use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::panels::paragraph::BulletGlyph;
|
||||
|
||||
use super::preview::LivePreview;
|
||||
|
||||
/// The dialog kind of Bullets and Numbering.
|
||||
pub const KIND: &str = "bulletsAndNumbering";
|
||||
|
||||
@@ -122,9 +128,73 @@ pub(crate) struct BulletsDialog {
|
||||
hanging: bool,
|
||||
/// The General unit the indent fields show; the pump keeps it current.
|
||||
lengths: LengthUnits,
|
||||
active_document: bool,
|
||||
held: HeldAnswer<Map<String, Value>>,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
/// The preview from the opening drawing and the interaction that owns its undo snapshot.
|
||||
pub(crate) struct Preview {
|
||||
document: (u64, u64),
|
||||
live: LivePreview,
|
||||
selection: Option<Weak<ArtworkSelection>>,
|
||||
}
|
||||
|
||||
impl Preview {
|
||||
fn owns_interaction(&self, app: &VectorcraftApp) -> bool {
|
||||
let Some(selection) = &self.selection else { return false };
|
||||
app.session.active().is_some_and(|state| {
|
||||
(state.uid, state.reverts) == self.document
|
||||
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
|
||||
})
|
||||
}
|
||||
|
||||
fn update(&mut self, app: &mut VectorcraftApp, fields: Map<String, Value>) {
|
||||
let Some(state) = app.session.active().filter(|state| (state.uid, state.reverts) == self.document) else { return };
|
||||
if !self.owns_interaction(app) {
|
||||
self.live = LivePreview::default();
|
||||
self.selection = None;
|
||||
if state.interaction.is_some() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let on = changes(&fields);
|
||||
let ran = self.live.run(app, on, tl!("Bullets and Numbering"), CMD, &Value::Object(fields)).is_some();
|
||||
if !on {
|
||||
self.selection = None;
|
||||
} else if ran {
|
||||
self.selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection));
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, app: &mut VectorcraftApp, fields: Map<String, Value>) -> Result<(), String> {
|
||||
if !changes(&fields) {
|
||||
if self.owns_interaction(app) {
|
||||
std::mem::take(&mut self.live).cancel(app);
|
||||
self.selection = None;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(state) = app.session.active().filter(|state| state.uid == self.document.0) else {
|
||||
return Err(tl!("Bullets and Numbering can only change the document where it was opened.").to_owned());
|
||||
};
|
||||
if state.reverts != self.document.1 {
|
||||
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
|
||||
}
|
||||
if app.session.in_interaction() && !self.owns_interaction(app) {
|
||||
return Err(tl!("Finish the active edit before applying Bullets and Numbering.").to_owned());
|
||||
}
|
||||
self.selection = None;
|
||||
std::mem::take(&mut self.live).commit(app, CMD, Value::Object(fields)).map(drop)
|
||||
}
|
||||
|
||||
fn cancel(self, app: &mut VectorcraftApp) {
|
||||
if self.owns_interaction(app) {
|
||||
self.live.cancel(app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of list `list` is, as the `list` field names it.
|
||||
fn kind(list: Option<ParaList>) -> &'static str {
|
||||
match list {
|
||||
@@ -144,8 +214,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?),
|
||||
};
|
||||
crate::panels::character::text_style(app).ok_or("select some type first")?;
|
||||
let active = app.session.active().ok_or("no document")?;
|
||||
let document = (active.uid, active.reverts);
|
||||
// A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own.
|
||||
std::mem::take(&mut app.bullets_preview).cancel(app);
|
||||
if let Some(old) = app.bullets_preview.take() {
|
||||
old.cancel(app);
|
||||
}
|
||||
// While typing, the dialog acts on the paragraphs of the text being edited.
|
||||
let mut targets = json!({});
|
||||
if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? {
|
||||
@@ -192,9 +266,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
targets,
|
||||
hanging: false,
|
||||
lengths: crate::canvas::general_lengths(app),
|
||||
active_document: true,
|
||||
held: HeldAnswer::default(),
|
||||
open: true,
|
||||
};
|
||||
host.with(|h| h.open(dialog));
|
||||
app.bullets_preview = Some(Preview { document, live: LivePreview::default(), selection: None });
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -468,8 +545,7 @@ fn changes(p: &Map<String, Value>) -> bool {
|
||||
}
|
||||
|
||||
impl StackDialog for BulletsDialog {
|
||||
/// The `text.setFormat` parameters OK runs.
|
||||
type Result = Value;
|
||||
type Result = ();
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
dialog_id(KIND)
|
||||
@@ -479,20 +555,46 @@ impl StackDialog for BulletsDialog {
|
||||
Some(KIND)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Value>> {
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
|
||||
let common = Env::of(ui).words::<CommonWords>();
|
||||
let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)];
|
||||
let finish = self.held.is_accepted();
|
||||
let refusal = self.held.refusal().map(|(reason, _)| reason.clone());
|
||||
let buttons = [
|
||||
FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(true).enabled(!self.held.is_waiting()),
|
||||
FooterButton::new(common.cancel.clone(), DialogRole::Cancel),
|
||||
];
|
||||
let mut open = self.open;
|
||||
let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open));
|
||||
let shown = dialog.show(ui, |ui, _| self.body(ui));
|
||||
let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)).refusal(move || refusal.clone());
|
||||
let shown = dialog.show(ui, |ui, cx| {
|
||||
if finish && !measure::active(ui.ctx()) {
|
||||
cx.request_close_as(CloseReason::Activated);
|
||||
}
|
||||
self.body(ui);
|
||||
});
|
||||
self.open = open;
|
||||
let DialogOutput { closed, picked, .. } = shown.output;
|
||||
closed?;
|
||||
Some(if picked == Some(OK) { DialogResult::Ok(Value::Object(params(self))) } else { DialogResult::Cancel })
|
||||
if picked == Some(OK) && !self.held.is_waiting() {
|
||||
self.held.file(params(self));
|
||||
}
|
||||
match closed {
|
||||
Some(CloseReason::Activated) if finish => self.held.finish().map(|_| DialogResult::Ok(())),
|
||||
Some(_) => Some(DialogResult::Cancel),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &Context) -> Option<Value> {
|
||||
Some(Value::Object(params(self)))
|
||||
fn confirm(&mut self, _: &Context) -> Option<()> {
|
||||
if self.held.is_accepted() {
|
||||
return self.held.finish().map(drop);
|
||||
}
|
||||
if !self.held.is_waiting() {
|
||||
self.held.file(params(self));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.held.state()
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
@@ -515,38 +617,41 @@ impl StackDialog for BulletsDialog {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs once per frame: keeps the indent fields' unit current, shows the dialog's values on the type while they change
|
||||
/// something, and answers a finished dialog: OK keeps the preview as one undo step, Cancel (Escape and the close box
|
||||
/// too) and an OK that changes nothing put the type back.
|
||||
/// Shows the draft on its opening drawing and answers OK before the dialog closes.
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
|
||||
let Some(host) = app.dialogs() else { return };
|
||||
if let Some(result) = host.with(|h| h.take::<BulletsDialog>()) {
|
||||
let live = std::mem::take(&mut app.bullets_preview);
|
||||
match result {
|
||||
DialogResult::Ok(Value::Object(p)) if changes(&p) => {
|
||||
if let Err(e) = live.commit(app, CMD, Value::Object(p)) {
|
||||
app.status(e);
|
||||
// The dialog is gone: a preview the refused OK left running goes with it. Nothing runs
|
||||
// when the refusal came before the interaction began, which is the right outcome too.
|
||||
let _ = app.session.cancel_interaction();
|
||||
}
|
||||
}
|
||||
_ => live.cancel(app),
|
||||
}
|
||||
}
|
||||
let Some(mut preview) = app.bullets_preview.take() else { return };
|
||||
let active_document = app.session.active().is_some_and(|state| (state.uid, state.reverts) == preview.document);
|
||||
let lengths = crate::canvas::general_lengths(app);
|
||||
// The host's lock is released before the preview runs: a command never runs inside `with`.
|
||||
let Some(p) = host.with(|h| {
|
||||
let Some((fields, answer)) = host.with(|h| {
|
||||
h.get_mut::<BulletsDialog>().map(|d| {
|
||||
d.lengths = lengths;
|
||||
params(d)
|
||||
let fields = params(d);
|
||||
if (active_document && !d.active_document) || d.held.refusal().is_some_and(|(_, at)| *at != fields) {
|
||||
d.held.clear_refusal();
|
||||
}
|
||||
d.active_document = active_document;
|
||||
(fields, d.held.take())
|
||||
})
|
||||
}) else {
|
||||
preview.cancel(app);
|
||||
return;
|
||||
};
|
||||
let mut live = std::mem::take(&mut app.bullets_preview);
|
||||
let _ = live.run(app, changes(&p), tl!("Bullets and Numbering"), CMD, &Value::Object(p));
|
||||
app.bullets_preview = live;
|
||||
if let Some(answer) = answer {
|
||||
let result = preview.apply(app, answer).map_err(Label::from);
|
||||
let accepted = result.is_ok();
|
||||
host.with(|h| {
|
||||
if let Some(dialog) = h.get_mut::<BulletsDialog>() {
|
||||
dialog.held.answer(result);
|
||||
}
|
||||
});
|
||||
if accepted {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
preview.update(app, fields);
|
||||
}
|
||||
app.bullets_preview = Some(preview);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -618,13 +723,23 @@ mod tests {
|
||||
crate::dialogs::host::pump(app, &ctx);
|
||||
}
|
||||
|
||||
/// OK on the open dialog, as automation answers it, then the frame's pump.
|
||||
fn ok(app: &mut VectorcraftApp) {
|
||||
fn press_ok(app: &mut VectorcraftApp) {
|
||||
let (ctx, (id, _)) = (window(app), top(app));
|
||||
assert!(app.dialogs().expect("a window").with(|h| h.confirm_by_id(&ctx, id)), "OK is enabled");
|
||||
let host = app.dialogs().unwrap();
|
||||
host.with(|h| {
|
||||
assert!(!h.confirm_by_id(&ctx, id), "the app must accept the answer first");
|
||||
assert_eq!(h.held_state(id), Some(HeldOk::Waiting));
|
||||
});
|
||||
frame(app);
|
||||
}
|
||||
|
||||
/// Files OK and closes with the accepted answer, as the view or automation does.
|
||||
fn ok(app: &mut VectorcraftApp) {
|
||||
press_ok(app);
|
||||
let (ctx, (id, _)) = (window(app), top(app));
|
||||
assert!(app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)), "the app accepted OK");
|
||||
}
|
||||
|
||||
/// Cancel on the open dialog, as Esc gives it, then the frame's pump.
|
||||
fn cancel(app: &mut VectorcraftApp) {
|
||||
let (ctx, (id, _)) = (window(app), top(app));
|
||||
@@ -641,6 +756,127 @@ mod tests {
|
||||
with_dialog(app, |d| params(d))
|
||||
}
|
||||
|
||||
fn other_drawing(app: &mut VectorcraftApp) -> u64 {
|
||||
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 15, "y": 10, "text": "Other\nDrawing", "area": {"width": 200, "height": 100}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bullets_preview_pauses_in_another_drawing() {
|
||||
let (mut app, id) = app();
|
||||
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
|
||||
pick_preset(&mut app, "bullet", Some("square"));
|
||||
let other = other_drawing(&mut app);
|
||||
let before = first(&app, other);
|
||||
|
||||
frame(&mut app);
|
||||
|
||||
assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by preview");
|
||||
assert!(!app.session.in_interaction());
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
frame(&mut app);
|
||||
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
|
||||
ok(&mut app);
|
||||
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bullets_ok_does_not_change_the_other_drawings_type() {
|
||||
let (mut app, id) = app();
|
||||
let opening = first(&app, id);
|
||||
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
|
||||
pick_preset(&mut app, "number", Some("arabic"));
|
||||
let other = other_drawing(&mut app);
|
||||
let before = first(&app, other);
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
|
||||
press_ok(&mut app);
|
||||
|
||||
assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by OK");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
|
||||
assert!(with_dialog(&app, |d| matches!(d.held.state(), Some(HeldOk::Refused(_)))));
|
||||
assert_eq!(fields(&app)["number"], "arabic");
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
assert_eq!(first(&app, id), opening);
|
||||
frame(&mut app);
|
||||
assert!(with_dialog(&app, |d| d.held.state().is_none()));
|
||||
ok(&mut app);
|
||||
assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bullets_preview_and_ok_leave_restored_paragraphs_unchanged() {
|
||||
let (mut app, id) = app();
|
||||
let dir = vectorcraft_testkit::TempDir::new("bullets-revert");
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
|
||||
let saved = paras(&app, id);
|
||||
app.run("file.saveAs", json!({"path": dir.join("Paragraphs.vectorcraft")})).unwrap();
|
||||
app.run("text.setFormat", json!({"ids": [id], "leftIndent": 19})).unwrap();
|
||||
let drawing = app.session.active().unwrap();
|
||||
let (uid, reverts) = (drawing.uid, drawing.reverts);
|
||||
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
|
||||
pick_preset(&mut app, "bullet", Some("square"));
|
||||
frame(&mut app);
|
||||
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
|
||||
|
||||
app.run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
let restored = app.session.active().unwrap();
|
||||
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
|
||||
let undo = restored.history.undo.len();
|
||||
frame(&mut app);
|
||||
assert_eq!(paras(&app, id), saved);
|
||||
assert!(!app.session.in_interaction());
|
||||
press_ok(&mut app);
|
||||
assert!(with_dialog(&app, |dialog| matches!(dialog.held.state(), Some(HeldOk::Refused(_)))));
|
||||
assert_eq!(paras(&app, id), saved);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bullets_cancel_keeps_the_other_drawings_pending_edit() {
|
||||
let (mut app, id) = app();
|
||||
let opening = first(&app, id);
|
||||
let other = other_drawing(&mut app);
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
|
||||
pick_preset(&mut app, "bullet", Some("square"));
|
||||
frame(&mut app);
|
||||
assert!(app.session.in_interaction());
|
||||
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
app.session.begin_interaction("Other paragraph edit").unwrap();
|
||||
app.session.preview("text.setFormat", &json!({"ids": [other], "leftIndent": 41})).unwrap();
|
||||
let editing = first(&app, other);
|
||||
assert_eq!(editing.1, 41.0);
|
||||
cancel(&mut app);
|
||||
|
||||
assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit");
|
||||
assert_eq!(first(&app, other), editing);
|
||||
app.session.commit_interaction().unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
assert_eq!(first(&app, id), opening);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepted_bullets_close_on_the_next_view_pass() {
|
||||
let (mut app, id) = app();
|
||||
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
|
||||
pick_preset(&mut app, "bullet", Some("square"));
|
||||
press_ok(&mut app);
|
||||
let ctx = window(&app);
|
||||
|
||||
crate::tests_synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
|
||||
}
|
||||
|
||||
/// `ui.bulletsAndNumbering` opens on the selected type's values; a preset, Alignment and the
|
||||
/// indents show on the type at once, and OK keeps them as one `text.setFormat`, which one Undo
|
||||
/// takes back.
|
||||
|
||||
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user