mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 20:18:38 -05:00
Merge pull request #9062 from dotCooCoo/feat/scripts-api-d8-placed-raster
Scripts: documents give scripts their placed and raster images
This commit is contained in:
5 files changed
+154
-20
No files matched your search
@@ -27,8 +27,10 @@
|
||||
//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only
|
||||
//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file.
|
||||
//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of
|
||||
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a
|
||||
//! matrix with no area or one that puts a corner of the image outside the canvas is refused.
|
||||
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`,
|
||||
//! and assigning the matrix it reads runs nothing; a matrix with no area, one that puts a
|
||||
//! corner of the image outside the canvas, or one a nearly singular image cannot reach exactly
|
||||
//! is refused.
|
||||
//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system.
|
||||
|
||||
use std::cell::RefCell;
|
||||
@@ -291,7 +293,8 @@ fn doc_raster(h: &Host, a: &[Data]) -> Answer {
|
||||
// ---- files ----
|
||||
|
||||
/// Whether the script may read `path` now by its own read scope and the read roots
|
||||
/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read.
|
||||
/// ([`crate::file_access::ScriptGate`]), without the open documents' files, or the files they link
|
||||
/// to, that a command may also read.
|
||||
fn may_read(h: &Host, path: &str) -> bool {
|
||||
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
|
||||
crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok()
|
||||
@@ -496,16 +499,50 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
return Err(HostError::Range("the matrix puts the image outside the canvas".into()));
|
||||
}
|
||||
let old = im.xf;
|
||||
// The coordinate frame only changes the signs of the linear part, so any change to it
|
||||
// counts; the offsets compare in points, which absorbs the rounding of the frame.
|
||||
let same = old.as_coeffs().iter().zip(target.as_coeffs()).enumerate().all(|(k, (o, t))| if k < 4 { *o == t } else { (o - t).abs() <= 1e-9 });
|
||||
if same {
|
||||
// Unchanged means the numbers the `matrix` getter reports, compared exactly, so a small
|
||||
// change such as `mValueTX` from 0 to 5e-10 still moves the image. A change that the
|
||||
// conversion to document space rounds away leaves the image's matrix as it is and runs nothing.
|
||||
// A coefficient the script left as the getter reports keeps the image's own value, so the
|
||||
// conversion back does not shift an untouched axis.
|
||||
let olds = old.as_coeffs();
|
||||
let [a0, b0, c0, d0, e0, f0] = olds;
|
||||
let reported = match h.dom.coords.get() {
|
||||
Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0],
|
||||
Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top],
|
||||
};
|
||||
let mut wanted = target.as_coeffs();
|
||||
for ((w, o), (r, v)) in wanted.iter_mut().zip(olds).zip(reported.iter().zip(m.iter())) {
|
||||
if r == v {
|
||||
*w = o;
|
||||
}
|
||||
}
|
||||
if wanted == olds {
|
||||
return Ok(None);
|
||||
}
|
||||
if !area_of(old) {
|
||||
return Err(HostError::Error("the image has no area to transform".into()));
|
||||
}
|
||||
Ok(Some((target * old.inverse()).as_coeffs()))
|
||||
let target = Affine::new(wanted);
|
||||
let [ta, tb, tc, td, te, tf] = wanted;
|
||||
if [ta, tb, tc, td] == [a0, b0, c0, d0] {
|
||||
// A move alone: the offset difference, without the error an inverse adds.
|
||||
return Ok(Some([1.0, 0.0, 0.0, 1.0, te - e0, tf - f0]));
|
||||
}
|
||||
// A nearly singular image loses precision through the inverse; refuse a change that would
|
||||
// not land where the script asked rather than move the image somewhere else.
|
||||
let delta = target * old.inverse();
|
||||
let landed = delta * old;
|
||||
if landed.as_coeffs() == olds {
|
||||
return Ok(None);
|
||||
}
|
||||
let close = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].iter().all(|&(x, y)| {
|
||||
let (p, q) = (landed * Point::new(x, y), target * Point::new(x, y));
|
||||
(p.x - q.x).abs() <= 1e-6 && (p.y - q.y).abs() <= 1e-6
|
||||
});
|
||||
if !close || !area_of(landed) {
|
||||
return Err(HostError::Range("the matrix cannot be applied exactly to this image".into()));
|
||||
}
|
||||
Ok(Some(delta.as_coeffs()))
|
||||
})?;
|
||||
if let Some(d) = delta {
|
||||
edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?;
|
||||
@@ -653,7 +690,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
let mut placed = named(vec![
|
||||
("file", property(l, placed_file, placed_set_file), typed("File")),
|
||||
("relink", method(l, placed_relink), returns("undefined", &[("relinkFile", "File")])),
|
||||
("relink", method(l, placed_relink), returns("undefined", &[("relinkFrom", "File")])),
|
||||
("embed", method(l, placed_embed), returns("undefined", &[])),
|
||||
("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")),
|
||||
("boundingBox", get(l, placed_box), typed("Array")),
|
||||
|
||||
@@ -448,6 +448,55 @@ fn image_matrix_assignment_transforms_the_image() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiny_matrix_change_still_transforms_the_image() {
|
||||
let base = folder("matrix-tiny");
|
||||
let g = base.join("main/g.png");
|
||||
std::fs::write(&g, gray_png(10, 20)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &g, false);
|
||||
let before = undo_steps(&s);
|
||||
let tx = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Image(im) => im.xf.as_coeffs()[4],
|
||||
_ => panic!("not an image"),
|
||||
};
|
||||
let old = tx(&s);
|
||||
log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueTX = m.mValueTX + 5e-10; r.matrix = m;");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert!(tx(&s) != old, "the image did not move");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_placed_item_is_not_a_relative_object() {
|
||||
let base = folder("stale-relative");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
place(&mut s, &a, true);
|
||||
place(&mut s, &a, true);
|
||||
place(&mut s, &a, true);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, p = d.placedItems[0], q = d.placedItems[1], r = d.placedItems[2], m = [];\
|
||||
r.move(q, ElementPlacement.PLACEBEFORE); m.push('live');\
|
||||
var n = d.placedItems.add(); n.file = new File('{}'); r.move(n, ElementPlacement.PLACEAFTER); m.push('added');\
|
||||
p.embed();\
|
||||
try {{ r.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\
|
||||
try {{ r.duplicate(p, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\
|
||||
n.embed();\
|
||||
try {{ r.move(n, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\
|
||||
try {{ r.duplicate(n, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\
|
||||
vc.log(m);",
|
||||
js_path(&a)
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(["live", "added", "Stale page item", "Stale page item", "Stale page item", "Stale page item"])]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_matrix_refuses_bad_values_without_changing_the_image() {
|
||||
let base = folder("matrix-bad");
|
||||
@@ -599,16 +648,19 @@ fn stale_and_foreign_placed_items_are_refused() {
|
||||
std::fs::write(&a, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &a, true);
|
||||
place(&mut s, &a, false);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var p = app.activeDocument.placedItems[0], m = []; p.remove();\
|
||||
try { p.relink(null); } catch (e) { m.push(e.message); }\
|
||||
try { app.activeDocument.placedItems.add().file; RasterItem.prototype.embedded.call(1); } catch (e) { m.push(e.name); }\
|
||||
var g = Object.getOwnPropertyDescriptor(RasterItem.prototype, 'embedded').get;\
|
||||
try { g.call(1); } catch (e) { m.push(e.name); }\
|
||||
m.push(g.call(app.activeDocument.rasterItems[0]));\
|
||||
try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Stale page item", "TypeError", "this is not a PlacedItem"])]);
|
||||
assert_eq!(out, vec![json!(["Stale page item", "TypeError", true, "this is not a PlacedItem"])]);
|
||||
assert!(s.active().unwrap().doc.node(id).is_none());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
@@ -583,19 +583,24 @@ fn more_settings_rows(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUni
|
||||
let shown = f64::from(shown_columns(s));
|
||||
let field = NumberField::new(columns.clone(), Bind::given(Some(shown))).range(1.0..=n).step(1.0).commit_decimals(0).enabled(several && grid);
|
||||
if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) {
|
||||
// A column count replaces a preset's rows.
|
||||
s.columns = v.round().clamp(1.0, n) as u32;
|
||||
s.rows = 0;
|
||||
set_columns(s, v.round().clamp(1.0, n) as u32);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The columns More Settings shows: for a grid by column made with `file.new`'s `rows`, the columns
|
||||
/// those rows give the current number of artboards, as `file.new` lays them out; otherwise the
|
||||
/// stored count. At most one for each artboard.
|
||||
/// stored count, where a stored 0 shows the columns `file.new` lays out for the layout. At most
|
||||
/// one for each artboard.
|
||||
fn shown_columns(s: &DocSettings) -> u32 {
|
||||
let n = s.artboards.max(1);
|
||||
if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { u32::try_from(s.grid_columns()).unwrap_or(n) } else { s.columns.max(1).min(n) }
|
||||
if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 {
|
||||
u32::try_from(s.grid_columns()).unwrap_or(n)
|
||||
} else if s.columns == 0 {
|
||||
u32::try_from(s.grid_columns()).unwrap_or(n).clamp(1, n)
|
||||
} else {
|
||||
s.columns.min(n)
|
||||
}
|
||||
}
|
||||
|
||||
/// Chooses a layout in More Settings. Another layout replaces a preset's rows and keeps the column
|
||||
@@ -611,6 +616,15 @@ fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) {
|
||||
s.layout = l;
|
||||
}
|
||||
|
||||
/// A column count entered in More Settings replaces the rows of a preset made with `file.new`'s
|
||||
/// `rows`; the same count as shown changes nothing.
|
||||
fn set_columns(s: &mut DocSettings, columns: u32) {
|
||||
if columns != shown_columns(s) {
|
||||
s.columns = columns;
|
||||
s.rows = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a
|
||||
/// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`.
|
||||
fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option<String>) {
|
||||
@@ -1316,6 +1330,33 @@ mod tests {
|
||||
assert!(app.session.documents().is_empty(), "no document was made");
|
||||
}
|
||||
|
||||
/// A new column count replaces a preset's rows; the count already shown changes nothing.
|
||||
#[test]
|
||||
fn a_new_column_count_replaces_a_presets_rows() {
|
||||
let rows = DocSettings { artboards: 9, layout: ArtboardLayout::GridByColumn, columns: 2, rows: 4, ..DocSettings::default() };
|
||||
let mut s = rows.clone();
|
||||
set_columns(&mut s, 3);
|
||||
assert_eq!(s, rows, "3 is what the rows show");
|
||||
set_columns(&mut s, 2);
|
||||
assert_eq!((s.layout, s.columns, s.rows), (ArtboardLayout::GridByColumn, 2, 0));
|
||||
assert_eq!(s.grid_columns(), 2);
|
||||
}
|
||||
|
||||
/// A stored column count of 0 shows the one row of all the artboards that `file.new` lays out, so
|
||||
/// entering 1 is stored and the same count as the row changes nothing.
|
||||
#[test]
|
||||
fn a_column_count_without_rows_is_stored() {
|
||||
let mut s = DocSettings { artboards: 4, layout: ArtboardLayout::GridByRow, columns: 0, rows: 0, ..DocSettings::default() };
|
||||
assert_eq!(shown_columns(&s), u32::try_from(s.grid_columns()).unwrap_or(0));
|
||||
set_columns(&mut s, 4);
|
||||
assert_eq!((s.columns, s.rows), (0, 0), "4 is what the row shows");
|
||||
set_columns(&mut s, 1);
|
||||
assert_eq!((s.columns, s.rows), (1, 0));
|
||||
assert_eq!(s.grid_columns(), 1);
|
||||
let column = DocSettings { artboards: 4, layout: ArtboardLayout::Column, columns: 0, rows: 0, ..DocSettings::default() };
|
||||
assert_eq!(shown_columns(&column), 1, "the Column layout is one column");
|
||||
}
|
||||
|
||||
/// The preset keeps the artboard layout, spacing and columns More Settings set (#4893); an empty
|
||||
/// name is refused.
|
||||
#[test]
|
||||
|
||||
+3
-1
@@ -861,7 +861,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
|
||||
documents, new documents, each document's selection and its page items, its text frames with their text ranges and
|
||||
character and paragraph attributes, their links to each other and the stories they form, its character and
|
||||
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries, and
|
||||
paragraph styles, the installed fonts, each document's variables, data sets and variable libraries, and its
|
||||
linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`); tracing,
|
||||
rasterizing and capturing images are still missing.
|
||||
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
|
||||
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a
|
||||
document's `fullName`, `path` and `saved`, and close it with `Document.close`.
|
||||
|
||||
+5
-3
@@ -3418,8 +3418,9 @@ through `$`:
|
||||
`null`, `embedded` is `true` and takes only `true`, and `status` is `RasterLinkState.NODATA`. `transparent` is true
|
||||
for an image with an alpha channel or a transparent palette entry. `matrix` is a record of `mValueA` to `mValueTY`
|
||||
that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning
|
||||
`matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of
|
||||
the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
|
||||
`matrix` runs `object.transform`, except that a matrix equal to the one `matrix` reads runs no command; a value
|
||||
that is not finite, a matrix with no area, one that puts a corner of the image outside the canvas and one that a
|
||||
nearly singular image cannot reach exactly throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
|
||||
a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete
|
||||
objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the
|
||||
item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()`
|
||||
@@ -11007,7 +11008,8 @@ that category), `name`, `width`/`height`
|
||||
rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
|
||||
an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are
|
||||
fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns
|
||||
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes),
|
||||
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes;
|
||||
with neither `columns` nor `rows` set, Columns shows the columns `file.new` lays out: one row of all the artboards in a grid),
|
||||
`bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's
|
||||
value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see
|
||||
[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)).
|
||||
|
||||
Reference in new issue
Block a user