mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 22:34:43 +00:00
Merge main into feat/psd-import-options-import-slices-after-7649
This commit is contained in:
Generated
+1
@@ -6824,6 +6824,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-svg",
|
||||
"data-url",
|
||||
"flate2",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
|
||||
@@ -172,6 +172,21 @@ impl IccProfile {
|
||||
Some(dst.map(|x| x.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// Device pixels `v` (RGB / CMYK / Gray, 0..1, the profile's channels a pixel, any number of
|
||||
/// pixels) → sRGB in `dst` (three values a pixel), converted with `intent` in one pass of the
|
||||
/// cached transform. `None` when `v` doesn't hold whole pixels, `dst` doesn't hold three values
|
||||
/// for each, or no transform can be built.
|
||||
pub fn to_srgb_pixels(&self, v: &[f32], dst: &mut [f32], intent: Intent) -> Option<()> {
|
||||
let n = self.channels();
|
||||
if !v.len().is_multiple_of(n) || dst.len() != v.len() / n * 3 {
|
||||
return None;
|
||||
}
|
||||
let xf = self.to_xf(intent)?;
|
||||
xf.transform(v, dst).ok()?;
|
||||
dst.iter_mut().for_each(|x| *x = x.clamp(0.0, 1.0));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// sRGB → device values.
|
||||
pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent) -> Option<Vec<f32>> {
|
||||
let xf = self.inverse_xf(intent)?;
|
||||
|
||||
@@ -48,6 +48,28 @@ fn gray_is_srgb_toned() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_pixels_convert_as_each_one_does() {
|
||||
let p = IccProfile::from_bytes(None, &icc_bytes(DISPLAY_P3).unwrap()).unwrap();
|
||||
let px = [[1.0f32, 0.0, 0.0], [0.2, 0.6, 0.9], [0.5, 0.5, 0.5], [0.0, 1.0, 0.0]];
|
||||
for intent in Intent::ALL {
|
||||
let v: Vec<f32> = px.iter().flatten().copied().collect();
|
||||
let mut dst = vec![0.0; v.len()];
|
||||
p.to_srgb_pixels(&v, &mut dst, intent).unwrap();
|
||||
for (i, rgb) in px.iter().enumerate() {
|
||||
let one = p.to_srgb(rgb, intent).unwrap();
|
||||
assert!(dst[i * 3..i * 3 + 3].iter().zip(one).all(|(a, b)| (a - b).abs() < 1e-5), "{intent:?} {rgb:?}: {dst:?} vs {one:?}");
|
||||
}
|
||||
}
|
||||
// Lengths that aren't whole pixels, or a destination of another size, are refused.
|
||||
assert!(p.to_srgb_pixels(&[0.5; 4], &mut [0.0; 3], Intent::Perceptual).is_none());
|
||||
assert!(p.to_srgb_pixels(&[0.5; 3], &mut [0.0; 6], Intent::Perceptual).is_none());
|
||||
let gray = IccProfile::from_bytes(None, &icc_bytes(GRAY).unwrap()).unwrap();
|
||||
let mut dst = [0.0; 6];
|
||||
gray.to_srgb_pixels(&[0.25, 0.75], &mut dst, Intent::RelativeColorimetric).unwrap();
|
||||
assert!(dst.iter().zip([0.25, 0.25, 0.25, 0.75, 0.75, 0.75]).all(|(a, b)| (a - b).abs() < 0.01), "{dst:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_profiles_are_reproducible() {
|
||||
assert_eq!(icc::builtin_rgb_bytes(DISPLAY_P3).unwrap(), icc::builtin_rgb_bytes(DISPLAY_P3).unwrap());
|
||||
|
||||
@@ -358,6 +358,34 @@ mod tests {
|
||||
assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 25.0).abs() < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coons_places_are_where_the_patch_bends() {
|
||||
// A rectangle's sides have 65 evenly spaced points.
|
||||
let [u, v] = Coons::rect(Rect::new(0.0, 0.0, 100.0, 50.0)).places();
|
||||
assert_eq!((u.len(), v.len()), (65, 65));
|
||||
assert!(u.iter().enumerate().all(|(i, x)| (x - i as f64 / 64.0).abs() < 1e-12), "{u:?}");
|
||||
// A top object with a curved top: between two places next to each other the patch is
|
||||
// straight, in `u` and in `v`.
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.curve_to((30.0, -20.0), (70.0, 10.0), (100.0, 0.0));
|
||||
path.line_to((100.0, 50.0));
|
||||
path.line_to((40.0, 50.0));
|
||||
path.line_to((0.0, 50.0));
|
||||
path.close_path();
|
||||
let c = Coons::from_top_object(&PathData::from_bezpath(&path), Some([0, 1, 2, 4])).unwrap();
|
||||
let [u, v] = c.places();
|
||||
assert!(u.first() == Some(&0.0) && u.last() == Some(&1.0) && u.windows(2).all(|w| w[0] < w[1]), "{u:?}");
|
||||
assert!(v.first() == Some(&0.0) && v.last() == Some(&1.0) && v.windows(2).all(|w| w[0] < w[1]), "{v:?}");
|
||||
for w in u.windows(2) {
|
||||
for y in [0.0, 0.3, 1.0] {
|
||||
let mid = c.eval((w[0] + w[1]) / 2.0, y);
|
||||
let half = c.eval(w[0], y).midpoint(c.eval(w[1], y));
|
||||
assert!(mid.distance(half) < 1e-9, "{w:?} {y}: {mid:?} {half:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_go_on_past_the_content_box() {
|
||||
// A stroke outline reaches past the box: a flat mesh and a rectangle stay the identity there.
|
||||
|
||||
@@ -338,6 +338,31 @@ impl Coons {
|
||||
let end = |side: &[Point]| side.last().copied().unwrap_or_default();
|
||||
[self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]]
|
||||
}
|
||||
|
||||
/// The places in `u` where the top or bottom side has a point, and the places in `v` where the
|
||||
/// left or right side has one, rising from 0 to 1. Between two places next to each other, each
|
||||
/// side runs straight, so [`Self::eval`] changes linearly in `u` and in `v` inside each cell of
|
||||
/// the grid they make.
|
||||
pub fn places(&self) -> [Vec<f64>; 2] {
|
||||
let sides = [&self.top, &self.right, &self.bottom, &self.left];
|
||||
let at = |which: usize| -> Vec<f64> {
|
||||
match self.knots.as_deref().and_then(|k| k.get(which)) {
|
||||
Some(knots) => knots.clone(),
|
||||
None => {
|
||||
let last = sides[which].len().saturating_sub(1).max(1);
|
||||
(0..=last).map(|i| i as f64 / last as f64).collect()
|
||||
}
|
||||
}
|
||||
};
|
||||
let merge = |a: usize, b: usize| {
|
||||
let mut v = at(a);
|
||||
v.extend(at(b));
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.dedup();
|
||||
v
|
||||
};
|
||||
[merge(0, 2), merge(1, 3)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The most points one side of [`Coons::from_top_object`] holds while it adds points between its
|
||||
|
||||
@@ -173,6 +173,10 @@ pub struct PatternDef {
|
||||
/// Size Tile to Art: the tile is the art bounds grown by the spacing.
|
||||
#[serde(default)]
|
||||
pub size_tile_to_art: bool,
|
||||
/// Move Tile with Art: in pattern editing mode, a move of all of the tile art moves the tile by
|
||||
/// the same offset.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub move_tile_with_art: bool,
|
||||
#[serde(default)]
|
||||
pub h_spacing: f64,
|
||||
#[serde(default)]
|
||||
@@ -202,6 +206,7 @@ impl PatternDef {
|
||||
art,
|
||||
overlap: Overlap::default(),
|
||||
size_tile_to_art: false,
|
||||
move_tile_with_art: false,
|
||||
h_spacing: 0.0,
|
||||
v_spacing: 0.0,
|
||||
copies: 5,
|
||||
|
||||
@@ -298,6 +298,15 @@ impl GlyphForm {
|
||||
GlyphForm::QuarterWidth => b"qwid",
|
||||
})
|
||||
}
|
||||
|
||||
/// Is this one of the monospaced width forms (`fwid`, `hwid`, `twid`, `qwid`)? A font may
|
||||
/// draw them with other glyphs (`GSUB`) or with other widths for the same glyphs (`GPOS`), and
|
||||
/// they set the characters on a fixed width, so Proportional Metrics (`palt`) is not applied
|
||||
/// with them.
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/features_fj#tag-fwid>
|
||||
pub fn is_width(self) -> bool {
|
||||
matches!(self, GlyphForm::FullWidth | GlyphForm::HalfWidth | GlyphForm::ThirdWidth | GlyphForm::QuarterWidth)
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
|
||||
@@ -785,6 +794,15 @@ impl CharStyle {
|
||||
self.position = self.position.in_range();
|
||||
self.small_caps = self.small_caps.map(small_caps_in_range);
|
||||
}
|
||||
/// Sets the East Asian glyph form ([`CharStyle::glyph_form`]). A form other than the default
|
||||
/// also takes away the character's glyph choice ([`CharStyle::glyph_alternate`]), which would
|
||||
/// otherwise keep drawing its own glyph; the default form keeps it.
|
||||
pub fn set_glyph_form(&mut self, form: GlyphForm) {
|
||||
self.glyph_form = form;
|
||||
if form != GlyphForm::Default {
|
||||
self.glyph_alternate = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
|
||||
@@ -828,6 +828,7 @@ pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
|
||||
@@ -422,6 +422,15 @@ pub(crate) fn design_reference(s: &Session, p: &Value, cmd: &str) -> Result<Opti
|
||||
Ok(ids.first().copied().filter(|id| super::graph::is_design_art(d, *id)))
|
||||
}
|
||||
|
||||
/// The [`design_reference`] of an edit aimed at `item`: none for the Appearance panel's active row, which is a row of the
|
||||
/// first selected object's stack.
|
||||
pub(crate) fn reference_of(s: &Session, p: &Value, item: ItemTarget, cmd: &str) -> Result<Option<NodeId>> {
|
||||
if matches!(item, ItemTarget::Item { explicit: false, .. }) {
|
||||
return Ok(None);
|
||||
}
|
||||
design_reference(s, p, cmd)
|
||||
}
|
||||
|
||||
/// `ids` after `of` (see [`design_reference`]), when there is one.
|
||||
pub(crate) fn with_reference(of: Option<NodeId>, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
of.into_iter().chain(ids.iter().copied()).collect()
|
||||
@@ -610,16 +619,23 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not
|
||||
/// an edit, and when `f` leaves every target as it was, the document and its undo history stay as
|
||||
/// they are.
|
||||
///
|
||||
/// With `of` (see [`reference_of`]), an explicit aligned `item` is a row of the stack of `of`, which
|
||||
/// is not among `ids`: it must be there and of the edited kind, each target edits the row equal to
|
||||
/// it, a target without one is left as it is, and no target with one is an error. Returns the
|
||||
/// targets `f` was aimed at, in the order of `ids`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn edit_items(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| {
|
||||
) -> Result<Vec<NodeId>> {
|
||||
edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| {
|
||||
let series = capture_series_changes(before, d, edited);
|
||||
// The rows `f` edited are kept by `edit_items_then`.
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false);
|
||||
@@ -636,17 +652,29 @@ pub(crate) fn edit_items_then(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
|
||||
) -> Result<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let art = of.and_then(|of| s.doc().ok()?.doc.node(of).map(|n| n.appearance.clone()));
|
||||
let per = match (item, art) {
|
||||
// Checked even when the art is the only object given, which leaves `ids` empty.
|
||||
(ItemTarget::Item { index, explicit: true, aligned: true }, Some(art)) => {
|
||||
item.resolve(&art, fill, cmd)?;
|
||||
let per = item.per_target_of(s, of, ids);
|
||||
if per.iter().all(Option::is_none) {
|
||||
return Err(bad(cmd, format!("no appearance item {index}")));
|
||||
}
|
||||
per
|
||||
}
|
||||
_ if ids.is_empty() => return Ok(Vec::new()),
|
||||
_ => item.per_target(s, ids),
|
||||
};
|
||||
let aimed: Vec<NodeId> = ids.iter().zip(&per).filter(|(_, item)| item.is_some()).map(|(id, _)| *id).collect();
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = item.per_target(s, ids);
|
||||
super::overprint::edit_counted(s, label, |d| {
|
||||
let mut edited = Vec::new();
|
||||
// The objects whose rows `f` edited: on type, no row means its characters.
|
||||
@@ -665,7 +693,13 @@ pub(crate) fn edit_items_then(
|
||||
let labels = super::graph::capture_label_rows(d, &rows);
|
||||
Ok(count_changed(d, &before, &edited) + usize::from(more || labels))
|
||||
})?;
|
||||
Ok(())
|
||||
Ok(aimed)
|
||||
}
|
||||
|
||||
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
|
||||
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
|
||||
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// How many of `ids` differ in `d` from `before`.
|
||||
@@ -674,8 +708,8 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_
|
||||
}
|
||||
|
||||
/// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the
|
||||
/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or
|
||||
/// null is an error of command `cmd`.
|
||||
/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`] and [`reference_of`]), else `default`. A `stroke` other than
|
||||
/// true, false or null is an error of command `cmd`.
|
||||
pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result<bool> {
|
||||
check_switches(p, &["stroke"], cmd)?;
|
||||
if let Some(b) = p.get("stroke").and_then(Value::as_bool) {
|
||||
@@ -683,8 +717,14 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
|
||||
}
|
||||
let ItemTarget::Item { index, .. } = item else { return Ok(default) };
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = drop_design_art(d, appearance_targets(s, p)?);
|
||||
Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
let holder = match reference_of(s, p, item, cmd)? {
|
||||
Some(of) => Some(of),
|
||||
None => {
|
||||
let ids = drop_design_art(d, appearance_targets(s, p)?);
|
||||
ids.get(item.anchor(s, &ids)).copied()
|
||||
}
|
||||
};
|
||||
Ok(holder.and_then(|id| d.node(id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, read with [`u64_req`] and [`index`].
|
||||
|
||||
@@ -32,7 +32,7 @@ use crate::DocState;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = vec![
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty)", always, export_svg),
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty). Under automation read roots it is refused while the SVG would name a linked image's file outside them (an image whose pixels the clipboard doesn't hold; a relative path is followed from the document the objects came from while it is open)", always, export_svg),
|
||||
cmd!(
|
||||
query "clipboard.importSvg",
|
||||
"Load SVG into Clipboard",
|
||||
@@ -435,14 +435,37 @@ impl Clipboard {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty).
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty, and when the SVG would name
|
||||
/// a linked image's file the caller asking now may not be shown: [`Self::clipboard_svg_refused`]).
|
||||
pub fn clipboard_svg(&self) -> Option<String> {
|
||||
if self.clipboard_svg_refused() {
|
||||
return None;
|
||||
}
|
||||
self.clipboard.svg()
|
||||
}
|
||||
|
||||
/// Would the internal clipboard's SVG name a linked image's file outside the read roots in
|
||||
/// force? It names the file of an image whose pixels the clipboard doesn't hold. A relative
|
||||
/// path is followed from the document the objects came from while it is open; otherwise it
|
||||
/// counts as outside.
|
||||
pub fn clipboard_svg_refused(&self) -> bool {
|
||||
self.check_clipboard_svg("clipboard.exportSvg").is_err()
|
||||
}
|
||||
|
||||
/// [`Self::clipboard_svg_refused`] as `cmd`'s error, which names no file or folder.
|
||||
fn check_clipboard_svg(&self, cmd: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() || !self.clipboard.has_art() {
|
||||
return Ok(());
|
||||
}
|
||||
let from = self.docs.iter().find(|d| Some(d.uid) == self.clipboard.source_doc);
|
||||
let base = from.map_or_else(super::links::LinkBase::default, super::links::LinkBase::of);
|
||||
super::fileio::check_images_in(cmd, "svg", &self.clipboard.to_document(), base, &json!({}))
|
||||
}
|
||||
}
|
||||
|
||||
fn export_svg(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "svg": s.clipboard_svg() }))
|
||||
s.check_clipboard_svg("clipboard.exportSvg")?;
|
||||
Ok(json!({ "svg": s.clipboard.svg() }))
|
||||
}
|
||||
|
||||
fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Assign Profile…",
|
||||
["Edit"],
|
||||
None,
|
||||
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
|
||||
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: no profile, Don't Color Manage This Document, so colors show through the working space; the working space's name: that profile stays assigned when the working space changes). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
|
||||
has_doc,
|
||||
assign_profile
|
||||
),
|
||||
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
use super::common::{
|
||||
dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, samples_param,
|
||||
sibling_with, size_pressure, target_paths, usize_opt,
|
||||
PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces,
|
||||
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath,
|
||||
Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session,
|
||||
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
};
|
||||
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
use vectorcraft_tools::draw2::MIN_BRUSH_SIZE;
|
||||
|
||||
/// Split a filled path into connected pieces (each outer contour with its holes).
|
||||
pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
|
||||
@@ -278,7 +281,11 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
let pressure = size_pressure(p, &samples, C)?;
|
||||
let vary = eraser_variations(p, C)?;
|
||||
if varies_beyond_size_pressure(&vary) {
|
||||
return erase_varied(s, &samples, [angle, roundness, size], vary);
|
||||
}
|
||||
let pressure = if vary[2].0 == Variation::Pressure { size_pressure(p, &samples, C)? } else { None };
|
||||
let pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
|
||||
@@ -318,6 +325,101 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
|
||||
/// `sizeMode`.
|
||||
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with
|
||||
/// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation`
|
||||
/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how
|
||||
/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null
|
||||
/// is 0; any other mode, or a variation that is negative or past its most, is refused.
|
||||
fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> {
|
||||
const KEYS: [(&str, &str, f64); 3] =
|
||||
[("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)];
|
||||
let mut out = [(Variation::Fixed, 0.0); 3];
|
||||
for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) {
|
||||
let mode = match p.get(mode_key).filter(|v| !v.is_null()) {
|
||||
None => Variation::Fixed,
|
||||
Some(Value::String(id)) => Variation::parse(id).ok_or_else(|| bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not `{id}`")))?,
|
||||
Some(other) => return Err(bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not {other}"))),
|
||||
};
|
||||
let variation = number_or(p, var_key, 0.0, cmd)?;
|
||||
if !(variation.is_finite() && variation >= 0.0) {
|
||||
return Err(bad(cmd, format!("{var_key} must be 0 or more")));
|
||||
}
|
||||
if variation > most {
|
||||
return Err(bad(cmd, format!("{var_key} must be at most {most}")));
|
||||
}
|
||||
*slot = (mode, variation);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Does any of the Eraser's Angle, Roundness and Size vary with something other than Size on
|
||||
/// Pressure? A mode whose variation is 0 does not vary.
|
||||
fn varies_beyond_size_pressure(vary: &[(Variation, f64); 3]) -> bool {
|
||||
vary.iter().enumerate().any(|(i, (mode, v))| *v > 0.0 && *mode != Variation::Fixed && !(i == 2 && *mode == Variation::Pressure))
|
||||
}
|
||||
|
||||
/// `path.eraseRegion` with its tip varying along the drag ([`eraser_variations`]): the area the
|
||||
/// tip covers is swept as a Calligraphic brush nib of the same angle, roundness, size, modes and
|
||||
/// variations, with what the pen recorded along the drag. Random draws one value for the drag
|
||||
/// and the pen modes follow the pen at each point; a drag without that recording (a mouse) takes
|
||||
/// the value itself. `tip`: the angle, roundness and size.
|
||||
fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Variation, f64); 3]) -> Result<Value> {
|
||||
let [angle, roundness, size] = tip;
|
||||
let mut pts: Vec<Point> = samples.iter().map(|s| s.pt).collect();
|
||||
// A press without a drag is a dab: a sweep needs some length.
|
||||
if let [only] = pts[..] {
|
||||
pts.push(only + Vec2::new(0.01, 0.0));
|
||||
}
|
||||
// A nib's size is kept within 1296 pt and the stroke's width scales it: a larger tip is swept
|
||||
// at a fraction of its size on a stroke as many times wider.
|
||||
let [(am, av), (rm, rv), (sm, sv)] = vary;
|
||||
let sv = if sm == Variation::Fixed { 0.0 } else { sv };
|
||||
let scale = ((size + sv) / Calligraphic::RANGES[2].1).max(1.0);
|
||||
let nib = Calligraphic {
|
||||
angle,
|
||||
roundness: roundness.clamp(1.0, 100.0),
|
||||
size: size / scale,
|
||||
variation: [av, rv, sv / scale],
|
||||
modes: Some([am, rm, sm]),
|
||||
};
|
||||
let brush = Brush { name: "Eraser".into(), kind: BrushKind::Calligraphic(nib) };
|
||||
let mut stroke = StrokeLayer::new(Paint::None, scale);
|
||||
PenRecord::of_samples(samples).write(&mut stroke);
|
||||
let spine = SubPath::polyline(&pts, false);
|
||||
let st = s.doc()?;
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&st.doc, &brush, &PathData::single(spine).to_bezpath(), &stroke);
|
||||
let areas: Vec<PathData> = pieces.iter().filter_map(|n| n.path_data().cloned()).collect();
|
||||
if areas.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let region =
|
||||
po::try_unite_all(&areas.iter().map(|a| (a, FillRule::NonZero)).collect::<Vec<_>>()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let bp = region.to_bezpath();
|
||||
// The narrowest the tip gets across: an open path is sampled at least every half of it.
|
||||
let low = |i: usize| match vary[i] {
|
||||
(Variation::Fixed, _) => tip[i],
|
||||
(_, v) => tip[i] - v,
|
||||
};
|
||||
let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0;
|
||||
let reach = (size + sv) / 2.0;
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
|
||||
if pd.is_closed() {
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference))));
|
||||
} else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| fill_contains(&bp, FillRule::NonZero, q)) {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>) -> Result<Value> {
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
|
||||
@@ -14,7 +14,8 @@ use vectorcraft_geom::{FillRule, PathData};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::appearance::{
|
||||
ItemTarget, aligned, appearance_targets, design_reference, edit_targets, index_param, item_indices, item_target, item_target_at, with_reference,
|
||||
ItemTarget, aligned, appearance_targets, design_reference, edit_targets, index_param, item_indices, item_target, item_target_at, reference_of,
|
||||
with_reference,
|
||||
};
|
||||
use super::expand::has_seeded;
|
||||
use super::rasterfx;
|
||||
@@ -336,15 +337,6 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us
|
||||
/// have.
|
||||
const APPENDED: usize = usize::MAX;
|
||||
|
||||
/// The [`design_reference`] of an effect edit aimed at `item`: none for the Appearance panel's active row, which is a
|
||||
/// row of the first selected object's stack.
|
||||
fn reference_of(s: &Session, p: &Value, item: ItemTarget, cmd: &str) -> Result<Option<NodeId>> {
|
||||
if matches!(item, ItemTarget::Item { explicit: false, .. }) {
|
||||
return Ok(None);
|
||||
}
|
||||
design_reference(s, p, cmd)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edit_effects(
|
||||
s: &mut Session,
|
||||
|
||||
@@ -92,6 +92,7 @@ pub(crate) use mesh3d::{mesh_file_names, mesh_files};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
pub(crate) use pdfimport::opened_page_document;
|
||||
pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use psdlayers::import_active as psd_layers;
|
||||
pub use psdlayers::{PsdInfo, info as psd_info};
|
||||
@@ -128,9 +129,10 @@ mod commands;
|
||||
mod export_names;
|
||||
mod formats;
|
||||
|
||||
pub(crate) use access::check_images_in;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_readonly;
|
||||
|
||||
@@ -139,6 +139,49 @@ pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
|
||||
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
|
||||
/// those too unless read roots are in force and the file would name a linked image's file outside
|
||||
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
|
||||
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
|
||||
/// and each data set's image. The error names no file or folder.
|
||||
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
|
||||
check_images_in(cmd, format, d, crate::cmd::links::LinkBase::of(st), p)
|
||||
}
|
||||
|
||||
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
|
||||
/// objects on the clipboard, looked for from the document they came from).
|
||||
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
|
||||
// layers kept: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden) = match super::svg::options_map(p) {
|
||||
Ok(m) => {
|
||||
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
|
||||
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
|
||||
}
|
||||
Err(_) => (true, true, true),
|
||||
};
|
||||
// The opacity-mask and symbol editing layers are never written.
|
||||
let d = &*d.without_edit_modes();
|
||||
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
|
||||
if preserve && crate::cmd::links::names_hidden_file(d, base)
|
||||
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
|
||||
{
|
||||
return Err(bad(cmd, IMAGE_OUTSIDE));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SymbolOverride};
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SYMBOL_SIZES, SymbolOverride};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::AntiAlias;
|
||||
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
|
||||
@@ -454,7 +454,12 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
|
||||
/// make the same appearance changes to its art are measured on a copy of the symbol of their own,
|
||||
/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of
|
||||
/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects
|
||||
/// they change.
|
||||
/// they change. Each copy keeps its symbol's 9-slice guides and natural size. An instance whose art
|
||||
/// goes through 9-slice guides at any depth is measured as its art placed through them
|
||||
/// ([`placed_instances`]), with the objects `left_out` picks hidden after placing: the guides cut
|
||||
/// the box of the whole art. Where an instance stays one, the art of a symbol with 9-slice guides,
|
||||
/// and of the symbols whose instances are in that art at any depth ([`sliced_art`]), is measured
|
||||
/// whole.
|
||||
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
|
||||
// The symbols instances show (the first of each name).
|
||||
let mut names = HashSet::new();
|
||||
@@ -492,12 +497,15 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
let Some(s) = d.symbols.get(*i).cloned() else { continue };
|
||||
for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() {
|
||||
copies.push((d.symbols.len(), c.as_slice()));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: format!("{}\u{0}{k}", s.name), ..s.clone() });
|
||||
let name = format!("{}\u{0}{k}", s.name);
|
||||
copy_placement(&mut d, &s.name, &name);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name, ..s.clone() });
|
||||
}
|
||||
}
|
||||
d
|
||||
});
|
||||
let src = remapped_doc.as_ref().unwrap_or(doc);
|
||||
let whole = sliced_art(src);
|
||||
// The symbols to measure with the changes their instances make (`None` for a static symbol),
|
||||
// without the dynamic symbols measured whole.
|
||||
let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown
|
||||
@@ -517,11 +525,25 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
}
|
||||
let left_out =
|
||||
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
|
||||
// The instances whose art goes through 9-slice guides, at any depth, are measured as their art
|
||||
// placed by those guides without the objects `left_out` picks, and without a clip group that
|
||||
// holds only such objects.
|
||||
let layers = hidden_nodes(&src.layers, left_out);
|
||||
let placing = holding(src, &whole);
|
||||
let layers = if placing.is_empty() {
|
||||
layers
|
||||
} else {
|
||||
let picked = &|n: &Node| {
|
||||
left_out(n) || matches!(n.kind, NodeKind::Group { clip: true, .. }) && all_left_out(n, left_out, &empty, None, &mut Vec::new())
|
||||
};
|
||||
let mut budget = 0;
|
||||
let from = layers.as_deref().unwrap_or(&src.layers);
|
||||
Some(from.iter().map(|l| placed_instances(src, l, &placing, picked, &mut budget, 0).unwrap_or_else(|| l.clone())).collect())
|
||||
};
|
||||
let symbols: Vec<(usize, Arc<Node>)> = entries
|
||||
.iter()
|
||||
.filter_map(|(i, c)| {
|
||||
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()))?;
|
||||
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && !whole.contains(s.name.as_str()))?;
|
||||
without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art))
|
||||
})
|
||||
.collect();
|
||||
@@ -540,6 +562,135 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
vectorcraft_render::encode::art_bounds(&d)
|
||||
}
|
||||
|
||||
/// Give symbol `to` of `d` the 9-slice guides and the natural size that symbol `from` has.
|
||||
fn copy_placement(d: &mut Document, from: &str, to: &str) {
|
||||
if let Some(guides) = d.symbol_nine_slice(from) {
|
||||
d.set_symbol_nine_slice(to, Some(guides));
|
||||
}
|
||||
if let Some(size) = d.unknown.get(SYMBOL_SIZES).and_then(|m| m.get(from)).cloned()
|
||||
&& let Some(sizes) = d.unknown.get_mut(SYMBOL_SIZES).and_then(Value::as_object_mut)
|
||||
{
|
||||
sizes.insert(to.to_string(), size);
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the symbols of `doc` with 9-slice guides, and of the symbols whose instances are in
|
||||
/// the art of those at any depth.
|
||||
fn sliced_art(doc: &Document) -> HashSet<&str> {
|
||||
let mut arts: HashMap<&str, &Arc<Node>> = HashMap::new();
|
||||
for s in &doc.symbols {
|
||||
arts.entry(s.name.as_str()).or_insert(&s.art);
|
||||
}
|
||||
let mut todo: Vec<&str> = arts.keys().copied().filter(|name| doc.symbol_nine_slice(name).is_some()).collect();
|
||||
let mut found = HashSet::new();
|
||||
while let Some(name) = todo.pop() {
|
||||
if !found.insert(name) {
|
||||
continue;
|
||||
}
|
||||
if let Some(&art) = arts.get(name) {
|
||||
art.walk(&mut |n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
todo.push(symbol.as_str());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The names of the symbols of `doc` in `sliced`, and of the symbols whose art holds an instance of
|
||||
/// one of those at any depth.
|
||||
fn holding<'a>(doc: &'a Document, sliced: &HashSet<&'a str>) -> HashSet<&'a str> {
|
||||
let mut held_by: HashMap<&str, Vec<&str>> = HashMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
for s in doc.symbols.iter().filter(|s| seen.insert(s.name.as_str())) {
|
||||
s.art.walk(&mut |n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
held_by.entry(symbol.as_str()).or_default().push(s.name.as_str());
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut found = HashSet::new();
|
||||
let mut todo: Vec<&str> = sliced.iter().copied().collect();
|
||||
while let Some(name) = todo.pop() {
|
||||
if found.insert(name) {
|
||||
todo.extend(held_by.get(name).into_iter().flatten().copied());
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The most instances deep [`placed_instances`] places symbol art.
|
||||
const MAX_PLACED_DEPTH: usize = 32;
|
||||
|
||||
/// `n` with each instance of the `placing` symbols in it, and in its layers and groups at any depth,
|
||||
/// made a group with the instance's appearance that holds the instance's art (with its changes and
|
||||
/// stain) as `doc` places it, through the symbol's 9-slice guides when it has them, without the
|
||||
/// objects `picked` picks ([`without_nodes`]; hidden when it picks the whole art); `None` when `n`
|
||||
/// holds no such instance, or is hidden. An instance on a perspective grid, one
|
||||
/// [`MAX_PLACED_DEPTH`] instances deep, one in another kind of object (a blend, for example), and
|
||||
/// one whose art would take the objects placed in all (`budget`) past
|
||||
/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] stay instances.
|
||||
/// Their symbols' art is measured whole, as taking objects out of it would change the box the
|
||||
/// guides cut, and the page can come out larger than the plot.
|
||||
fn placed_instances(
|
||||
doc: &Document,
|
||||
n: &Arc<Node>,
|
||||
placing: &HashSet<&str>,
|
||||
picked: &dyn Fn(&Node) -> bool,
|
||||
budget: &mut u64,
|
||||
depth: usize,
|
||||
) -> Option<Arc<Node>> {
|
||||
// Hidden art is not plotted, and placing it would take from the budget of the art that is.
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
if !placing.contains(symbol.as_str()) || depth >= MAX_PLACED_DEPTH || n.projection().is_some() {
|
||||
return None;
|
||||
}
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
|
||||
let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc));
|
||||
if budget.saturating_add(most) > vectorcraft_doc::MAX_SYMBOL_NODES {
|
||||
return None;
|
||||
}
|
||||
let art = Arc::new(doc.place_symbol_art(symbol, &art, *xf)?);
|
||||
*budget = budget.saturating_add(art.count_with_masks() as u64);
|
||||
let art = placed_instances(doc, &art, placing, picked, budget, depth + 1).unwrap_or(art);
|
||||
let art = if picked(&art) {
|
||||
let mut hidden = (*art).clone();
|
||||
hidden.visible = false;
|
||||
Arc::new(hidden)
|
||||
} else {
|
||||
without_nodes(&art, picked, None, &mut Vec::new()).unwrap_or(art)
|
||||
};
|
||||
let mut g = (**n).clone();
|
||||
g.kind = NodeKind::Group { children: vec![art], clip: false };
|
||||
Some(Arc::new(g))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
let mut out: Option<Vec<Arc<Node>>> = None;
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if let Some(new) = placed_instances(doc, c, placing, picked, budget, depth)
|
||||
&& let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i)
|
||||
{
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
out.map(|c| {
|
||||
let mut m = (**n).clone();
|
||||
if let Some(children) = m.children_mut() {
|
||||
*children = c;
|
||||
}
|
||||
Arc::new(m)
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The appearance changes instance `n` makes to its symbol's art, without those that change nothing.
|
||||
fn own_changes(n: &Node) -> Vec<&SymbolOverride> {
|
||||
n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect()
|
||||
@@ -600,9 +751,10 @@ fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str
|
||||
|
||||
/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of
|
||||
/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the
|
||||
/// instances show (`walked`, the symbols already looked in). The instances that `left_out` picks or
|
||||
/// that are in an object it picks are left out, and with `hidden` (in a layer) the hidden ones and
|
||||
/// those in a hidden object. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
|
||||
/// instances show (`walked`, the symbols already looked in). With `hidden` (in a layer), the
|
||||
/// instances that are hidden or that `left_out` picks, and those in such an object, are left out.
|
||||
/// In symbol art every instance counts, since an instance of the symbol can change the objects
|
||||
/// that hold it. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
|
||||
fn drawn_changes<'a>(
|
||||
doc: &'a Document,
|
||||
n: &'a Node,
|
||||
@@ -611,7 +763,7 @@ fn drawn_changes<'a>(
|
||||
walked: &mut HashSet<&'a str>,
|
||||
sets: &mut HashMap<&'a str, Option<Vec<Vec<&'a SymbolOverride>>>>,
|
||||
) {
|
||||
if hidden && !n.visible || left_out(n) {
|
||||
if hidden && (!n.visible || left_out(n)) {
|
||||
return;
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
|
||||
@@ -12,8 +12,8 @@ use crate::DocState;
|
||||
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, Format, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded,
|
||||
write_or_return,
|
||||
ARTBOARD_PARAMS, Format, check_images_in, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output,
|
||||
writable, write_encoded, write_or_return,
|
||||
};
|
||||
|
||||
/// The keys the export commands take for every format, beside the path, the format and the
|
||||
@@ -287,6 +287,8 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = export_doc(st, f, p)?;
|
||||
// The objects written (all, or with selectedOnly the selected ones) are checked.
|
||||
check_images_in(cmd, f.id, &doc, crate::cmd::links::LinkBase::of(st), p)?;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
|
||||
}
|
||||
@@ -372,6 +374,8 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The selected objects' links are looked for from the document they are in.
|
||||
check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?;
|
||||
// The encoder's warnings (options accepted but not applied, features approximated or left
|
||||
// out), as document.export reports them.
|
||||
let (bytes, mut warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -213,7 +213,7 @@ pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Docu
|
||||
}
|
||||
|
||||
/// [`page_document`] of `opened`, the PDF `bytes` already read.
|
||||
fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
vectorcraft_pdf::import_opened(bytes, opened, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err)
|
||||
}
|
||||
|
||||
@@ -225,8 +225,11 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
|
||||
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
|
||||
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
|
||||
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
|
||||
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`), in a row from the left
|
||||
/// with the gap a PDF's artboards open with, and a layer named after the page. The document opens
|
||||
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box;
|
||||
/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the
|
||||
/// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box,
|
||||
/// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the
|
||||
/// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens
|
||||
/// in CMYK when most of the pages read in CMYK, unless `o.color_mode` names a mode. Refused without a
|
||||
/// path, for any other file, with a password (a linked page is read again without one), with
|
||||
/// `textAs: outlines` (a linked page shows the file's own type) and for a file over
|
||||
@@ -247,12 +250,16 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
if bytes.len() > document::MAX_FILE {
|
||||
return Err(bad(C, format!("linkPages: `{file}` is over {} MB", document::MAX_FILE >> 20)));
|
||||
}
|
||||
let count = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?.page_count();
|
||||
// The file is read once: every page is read from it.
|
||||
let opened = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?;
|
||||
let count = opened.page_count();
|
||||
let picked = match &o.pages {
|
||||
None => (0..count).collect(),
|
||||
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
|
||||
};
|
||||
let bounding = o.crop == CropTo::Bounding;
|
||||
// A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]).
|
||||
let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
|
||||
doc.artboards.clear();
|
||||
@@ -261,14 +268,55 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
let gap = ImportOptions::default().artboard_gap;
|
||||
// Every page's object keeps the same one copy of the file.
|
||||
let shared = Arc::new(bytes.to_vec());
|
||||
let (mut x, mut warnings, mut cmyk_pages) = (0.0, Vec::<String>::new(), 0);
|
||||
for (i, &index) in picked.iter().enumerate() {
|
||||
// The file is hashed once for all its pages.
|
||||
let hash = link.hash.clone().unwrap_or_else(|| vectorcraft_doc::links::hash_bytes(bytes));
|
||||
let (mut warnings, mut cmyk_pages) = (Vec::<String>::new(), 0);
|
||||
// Each page as read, with its bleed (top, bottom, left, right). The pages are laid out once
|
||||
// the document's bleed is known.
|
||||
let mut read_pages = Vec::with_capacity(picked.len());
|
||||
for &index in &picked {
|
||||
let page = index as u32 + 1;
|
||||
let s = document::shared_source(name, &shared, Some(path), page, bounding, document::page_box(o.crop), C)?;
|
||||
let file_once = document::SharedFile { bytes: &shared, hash: &hash, opened: &opened };
|
||||
// On its trim box, a page shows its bleed box, the artboard on the trim box inside it, so
|
||||
// the art in the bleed shows and prints as bleed.
|
||||
let bleed = if crop == CropTo::Trim { opened.page_bleed(index) } else { None };
|
||||
let page_box = if bleed.is_some() { vectorcraft_doc::PageBox::Bleed } else { document::page_box(crop) };
|
||||
let read = |bounding| document::shared_source(name, file_once, Some(path), page, bounding, page_box, C);
|
||||
// A blank page has no art's bounds: it keeps its crop box, as opening it as art does.
|
||||
let (mut s, bounding) = match read(bounding) {
|
||||
Err(e) if bounding && e.to_string().contains("has no art to place") => (read(false)?, false),
|
||||
s => (s?, bounding),
|
||||
};
|
||||
// A page that is only a placeholder (a `.ai` saved without PDF compatibility) shows the
|
||||
// file's editing data, not a page of the file.
|
||||
if s.editing_data {
|
||||
return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file")));
|
||||
}
|
||||
cmyk_pages += usize::from(s.color_mode == ColorMode::Cmyk);
|
||||
// The document's bleed is the widest of the pages' on each side.
|
||||
let sides = bleed.unwrap_or_default();
|
||||
for (side, b) in doc.setup.bleed.iter_mut().zip(sides) {
|
||||
*side = side.max(b.min(vectorcraft_doc::setup::MAX_BLEED));
|
||||
}
|
||||
for w in std::mem::take(&mut s.warnings) {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
}
|
||||
read_pages.push((page, s, bounding, sides));
|
||||
}
|
||||
// Each artboard is the gap from the one before plus the bleed on both sides of it: the
|
||||
// document's bleed, which export adds round every artboard, or a page's own bleed box where it
|
||||
// reaches farther. Neither page then shows or exports the other's art.
|
||||
let [_, _, doc_left, doc_right] = doc.setup.bleed;
|
||||
let mut x = 0.0;
|
||||
for (i, (page, s, bounding, [top, bottom, left, right])) in read_pages.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
x += doc_left.max(left);
|
||||
}
|
||||
let mut node = document::node(&mut doc, &s, LinkInfo { page: Some(page), ..link.clone() }, bounding);
|
||||
if let NodeKind::PlacedDocument(p) = &mut node.kind {
|
||||
p.xf = Affine::translate((x, 0.0));
|
||||
p.xf = Affine::translate((x - left, -top));
|
||||
}
|
||||
node.name = Some(file.clone());
|
||||
let mut layer = Node::layer(doc.alloc_id(), &format!("Page {page}"), LayerColor::Preset((i % 27) as u8));
|
||||
@@ -276,14 +324,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
doc.layers.push(Arc::new(layer));
|
||||
let rect = Rect::new(x, 0.0, x + s.frame.width(), s.frame.height());
|
||||
let rect = Rect::new(x, 0.0, x + s.frame.width() - left - right, s.frame.height() - top - bottom);
|
||||
doc.artboards.push(Artboard { id: i as u32 + 1, name: format!("Artboard {}", i + 1), rect, ..board.clone() });
|
||||
x = rect.x1 + gap;
|
||||
for w in s.warnings {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
}
|
||||
x = rect.x1 + doc_right.max(right) + gap;
|
||||
}
|
||||
// Pages painted mostly in CMYK read as CMYK documents, as opening them as art does: the
|
||||
// document opens in CMYK (with the CMYK default swatches) when most of its pages do.
|
||||
|
||||
@@ -891,6 +891,13 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let cmd = plan.mode.command();
|
||||
super::check_linked_scripts(cmd, plan.format.id, st)?;
|
||||
let mut own = doc_to_save(st, plan.format);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
// A save keeps hidden layers (not displayed) unless told otherwise; exports leave them out.
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let params = Value::Object(params);
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
// The file the document is saved as (else its own) titles it if New's name is all it has.
|
||||
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
|
||||
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
|
||||
@@ -905,12 +912,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let base = crate::cmd::links::LinkBase::of(st);
|
||||
let relative = plan.path.as_deref().filter(|_| is_native(plan.format)).and_then(|p| crate::cmd::links::with_relative_paths(&own, base, p));
|
||||
let doc = relative.map_or(own, Arc::new);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
// A save keeps hidden layers (not displayed) unless told otherwise; exports leave them out.
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let mut params = Value::Object(params);
|
||||
let mut params = params;
|
||||
if matches!(plan.format.id, "vectorcraft" | "template") {
|
||||
// Not remembered with the options: the preference decides each time it isn't given.
|
||||
params = with_compression_pref(&s.prefs, ¶ms);
|
||||
@@ -1307,7 +1309,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -1125,6 +1125,13 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
};
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// The file each item writes for each SVG row, before the folder is made or any row is written.
|
||||
let base = crate::cmd::links::LinkBase::of(s.doc()?);
|
||||
for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) {
|
||||
for item in &items {
|
||||
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
|
||||
}
|
||||
}
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! params' top level or from an `svg` object (which wins), and the files an SVG export writes
|
||||
//! (one per artboard, plus the images it links to).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -155,6 +157,18 @@ fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec<Option<usize>>,
|
||||
Ok((opts, named.unwrap_or_else(|| vec![0]).into_iter().map(Some).collect(), chosen))
|
||||
}
|
||||
|
||||
/// The art the SVG files of `doc` with options `p` draw, as [`encode`] picks it: with chosen
|
||||
/// artboards, the art over each one; else all of `doc`. `None` when the options don't read.
|
||||
pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Document>>> {
|
||||
let (_, boards, chosen) = plan(doc, p).ok()?;
|
||||
if !chosen {
|
||||
return Some(vec![Cow::Borrowed(doc)]);
|
||||
}
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let rects: Vec<_> = boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect();
|
||||
Some(rects.into_iter().map(|r| Cow::Owned(super::export::art_over(doc, r, &mut renderer))).collect())
|
||||
}
|
||||
|
||||
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
|
||||
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
|
||||
/// Editing Capabilities).
|
||||
|
||||
@@ -1160,6 +1160,91 @@ fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() {
|
||||
assert!(e.contains("placeholder"), "{e}");
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` refuses a `.ai` saved without PDF compatibility, whose page is
|
||||
/// only a placeholder, and opens a PDF-compatible one.
|
||||
#[test]
|
||||
fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpages-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let file = |name: &str, page: &str| {
|
||||
let path = d.join(name);
|
||||
std::fs::write(&path, ai::ai(&compressed(&ai::sample_data()), page)).unwrap();
|
||||
path.to_string_lossy().to_string()
|
||||
};
|
||||
let (plain, compatible) = (file("plain.ai", PLACEHOLDER), file("compatible.ai", "0 g 10 10 40 40 re f"));
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("document.open", &json!({"path": plain, "linkPages": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("isn't a PDF or a PDF-compatible .ai file"), "{e}");
|
||||
assert!(s.documents().is_empty(), "nothing opened");
|
||||
s.execute("document.open", &json!({"path": compatible, "linkPages": true})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.has_placed());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
|
||||
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
|
||||
#[test]
|
||||
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let path = d.join("trimmed.ai");
|
||||
let boxes = "/TrimBox [10 10 190 90] /BleedBox [4 2 196 98]";
|
||||
std::fs::write(&path, ai::ai_with(&compressed(&ai::sample_data()), "0 g 10 10 40 40 re f", boxes)).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let board = doc.artboards[0].rect;
|
||||
assert_eq!((board.width(), board.height()), (180.0, 80.0), "the trim box");
|
||||
assert_eq!(doc.setup.bleed, [8.0, 8.0, 6.0, 6.0], "top, bottom, left, right");
|
||||
// The page shows its bleed box, so the art in the bleed is kept.
|
||||
let placed = doc.layers[0].children().unwrap()[0].clone();
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
|
||||
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_pages_on_their_trim_boxes_keep_the_bleed_between_the_artboards() {
|
||||
// Two 100 pt trim boxes: the first with 60 pt of bleed on each side, the second with 80 pt on
|
||||
// its left, more than the largest document bleed (72 pt).
|
||||
let entries = format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(2));
|
||||
let first = PdfPage {
|
||||
bleed: Some([0.0, 0.0, 220.0, 220.0]),
|
||||
trim: Some([60.0, 60.0, 160.0, 160.0]),
|
||||
entries,
|
||||
..PdfPage::new(220.0, 220.0, "0 g 0 0 220 220 re f")
|
||||
};
|
||||
let second = PdfPage {
|
||||
bleed: Some([0.0, 0.0, 240.0, 220.0]),
|
||||
trim: Some([80.0, 60.0, 180.0, 160.0]),
|
||||
..PdfPage::new(240.0, 220.0, "0 g 0 0 240 220 re f")
|
||||
};
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagesgap-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let path = d.join("pages.ai");
|
||||
std::fs::write(&path, pdf_with(&[first, second], &["<< /Length 4 >>\nstream\ndata\nendstream"], None)).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.setup.bleed, [60.0, 60.0, 72.0, 60.0], "top, bottom, left, right");
|
||||
// The first page's bleed ends at 160; the second's starts 36 pt later, 80 pt left of its trim box.
|
||||
let boards: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.x0, a.rect.x1)).collect();
|
||||
assert_eq!(boards, [(0.0, 100.0), (276.0, 376.0)]);
|
||||
let shown: Vec<f64> = doc
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| match &l.children().unwrap()[0].kind {
|
||||
NodeKind::PlacedDocument(p) => p.xf.translation().x,
|
||||
k => panic!("{k:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(shown, [-60.0, 196.0], "each page's bleed box round its artboard");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A page of text alone, as text-only art has in its PDF part: no path is painted.
|
||||
const TEXT_ART: &str = "BT /F1 36 Tf 10 40 Td (Text only) Tj ET";
|
||||
|
||||
|
||||
@@ -338,6 +338,152 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() {
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
}
|
||||
|
||||
/// A rectangle filled black, or one that paints nothing.
|
||||
fn plot_rect(d: &mut vectorcraft_doc::Document, r: vectorcraft_geom::Rect, painted: bool) -> std::sync::Arc<vectorcraft_doc::Node> {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let fill = if painted { Paint::solid(Color::BLACK) } else { Paint::None };
|
||||
let appearance = vectorcraft_doc::Appearance::basic(fill, Paint::None, 0.0);
|
||||
std::sync::Arc::new(vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), appearance))
|
||||
}
|
||||
|
||||
/// An instance of symbol `symbol` placed by `xf`.
|
||||
fn plot_instance(d: &mut vectorcraft_doc::Document, symbol: &str, xf: vectorcraft_geom::Affine) -> vectorcraft_doc::Node {
|
||||
vectorcraft_doc::Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf })
|
||||
}
|
||||
|
||||
/// Symbol `name` holding `art` in a group.
|
||||
fn plot_symbol(d: &mut vectorcraft_doc::Document, name: &str, art: Vec<std::sync::Arc<vectorcraft_doc::Node>>, dynamic: bool) {
|
||||
let group = vectorcraft_doc::Node::group(d.alloc_id(), art);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic, name: name.into(), art: std::sync::Arc::new(group) });
|
||||
}
|
||||
|
||||
/// Puts `n` on the first layer of `d`.
|
||||
fn plot_on_layer(d: &mut vectorcraft_doc::Document, n: vectorcraft_doc::Node) {
|
||||
std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(n));
|
||||
}
|
||||
|
||||
/// The art of a symbol with 9-slice guides, static or dynamic, is placed whole and measured
|
||||
/// without what the plot leaves out: a frame that paints nothing sets where the guides place the
|
||||
/// painted art inside it, and is not measured itself.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_places_9_slice_symbol_art_by_all_of_it() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
// Static and dynamic, and with the instance's fill staining the art.
|
||||
for (dynamic, stained) in [(false, false), (true, false), (false, true)] {
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let square = plot_rect(&mut d, Rect::new(40.0, 40.0, 60.0, 60.0), true);
|
||||
plot_symbol(&mut d, "Panel", vec![frame, square], dynamic);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let mut wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
if stained {
|
||||
let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
|
||||
wide.appearance = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0).into();
|
||||
}
|
||||
plot_on_layer(&mut d, wide);
|
||||
// Scaled 2 times across, the middle column maps x to 3x - 50: the square draws from x 70
|
||||
// to 130.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
let exact = [(b.x0, 70.0), (b.y0, 40.0), (b.x1, 130.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact, "dynamic: {dynamic}, stained: {stained}, {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// In art placed through 9-slice guides, a group with a fill of its own keeps the path it paints,
|
||||
/// which paints nothing by itself.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_keeps_what_a_group_paints_in_9_slice_symbol_art() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let bare = plot_rect(&mut d, Rect::new(40.0, 40.0, 60.0, 60.0), false);
|
||||
let mut group = vectorcraft_doc::Node::group(d.alloc_id(), vec![bare]);
|
||||
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
|
||||
group.appearance = vectorcraft_doc::Appearance::basic(black, vectorcraft_color::Paint::None, 0.0).into();
|
||||
plot_symbol(&mut d, "Panel", vec![frame, std::sync::Arc::new(group)], false);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
plot_on_layer(&mut d, wide);
|
||||
let b = super::export_art_bounds(&d, "hpgl").expect("the group's path is plotted");
|
||||
let exact = [(b.x0, 70.0), (b.y0, 40.0), (b.x1, 130.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact, "{b:?}");
|
||||
}
|
||||
|
||||
/// A symbol without guides in the art of a symbol with 9-slice guides is measured without what the
|
||||
/// plot leaves out, in the placed art and in an instance of its own.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_leaves_out_unplotted_art_of_symbols_in_9_slice_art() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let far = plot_rect(&mut d, Rect::new(45.0, -500.0, 55.0, -480.0), false);
|
||||
let dot = plot_rect(&mut d, Rect::new(45.0, 45.0, 55.0, 55.0), true);
|
||||
plot_symbol(&mut d, "Dot", vec![far, dot], false);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let inner = std::sync::Arc::new(plot_instance(&mut d, "Dot", Affine::IDENTITY));
|
||||
plot_symbol(&mut d, "Panel", vec![frame, inner], false);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
plot_on_layer(&mut d, wide);
|
||||
let near = |b: Rect, e: [f64; 4]| [b.x0, b.y0, b.x1, b.y1].iter().zip(e).all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
// The dot's box is in the middle column, which maps x to 3x - 50.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(near(b, [85.0, 45.0, 115.0, 55.0]), "{b:?}");
|
||||
let own = plot_instance(&mut d, "Dot", Affine::translate((200.0, 0.0)));
|
||||
plot_on_layer(&mut d, own);
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(near(b, [85.0, 45.0, 255.0, 55.0]), "{b:?}");
|
||||
}
|
||||
|
||||
/// The copy of a dynamic symbol that an instance's changes are measured on keeps the symbol's
|
||||
/// 9-slice guides.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_measures_changed_9_slice_instances_by_their_guides() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let bar = plot_rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), true);
|
||||
plot_symbol(&mut d, "Bar", vec![bar], false);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let inner = std::sync::Arc::new(plot_instance(&mut d, "Bar", Affine::IDENTITY));
|
||||
plot_symbol(&mut d, "Panel", vec![frame, inner], true);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let mut wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
wide.extras_mut().symbol_overrides =
|
||||
vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(vectorcraft_color::Paint::None), ..Default::default() }];
|
||||
plot_on_layer(&mut d, wide);
|
||||
// The bar crosses the left guide and is placed by the middle column's map, x to 3x - 50: it
|
||||
// draws from x -20 to 160.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
let exact = |b: Rect| [(b.x0, -20.0), (b.y0, 40.0), (b.x1, 160.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact(b), "{b:?}");
|
||||
// The same instance in the art of a symbol without guides.
|
||||
let wide = std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().unwrap().pop().unwrap();
|
||||
plot_symbol(&mut d, "Holder", vec![wide], false);
|
||||
let holder = plot_instance(&mut d, "Holder", Affine::IDENTITY);
|
||||
plot_on_layer(&mut d, holder);
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(exact(b), "{b:?}");
|
||||
}
|
||||
|
||||
/// An instance in a dynamic symbol's art, in a group at 0% opacity that an instance of the symbol
|
||||
/// brings back to full opacity, is measured with the paint it gives its own symbol's art.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_measures_instances_that_an_instance_brings_back() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let bare = plot_rect(&mut d, Rect::new(300.0, 300.0, 320.0, 320.0), false);
|
||||
plot_symbol(&mut d, "Inner", vec![bare], true);
|
||||
let mut inner = plot_instance(&mut d, "Inner", Affine::IDENTITY);
|
||||
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
|
||||
inner.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(black), ..Default::default() }];
|
||||
plot_symbol(&mut d, "Outer", vec![std::sync::Arc::new(inner)], true);
|
||||
std::sync::Arc::make_mut(&mut d.symbols[1].art).opacity = 0.0;
|
||||
let mut outer = plot_instance(&mut d, "Outer", Affine::IDENTITY);
|
||||
outer.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![], opacity: Some(1.0), ..Default::default() }];
|
||||
plot_on_layer(&mut d, outer);
|
||||
let b = super::export_art_bounds(&d, "hpgl").expect("the painted rectangle is plotted");
|
||||
assert!((b.x0 - 300.0).abs() < 1e-6 && (b.x1 - 320.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left
|
||||
/// out when it would take more cells than the effect makes.
|
||||
#[test]
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
has_doc,
|
||||
delete_point
|
||||
),
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
has_doc,
|
||||
add_line
|
||||
),
|
||||
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Split Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
has_doc,
|
||||
split_line
|
||||
),
|
||||
@@ -201,7 +201,9 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
first.get_or_insert(r);
|
||||
Ok(())
|
||||
};
|
||||
edit_items(s, &ids, item, cmd, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &ids);
|
||||
edit_items(s, &ids, item, of, cmd, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -222,7 +224,9 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
})?;
|
||||
let r = first.ok_or_else(|| bad(cmd, NOT_FREEFORM))?;
|
||||
// The edited gradient is the last one used (`paint.lastGradient`).
|
||||
let shown = s.doc()?.doc.node(ids[0]).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten()));
|
||||
let shown = shown_at.and_then(|(id, item)| {
|
||||
s.doc().ok()?.doc.node(id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten()))
|
||||
});
|
||||
if let Some(p) = shown {
|
||||
s.remember_paint(&p);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient Vector",
|
||||
[],
|
||||
None,
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
has_doc,
|
||||
set_gradient_geom
|
||||
),
|
||||
@@ -580,7 +580,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &ids);
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -616,9 +619,12 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.gradient_mode = m;
|
||||
}
|
||||
// The last gradient is the one the first object now shows (the defaults' without objects).
|
||||
let shown = match ids.first() {
|
||||
Some(id) => s.doc()?.doc.node(*id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten())),
|
||||
None => Some(new_default.clone()),
|
||||
let shown = match shown_at {
|
||||
Some((id, item)) => {
|
||||
s.doc()?.doc.node(id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten()))
|
||||
}
|
||||
None if ids.is_empty() => Some(new_default.clone()),
|
||||
None => None,
|
||||
};
|
||||
if let Some(shown) = shown {
|
||||
s.remember_paint(&shown);
|
||||
@@ -628,7 +634,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
s.paint.fill = new_default;
|
||||
}
|
||||
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
Ok(json!({"ids": edited.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// A painted stroke on a type run without a weight gets 1 pt.
|
||||
@@ -766,7 +772,9 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
let model = super::paint::new_color_model(s, &Value::Null);
|
||||
edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
let targets = edit_items(s, &targets, item, of, C, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
|
||||
@@ -869,6 +869,188 @@ fn aligned_rows_of_a_graph_designs_art_and_a_different_stack_are_not_moved() {
|
||||
assert_eq!(paints, [art_was.items[1].paint().clone(), art_was.items[0].paint().clone(), art_was.items[1].paint().clone()]);
|
||||
}
|
||||
|
||||
/// An `item` given with `aligned: true` and the art of a graph design in a series first is a row of the art's stack in the
|
||||
/// paint and stroke commands: each other object edits the row equal to it, and a row the art does not have as a fill or
|
||||
/// stroke as edited, or that no other object has, is an error that leaves the document and its undo history as they are.
|
||||
#[test]
|
||||
fn aligned_paint_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_objects() {
|
||||
let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
|
||||
let green = Paint::solid(vectorcraft_color::Color::rgb(0.0, 1.0, 0.0));
|
||||
// The art's row 1 is the blue fill the mark has as row 0, and its row 2 the black stroke the mark has as row 1.
|
||||
let (mut s, _, art, mark) = aligned_design_art();
|
||||
let black = rows(&s, mark).items[1].clone();
|
||||
s.edit("Stroke", |d, _| {
|
||||
d.node_mut(art).unwrap().appearance.items.push(black.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (art_was, mark_was) = (rows(&s, art), rows(&s, mark));
|
||||
let fill = |s: &mut Session, cmd: &str, p: serde_json::Value| {
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let now = rows(s, mark);
|
||||
assert_eq!(rows(s, art), art_was, "{cmd}");
|
||||
assert_ne!(now.items[0], mark_was.items[0], "{cmd} edits the mark's blue fill");
|
||||
assert_eq!(now.items[1], mark_was.items[1], "{cmd} leaves the mark's stroke");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(rows(s, mark), mark_was, "{cmd} is one undo step");
|
||||
now
|
||||
};
|
||||
let ids = [art.0, mark.0];
|
||||
let now = fill(&mut s, "paint.setFill", json!({"ids": ids, "item": 1, "aligned": true, "color": "#00ff00"}));
|
||||
assert_eq!(now.items[0].paint(), &green);
|
||||
let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 1, "aligned": true}));
|
||||
assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the inverted color is the last color, not the art's");
|
||||
let now = fill(&mut s, "paint.lastColor", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false}));
|
||||
assert_eq!(Some(s.last_solid), now.items[0].paint().color());
|
||||
// Without `aligned`, the art is left out and the item is a row of the mark.
|
||||
let now = fill(&mut s, "paint.invert", json!({"ids": ids, "item": 0}));
|
||||
assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the mark's inverted color is the last color, not the art's");
|
||||
s.last_solid = vectorcraft_color::Color::rgb(0.5, 0.5, 0.5);
|
||||
let now = fill(&mut s, "paint.complement", json!({"ids": ids, "item": 0}));
|
||||
assert_eq!(Some(s.last_solid), now.items[0].paint().color(), "the mark's complement is the last color, not the art's");
|
||||
let now = fill(&mut s, "paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "linear"}));
|
||||
let Paint::Gradient(g) = now.items[0].paint() else { panic!("{:?}", now.items[0].paint()) };
|
||||
assert_eq!(&s.last_gradient, &**g, "the mark's new gradient is the last gradient");
|
||||
let now = fill(&mut s, "paint.lastGradient", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false}));
|
||||
assert!(matches!(now.items[0].paint(), Paint::Gradient(_)));
|
||||
|
||||
let stroke = |s: &mut Session, cmd: &str, p: serde_json::Value| {
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let now = rows(s, mark);
|
||||
assert_eq!(rows(s, art), art_was, "{cmd}");
|
||||
assert_eq!(now.items[0], mark_was.items[0], "{cmd} leaves the mark's fill");
|
||||
assert_ne!(now.items[1], mark_was.items[1], "{cmd} edits the mark's stroke");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(rows(s, mark), mark_was, "{cmd} is one undo step");
|
||||
now
|
||||
};
|
||||
let now = stroke(&mut s, "paint.setStroke", json!({"ids": ids, "item": 2, "aligned": true, "color": "#00ff00"}));
|
||||
assert_eq!(now.items[1].paint(), &green);
|
||||
let now = stroke(&mut s, "stroke.set", json!({"ids": ids, "item": 2, "aligned": true, "weight": 5}));
|
||||
assert_eq!(now.stroke_at(Some(1)).unwrap().width, 5.0);
|
||||
let now = stroke(&mut s, "stroke.setAdvanced", json!({"ids": ids, "item": 2, "aligned": true, "arrowScale": [200, 200]}));
|
||||
assert_eq!(now.stroke_at(Some(1)).unwrap().arrow_scale, (200.0, 200.0));
|
||||
// Without `stroke`, the kind of the art's row is edited.
|
||||
let now = stroke(&mut s, "paint.editGradient", json!({"ids": ids, "item": 2, "aligned": true, "kind": "linear"}));
|
||||
assert!(matches!(now.items[1].paint(), Paint::Gradient(_)));
|
||||
fill(&mut s, "paint.complement", json!({"ids": ids, "item": 1, "aligned": true, "stroke": false}));
|
||||
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, p, said) in [
|
||||
("stroke.set", json!({"ids": ids, "item": 1, "aligned": true, "weight": 5}), "appearance item 1 is not a stroke"),
|
||||
("paint.setFill", json!({"ids": ids, "item": 2, "aligned": true, "color": "#00ff00"}), "appearance item 2 is not a fill"),
|
||||
("paint.setFill", json!({"ids": ids, "item": 0, "aligned": true, "color": "#00ff00"}), "no appearance item 0"),
|
||||
("paint.setFill", json!({"ids": ids, "item": 9, "aligned": true, "color": "#00ff00"}), "no appearance item 9"),
|
||||
// The art alone: no other object has the row.
|
||||
("paint.setFill", json!({"ids": [art.0], "item": 9, "aligned": true, "color": "#00ff00"}), "no appearance item 9"),
|
||||
("paint.setFill", json!({"ids": [art.0], "item": 1, "aligned": true, "color": "#00ff00"}), "no appearance item 1"),
|
||||
("stroke.set", json!({"ids": [art.0], "item": 1, "aligned": true, "weight": 5}), "appearance item 1 is not a stroke"),
|
||||
("paint.editGradient", json!({"ids": [art.0], "item": 1, "aligned": true, "kind": "linear"}), "no appearance item 1"),
|
||||
// The weight steps take no row: they step each object's active or top stroke.
|
||||
("stroke.weightUp", json!({"ids": ids, "item": 2}), "unknown parameter `item`"),
|
||||
("stroke.weightUp", json!({"ids": ids, "aligned": true}), "unknown parameter `aligned`"),
|
||||
("stroke.weightDown", json!({"ids": ids, "item": 2}), "unknown parameter `item`"),
|
||||
("stroke.weightDown", json!({"ids": ids, "aligned": true}), "unknown parameter `aligned`"),
|
||||
] {
|
||||
let defaults = format!("{:?}", (&s.paint.fill, &s.paint.stroke, &s.last_gradient));
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(said), "{cmd}: {e}");
|
||||
assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}");
|
||||
assert_eq!(format!("{:?}", (&s.paint.fill, &s.paint.stroke, &s.last_gradient)), defaults, "{cmd}");
|
||||
}
|
||||
|
||||
// An object with no row equal to the art's is left out of what the commands report as edited.
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let rect = *s.doc().unwrap().selection.subjects().first().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [rect.0], "color": "#ff00ff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff00ff"})).unwrap();
|
||||
let rect_was = rows(&s, rect);
|
||||
let ids = [art.0, mark.0, rect.0];
|
||||
for (cmd, p, key, said) in [
|
||||
("paint.setFill", json!({"ids": ids, "item": 1, "aligned": true, "color": "#00ff00"}), "objects", json!(1)),
|
||||
("stroke.set", json!({"ids": ids, "item": 2, "aligned": true, "weight": 5}), "objects", json!(1)),
|
||||
("paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "linear"}), "ids", json!([mark.0])),
|
||||
("paint.setGradientGeom", json!({"ids": ids, "item": 1, "aligned": true, "start": [0, 0], "end": [10, 40]}), "ids", json!([mark.0])),
|
||||
] {
|
||||
if cmd == "paint.setGradientGeom" {
|
||||
s.execute("paint.editGradient", &json!({"ids": [mark.0], "item": 0, "kind": "linear"})).unwrap();
|
||||
let gradient = rows(&s, mark).items[0].clone();
|
||||
s.edit("Gradient", |d, _| {
|
||||
d.node_mut(art).unwrap().appearance.items[1] = gradient.clone();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
let r = s.execute(cmd, &p).unwrap();
|
||||
assert_eq!(r[key], said, "{cmd}: {r}");
|
||||
assert_eq!(rows(&s, rect), rect_was, "{cmd}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
// A gradient spanning the selection spans only the objects that take it: a distant object without an equal row does
|
||||
// not move it.
|
||||
s.execute("shape.rectangle", &json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap();
|
||||
let far = *s.doc().unwrap().selection.subjects().first().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [far.0], "color": "#ff00ff"})).unwrap();
|
||||
let far_was = rows(&s, far);
|
||||
let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]});
|
||||
let mut placed = Vec::new();
|
||||
for ids in [vec![art.0, mark.0], vec![art.0, mark.0, far.0]] {
|
||||
s.execute("paint.setFill", &json!({"ids": ids, "item": 1, "aligned": true, "gradient": gradient, "span": "selection"})).unwrap();
|
||||
placed.push(rows(&s, mark).items[0].clone());
|
||||
assert_eq!(rows(&s, far), far_was);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(matches!(placed[0].paint(), Paint::Gradient(_)));
|
||||
assert_eq!(placed[1], placed[0]);
|
||||
}
|
||||
|
||||
/// The gradient and freeform gradient commands read an `item` given with `aligned: true` and the art of a graph design in
|
||||
/// a series first as a row of the art's stack, as the paint commands do.
|
||||
#[test]
|
||||
fn aligned_gradient_rows_of_a_graph_designs_art_edit_the_equal_rows_of_the_other_objects() {
|
||||
let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
|
||||
for kind in ["linear", "freeform"] {
|
||||
let (mut s, _, art, mark) = aligned_design_art();
|
||||
// The mark's fill and the art's equal row become the same gradient.
|
||||
s.execute("paint.editGradient", &json!({"ids": [mark.0], "item": 0, "kind": kind})).unwrap();
|
||||
let gradient = rows(&s, mark).items[0].clone();
|
||||
// A yellow fill above the mark's gradient is the mark's row 1, as the gradient is the art's row 1.
|
||||
let mut yellow = gradient.clone();
|
||||
*yellow.paint_mut() = Paint::solid(vectorcraft_color::Color::rgb(1.0, 1.0, 0.0));
|
||||
s.edit("Gradient", |d, _| {
|
||||
d.node_mut(art).unwrap().appearance.items[1] = gradient.clone();
|
||||
d.node_mut(mark).unwrap().appearance.items.insert(1, yellow.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let ids = [art.0, mark.0];
|
||||
let edits = if kind == "linear" {
|
||||
vec![
|
||||
("paint.setGradientGeom", json!({"ids": ids, "item": 1, "aligned": true, "start": [0, 0], "end": [10, 40]})),
|
||||
("paint.editGradient", json!({"ids": ids, "item": 1, "aligned": true, "kind": "radial"})),
|
||||
]
|
||||
} else {
|
||||
vec![("paint.freeform.addPoint", json!({"ids": ids, "item": 1, "aligned": true, "at": [5, 5]}))]
|
||||
};
|
||||
for (cmd, p) in edits {
|
||||
let (art_was, mark_was) = (rows(&s, art), rows(&s, mark));
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let now = rows(&s, mark);
|
||||
assert_eq!(rows(&s, art), art_was, "{cmd}");
|
||||
assert_ne!(now.items[0], mark_was.items[0], "{cmd} edits the mark's gradient fill");
|
||||
assert_eq!(now.items[1..], mark_was.items[1..], "{cmd}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// The edited gradient is the last gradient (paint.setGradientGeom does not set it).
|
||||
if cmd != "paint.setGradientGeom" {
|
||||
let Paint::Gradient(g) = now.items[0].paint() else { panic!("{cmd}") };
|
||||
assert_eq!(&s.last_gradient, &**g, "{cmd}: the mark's edited gradient is the last gradient");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Contents row of a graph design's copy and of a group whose stack differs is not moved with `aligned: true`, as
|
||||
/// the rows are not.
|
||||
#[test]
|
||||
|
||||
@@ -1298,7 +1298,112 @@ pub(crate) fn path_shown(path: &str, doc_path: Option<&str>) -> bool {
|
||||
/// alone in a reply to the caller asking now? Only a path [`path_shown`] does not allow; a URL is
|
||||
/// always shown as it is.
|
||||
pub(crate) fn script_hidden(f: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url))
|
||||
file_hidden(f, doc_path)
|
||||
}
|
||||
|
||||
/// Is the file `path` (a link of the document saved at `doc_path`) one the caller asking now may
|
||||
/// not be shown? Only a path [`path_shown`] does not allow; a URL is not a file and is shown as it is.
|
||||
pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(path, doc_path) && !matches!(fileio::document_path(path, doc_path), Err(craft_docpath::Refused::Url))
|
||||
}
|
||||
|
||||
/// Does an SVG of `d` (a document whose links are looked for from `base`) written for the caller
|
||||
/// asking now name the file of a linked image that [`file_hidden`] keeps from it? An `<image>`
|
||||
/// names its image's file with SVG Options › Images set to Link (`link`), and with Embed when the
|
||||
/// document holds no pixels for the image. An image with a solid colorize paint whose pixels are
|
||||
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
|
||||
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
|
||||
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
|
||||
/// no other resource. Hidden layers and objects are written only with
|
||||
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
|
||||
/// Always `false` without read roots in force.
|
||||
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
|
||||
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
|
||||
return false;
|
||||
}
|
||||
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
|
||||
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
|
||||
}
|
||||
|
||||
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
|
||||
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
|
||||
/// Only layers and groups lose members; other objects keep theirs as they are.
|
||||
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
|
||||
if !(n.visible || hidden) {
|
||||
return None;
|
||||
}
|
||||
let mut n = n.clone();
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
|
||||
let art = svg_written(&m.art, hidden)?;
|
||||
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
|
||||
});
|
||||
if n.extras().mask.is_some() {
|
||||
n.extras_mut().mask = mask;
|
||||
}
|
||||
match &mut n.kind {
|
||||
NodeKind::Layer { template: true, children, .. } => children.clear(),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// [`svg_names_hidden_image`] for every image of `d`: in the layers, symbols, graph designs,
|
||||
/// patterns, opacity masks and the art of the stored brushes, used or not.
|
||||
fn names_hidden_image(d: &Document, base: LinkBase, link: bool) -> bool {
|
||||
let d = with_brush_art(d);
|
||||
let mut hidden = false;
|
||||
d.visit_images(|n, im| {
|
||||
if hidden {
|
||||
return;
|
||||
}
|
||||
let shown = d.shown_image(n, im);
|
||||
let Some(l) = &shown.link else { return };
|
||||
let blob = d.image_blob(&shown).filter(|b| !b.bytes.is_empty());
|
||||
// The SVG writes an image with a solid colorize paint as colorized pixels when they are
|
||||
// gray, and leaves it out when the document holds none of them.
|
||||
if matches!(n.extras().colorize.as_deref(), Some(vectorcraft_color::Paint::Solid { .. })) && blob.is_none_or(|b| b.gray_source().is_some()) {
|
||||
return;
|
||||
}
|
||||
let named = link || blob.is_none();
|
||||
hidden = named && file_hidden(&l.path, base.doc);
|
||||
});
|
||||
hidden
|
||||
}
|
||||
|
||||
/// Does the native document an SVG of `d` (a document whose links are looked for from `base`)
|
||||
/// carries with Preserve Editing Capabilities name a file that the caller asking now may not be
|
||||
/// shown: the file of a linked image or placed document ([`file_hidden`]), the relative path kept
|
||||
/// of one, which is followed from the file the document was read from and from the document's own
|
||||
/// folder, or a data set's image? Links in the layers, symbols, graph designs, patterns, the pattern
|
||||
/// being edited as it was before, opacity masks and the art of the stored brushes are all checked,
|
||||
/// as [`with_hidden_paths_named`] checks them. A stored brush library that is not a list, or holds
|
||||
/// an entry that does not read as a brush, counts as naming one: the native document carries it as
|
||||
/// it is, and its links cannot be checked. Always `false` without read roots in force.
|
||||
pub(crate) fn names_hidden_file(d: &Document, base: LinkBase) -> bool {
|
||||
if crate::file_access::current().is_none() {
|
||||
return false;
|
||||
}
|
||||
let unread = |list: &Vec<Value>| list.iter().any(|raw| vectorcraft_brush::Brush::from_json(raw.clone()).is_err());
|
||||
if d.unknown.get(vectorcraft_brush::DOC_KEY).is_some_and(|v| v.as_array().is_none_or(unread)) {
|
||||
return true;
|
||||
}
|
||||
let relative_hidden = |r: &str| [base.relative, base.doc].into_iter().any(|from| !path_shown(r, from));
|
||||
let hidden = |l: &LinkInfo| file_hidden(&l.path, base.doc) || l.relative.as_deref().is_some_and(relative_hidden);
|
||||
let image_hidden = |v: &DataValue| matches!(v, DataValue::Image(path) if file_hidden(path, base.doc));
|
||||
if d.variables.datasets.iter().any(|set| set.values.values().any(image_hidden)) {
|
||||
return true;
|
||||
}
|
||||
let mut d = with_brush_art(d);
|
||||
if let Some(original) = d.pattern_edit.as_ref().and_then(|e| e.original.clone()) {
|
||||
d.to_mut().patterns.push(original);
|
||||
}
|
||||
let mut found = false;
|
||||
d.visit_images(|_, im| found |= im.link.as_ref().is_some_and(hidden));
|
||||
d.visit_placed(|_, p| found |= hidden(&p.link));
|
||||
found
|
||||
}
|
||||
|
||||
/// The linked JavaScript file `f` of the open document `st` as a reply to the caller asking now
|
||||
|
||||
@@ -158,6 +158,9 @@ fn apply_transform_moving_guides(
|
||||
}
|
||||
None => ids.clone(),
|
||||
};
|
||||
// Pattern editing with Move Tile with Art: the tile art's bounds before a move.
|
||||
let moves_only = c[0] == 1.0 && c[1] == 0.0 && c[2] == 0.0 && c[3] == 1.0;
|
||||
let tile_art = if objects && !copy && moves_only { crate::cmd::patterncmds::tile_art_bounds(d) } else { None };
|
||||
// Transforms don't move nodes in the tree, so reuse the paths found for the no-copy
|
||||
// case; copies and a settled typing session need paths from the edited document.
|
||||
let paths = if reindex { d.index_paths(targets.iter().copied()) } else { paths };
|
||||
@@ -172,6 +175,10 @@ fn apply_transform_moving_guides(
|
||||
for id in &targets {
|
||||
super::pixelgrid::keep_compound_aligned(d, *id, sc);
|
||||
}
|
||||
// Moving all of the tile art moves the tile as far.
|
||||
if let Some(before) = tile_art {
|
||||
crate::cmd::patterncmds::move_tile_with_art(d, &targets, before);
|
||||
}
|
||||
}
|
||||
if with_guides && (delta.x != 0.0 || delta.y != 0.0) {
|
||||
for i in sel.guides.clone() {
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke",
|
||||
[],
|
||||
None,
|
||||
"{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Invert",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -105,7 +105,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Complement",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
|
||||
),
|
||||
@@ -114,7 +114,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Apply Last Color",
|
||||
[],
|
||||
Some(","),
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let paint = Paint::solid(s.last_solid);
|
||||
@@ -126,7 +126,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Apply Last Gradient",
|
||||
[],
|
||||
Some("."),
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default → {objects} (as paint.setFill)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone())));
|
||||
@@ -553,7 +553,14 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, fill);
|
||||
let selected = item.targets(s, p)?;
|
||||
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
|
||||
let paint = if span { placed_across(&s.doc()?.doc, &ids, paint, p, fill) } else { paint };
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
let paint = if span {
|
||||
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it.
|
||||
let spanned: Vec<NodeId> = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect();
|
||||
placed_across(&s.doc()?.doc, &spanned, paint, p, fill)
|
||||
} else {
|
||||
paint
|
||||
};
|
||||
// The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso: a solid
|
||||
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`).
|
||||
let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] };
|
||||
@@ -570,10 +577,12 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
// The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep
|
||||
// for their characters; a row edit is kept with the label's rows.
|
||||
let characters = std::cell::RefCell::new(Vec::new());
|
||||
edit_items_then(
|
||||
// The objects counted: with a design's art, those with a row equal to the art's.
|
||||
let ids = edit_items_then(
|
||||
s,
|
||||
&ids,
|
||||
item,
|
||||
of,
|
||||
cmd,
|
||||
label,
|
||||
fill,
|
||||
@@ -1070,30 +1079,32 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
return Ok(json!({ "changed": changed as usize }));
|
||||
}
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
|
||||
let (r, shown_item, edited) = match item {
|
||||
ItemTarget::Item { index, .. } => {
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
|
||||
let (r, shown_at) = match item {
|
||||
ItemTarget::Item { .. } => {
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
// The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row.
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it {
|
||||
ItemTarget::Item { index, .. } => Some((id, Some(index))),
|
||||
ItemTarget::Top => None,
|
||||
});
|
||||
let mut changed = 0;
|
||||
edit_items(s, &ids, item, cmd, label, !stroke, |n, i| {
|
||||
edit_items(s, &targets, item, of, cmd, label, !stroke, |n, i| {
|
||||
let paint =
|
||||
if stroke { n.appearance.stroke_at_mut(i).map(|l| &mut l.paint) } else { n.appearance.fill_at_mut(i).map(|l| &mut l.paint) };
|
||||
changed += paint.is_some_and(|paint| super::colorcmds::map_paint(paint, f)) as usize;
|
||||
Ok(())
|
||||
})?;
|
||||
(json!({ "changed": changed }), Some(index), Some(ids))
|
||||
(json!({ "changed": changed }), shown_at)
|
||||
}
|
||||
// The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles.
|
||||
ItemTarget::Top => {
|
||||
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
|
||||
(super::colorcmds::recolor(s, &q, cmd, label, f)?, None, None)
|
||||
(super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None)))
|
||||
}
|
||||
};
|
||||
// The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none.
|
||||
let shown_ids = match edited {
|
||||
Some(ids) => ids,
|
||||
None => leaf_targets(s, &ids)?,
|
||||
};
|
||||
if let Some(shown) = shown_ids.first().and_then(|id| s.doc().ok()?.doc.node(*id).map(|n| proxy_paint(n, stroke, shown_item))) {
|
||||
if let Some(shown) = shown_at.and_then(|(id, at)| s.doc().ok()?.doc.node(id).map(|n| proxy_paint(n, stroke, at))) {
|
||||
s.remember_paint(&shown);
|
||||
}
|
||||
Ok(r)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pattern Options",
|
||||
["Window", "Pattern Options"],
|
||||
None,
|
||||
"{name? (default: the pattern being edited), newName? (trimmed; blank: the name is kept), tileType?, brickOffset?, width?, height?, hSpacing?, vSpacing?, sizeTileToArt?: bool, overlap?: {h: left|right, v: top|bottom}, copies?: 3|5|7|9, dimCopies?: %, showTileEdge?: bool, showSwatchBounds?: bool (outline the part of the tiling the swatch repeats, dashed)}",
|
||||
"{name? (default: the pattern being edited), newName? (trimmed; blank: the name is kept), tileType?, brickOffset?, width?, height?, hSpacing?, vSpacing?, sizeTileToArt?: bool, moveTileWithArt?: bool (in pattern editing mode, a move of all of the tile art moves the tile with it; off for a new pattern), overlap?: {h: left|right, v: top|bottom}, copies?: 3|5|7|9, dimCopies?: %, showTileEdge?: bool, showSwatchBounds?: bool (outline the part of the tiling the swatch repeats, dashed)}",
|
||||
has_doc,
|
||||
pattern_options
|
||||
),
|
||||
@@ -530,7 +530,7 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cur = s.doc()?.doc.pattern(&name).cloned().ok_or_else(|| bad(C, format!("no pattern `{name}`")))?;
|
||||
let tt = tile_type_param(p, C, cur.tile_type)?;
|
||||
check_numbers(p, &["width", "height", "hSpacing", "vSpacing", "copies", "dimCopies"], C)?;
|
||||
check_switches(p, &["sizeTileToArt", "showTileEdge", "showSwatchBounds"], C)?;
|
||||
check_switches(p, &["sizeTileToArt", "moveTileWithArt", "showTileEdge", "showSwatchBounds"], C)?;
|
||||
let num = |k: &str| p.get(k).and_then(Value::as_f64);
|
||||
for k in ["width", "height"] {
|
||||
if num(k).is_some_and(|v| !(v.is_finite() && v > 0.0)) {
|
||||
@@ -560,11 +560,11 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let edit_layer = editing(s).filter(|e| e.pattern == name).map(|e| e.layer);
|
||||
let out_name = new_name.clone().unwrap_or(name.clone());
|
||||
s.edit("Pattern Options", |d, _| {
|
||||
// While editing, the tile art is the edit layer's.
|
||||
let live_art: Option<Vec<Arc<Node>>> =
|
||||
edit_layer.and_then(|l| d.node(l)).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect());
|
||||
let def = d.pattern_mut(&name).ok_or_else(|| EngineError::Other("pattern missing".into()))?;
|
||||
// While editing, the tile art is the edit layer's.
|
||||
let live_art = |d: &Document| -> Option<Vec<Arc<Node>>> {
|
||||
edit_layer.and_then(|l| d.node(l)).and_then(|l| l.children()).map(|ch| ch.iter().filter(|c| !c.is_ruler_guide()).cloned().collect())
|
||||
};
|
||||
let apply = |def: &mut PatternDef, live_art: Option<Vec<Arc<Node>>>| {
|
||||
def.tile_type = tt;
|
||||
def.overlap = overlap;
|
||||
if let Some(v) = num("hSpacing") {
|
||||
@@ -576,6 +576,9 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = p.get("sizeTileToArt").and_then(Value::as_bool) {
|
||||
def.size_tile_to_art = v;
|
||||
}
|
||||
if let Some(v) = p.get("moveTileWithArt").and_then(Value::as_bool) {
|
||||
def.move_tile_with_art = v;
|
||||
}
|
||||
if let Some(v) = num("copies") {
|
||||
def.copies = (v as u32).clamp(1, 15) | 1;
|
||||
}
|
||||
@@ -590,13 +593,24 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if def.size_tile_to_art {
|
||||
let saved = std::mem::take(&mut def.art);
|
||||
def.art = live_art.clone().unwrap_or_else(|| saved.clone());
|
||||
def.art = live_art.unwrap_or_else(|| saved.clone());
|
||||
def.fit_tile_to_art();
|
||||
def.art = saved;
|
||||
} else if num("width").is_some() || num("height").is_some() {
|
||||
let c = def.tile.center();
|
||||
def.tile = Rect::from_center_size(c, (num("width").unwrap_or(def.tile.width()), num("height").unwrap_or(def.tile.height())));
|
||||
}
|
||||
};
|
||||
// Options that change nothing leave the document and its undo history as they are.
|
||||
let mut next = cur.clone();
|
||||
apply(&mut next, live_art(&s.doc()?.doc));
|
||||
if next == cur && new_name.is_none() {
|
||||
return Ok(json!({ "name": out_name }));
|
||||
}
|
||||
s.edit("Pattern Options", |d, _| {
|
||||
let live = live_art(d);
|
||||
let def = d.pattern_mut(&name).ok_or_else(|| EngineError::Other("pattern missing".into()))?;
|
||||
apply(def, live);
|
||||
if let Some(nn) = &new_name {
|
||||
def.name = nn.clone();
|
||||
rename_pattern_uses(d, &name, nn);
|
||||
@@ -609,6 +623,47 @@ fn pattern_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": out_name }))
|
||||
}
|
||||
|
||||
/// The tile art's objects (the editing layer's, ruler guides aside) while `d` edits a pattern that
|
||||
/// has Move Tile with Art on, with the pattern's name.
|
||||
fn moving_tile_art(d: &Document) -> Option<(String, Vec<Arc<Node>>)> {
|
||||
let pe = d.pattern_edit.as_ref()?;
|
||||
if !d.pattern(&pe.pattern).is_some_and(|p| p.move_tile_with_art) {
|
||||
return None;
|
||||
}
|
||||
let art = d.node(pe.layer)?.children()?.iter().filter(|c| !c.is_ruler_guide()).cloned().collect();
|
||||
Some((pe.pattern.clone(), art))
|
||||
}
|
||||
|
||||
/// Before a move: the bounds of the tile art for [`move_tile_with_art`], `None` unless `d` edits a
|
||||
/// pattern with Move Tile with Art on.
|
||||
pub(crate) fn tile_art_bounds(d: &Document) -> Option<Rect> {
|
||||
moving_tile_art(d).and_then(|(_, art)| vectorcraft_doc::live::nodes_bounds(&art))
|
||||
}
|
||||
|
||||
/// Move Tile with Art: after a move of `moved` that takes every object of the tile art (a group
|
||||
/// counting when all of its objects moved), the tile moves by as much as the art did, measured from
|
||||
/// its bounds `before` the move (objects aligned to the pixel grid snap back to it). A move of only
|
||||
/// some of the art leaves the tile where it is.
|
||||
pub(crate) fn move_tile_with_art(d: &mut Document, moved: &[NodeId], before: Rect) {
|
||||
let Some((name, art)) = moving_tile_art(d) else { return };
|
||||
let moved: std::collections::HashSet<NodeId> = moved.iter().copied().collect();
|
||||
// An object moves whole when it moved, or when every object in it did (a group whose members
|
||||
// were selected and moved one by one).
|
||||
fn whole(n: &Node, moved: &std::collections::HashSet<NodeId>) -> bool {
|
||||
moved.contains(&n.id) || n.children().is_some_and(|ch| !ch.is_empty() && ch.iter().all(|c| whole(c, moved)))
|
||||
}
|
||||
if art.is_empty() || !art.iter().all(|c| whole(c, &moved)) {
|
||||
return;
|
||||
}
|
||||
let Some(after) = vectorcraft_doc::live::nodes_bounds(&art) else { return };
|
||||
let by = after.origin() - before.origin();
|
||||
if (by.x != 0.0 || by.y != 0.0)
|
||||
&& let Some(def) = d.pattern_mut(&name)
|
||||
{
|
||||
def.tile = def.tile + by;
|
||||
}
|
||||
}
|
||||
|
||||
/// Side `side` of the `overlap` object `o` gives `cmd`: true for the second of `names`, false for the
|
||||
/// first, `current` when `o` leaves it out or gives null. Any other value is an error.
|
||||
fn overlap_side(o: &Value, side: &str, names: [&str; 2], current: bool, cmd: &str) -> Result<bool> {
|
||||
@@ -680,6 +735,7 @@ fn pattern_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"hSpacing": p.h_spacing,
|
||||
"vSpacing": p.v_spacing,
|
||||
"sizeTileToArt": p.size_tile_to_art,
|
||||
"moveTileWithArt": p.move_tile_with_art,
|
||||
"overlap": {"h": if p.overlap.right_in_front { "right" } else { "left" }, "v": if p.overlap.bottom_in_front { "bottom" } else { "top" }},
|
||||
"copies": p.copies,
|
||||
"dimCopies": p.dim_copies,
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -100,6 +100,9 @@ pub(crate) struct DocumentArt {
|
||||
/// What is shown: the artboard, or the art's bounds.
|
||||
pub frame: Rect,
|
||||
pub warnings: Vec<String>,
|
||||
/// Whether a PDF or `.ai` page was read from the file's editing data (its page only a
|
||||
/// placeholder, or its PDF part unreadable) instead of from the page.
|
||||
pub editing_data: bool,
|
||||
}
|
||||
|
||||
/// Artboard `page` (1-based) of the VectorCraft document `name` (`bytes`, read from `path` when
|
||||
@@ -114,6 +117,21 @@ pub(crate) fn document_art(
|
||||
bounding: bool,
|
||||
page_box: PageBox,
|
||||
cmd: &str,
|
||||
) -> Result<DocumentArt> {
|
||||
opened_document_art(name, (bytes, None), path, page, bounding, page_box, cmd)
|
||||
}
|
||||
|
||||
/// [`document_art`] of `bytes` and, for a PDF already read, `opened`: the PDF `bytes` as
|
||||
/// [`vectorcraft_pdf::open_pdf`] read it without a password, so its page is read without reading
|
||||
/// the file again.
|
||||
fn opened_document_art(
|
||||
name: &str,
|
||||
(bytes, opened): (&[u8], Option<&vectorcraft_pdf::Opened>),
|
||||
path: Option<&str>,
|
||||
page: u32,
|
||||
bounding: bool,
|
||||
page_box: PageBox,
|
||||
cmd: &str,
|
||||
) -> Result<DocumentArt> {
|
||||
let file = fileio::file_name(name);
|
||||
let pdf = is_pdf(name, bytes);
|
||||
@@ -125,7 +143,7 @@ pub(crate) fn document_art(
|
||||
}
|
||||
if pdf {
|
||||
let o = fileio::LoadOptions { crop: crop_to(page_box), ..Default::default() };
|
||||
return super::pdf_art(name, bytes, path, page as usize, o, bounding, cmd);
|
||||
return super::pdf_art(name, (bytes, opened), path, page as usize, o, bounding, cmd);
|
||||
}
|
||||
let mut l = fileio::load(name, bytes)?;
|
||||
// Its linked images show their files; its placed documents stay as they are, unless their
|
||||
@@ -145,7 +163,7 @@ pub(crate) fn document_art(
|
||||
let nodes = super::on_artboard(&symbols, &layers, board);
|
||||
let frame = if bounding { super::shown_bounds(&symbols, &nodes) } else { Some(board) };
|
||||
let frame = frame.filter(|r| r.width() > 0.0 || r.height() > 0.0).ok_or_else(|| bad(cmd, format!("`{file}` has no art to place")))?;
|
||||
Ok(DocumentArt { doc: l.doc, nodes, clip: (!bounding).then_some(board), frame, warnings: l.warnings })
|
||||
Ok(DocumentArt { doc: l.doc, nodes, clip: (!bounding).then_some(board), frame, warnings: l.warnings, editing_data: false })
|
||||
}
|
||||
|
||||
/// The most placed documents read inside one another while their links are resolved.
|
||||
@@ -223,6 +241,8 @@ pub(crate) struct Source {
|
||||
pub warnings: Vec<String>,
|
||||
/// The colour mode the file's art was read in (a PDF page painted mostly in CMYK reads in CMYK).
|
||||
pub color_mode: ColorMode,
|
||||
/// [`DocumentArt::editing_data`].
|
||||
pub editing_data: bool,
|
||||
}
|
||||
|
||||
/// The VectorCraft document `name` (`bytes`, from `path` when there is one) read for showing
|
||||
@@ -232,33 +252,48 @@ pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bo
|
||||
read_source(name, bytes, None, path, (page, bounding, page_box), cmd)
|
||||
}
|
||||
|
||||
/// [`source`] of the file whose bytes `bytes` holds, kept by the blob without a copy of its own:
|
||||
/// several pages of one file read this way share one copy of it.
|
||||
/// A PDF (or PDF-compatible `.ai`) whose pages are read for placing linked, read once for them all.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct SharedFile<'a> {
|
||||
/// The file's bytes, which every page's blob keeps without a copy of its own.
|
||||
pub bytes: &'a Arc<Vec<u8>>,
|
||||
/// The bytes' hash ([`hash_bytes`]).
|
||||
pub hash: &'a str,
|
||||
/// The bytes as [`vectorcraft_pdf::open_pdf`] read them, without a password.
|
||||
pub opened: &'a vectorcraft_pdf::Opened,
|
||||
}
|
||||
|
||||
/// [`source`] of page `page` of `file`: several pages of one file read this way share one copy of
|
||||
/// it, and the file is hashed and read once for them all.
|
||||
pub(crate) fn shared_source(
|
||||
name: &str,
|
||||
bytes: &Arc<Vec<u8>>,
|
||||
file: SharedFile<'_>,
|
||||
path: Option<&str>,
|
||||
page: u32,
|
||||
bounding: bool,
|
||||
page_box: PageBox,
|
||||
cmd: &str,
|
||||
) -> Result<Source> {
|
||||
read_source(name, bytes, Some(bytes), path, (page, bounding, page_box), cmd)
|
||||
read_source(name, file.bytes, Some(file), path, (page, bounding, page_box), cmd)
|
||||
}
|
||||
|
||||
/// [`source`], the blob keeping `shared` when given (else a copy of `bytes`); `shown` is the page
|
||||
/// (or artboard), whether the art's bounds are shown, and the page's box.
|
||||
/// [`source`], the blob keeping `shared`'s bytes when given (else a copy of `bytes`), its hash
|
||||
/// used for the key (else `bytes` hashed) and its pages read from what was read of it; `shown` is
|
||||
/// the page (or artboard), whether the art's bounds are shown, and the page's box.
|
||||
fn read_source(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
shared: Option<&Arc<Vec<u8>>>,
|
||||
shared: Option<SharedFile<'_>>,
|
||||
path: Option<&str>,
|
||||
shown: (u32, bool, PageBox),
|
||||
cmd: &str,
|
||||
) -> Result<Source> {
|
||||
let (page, bounding, page_box) = shown;
|
||||
let hash = shared.map_or_else(|| hash_bytes(bytes), |f| f.hash.to_string());
|
||||
let opened = shared.map(|f| f.opened);
|
||||
let shared = shared.map(|f| f.bytes);
|
||||
// The same document placed the same way is read once (placing it again is free).
|
||||
let key = key_for(&hash_bytes(bytes), page, bounding, page_box);
|
||||
let key = key_for(&hash, page, bounding, page_box);
|
||||
// Resolving its links depends on where the file is and on what the caller may read, so a hit
|
||||
// needs the same path, and nothing is shared with or from a confined (automation) caller.
|
||||
let confined = crate::file_access::current().is_some();
|
||||
@@ -269,7 +304,7 @@ fn read_source(
|
||||
}
|
||||
return Ok(s);
|
||||
}
|
||||
let a = document_art(name, bytes, path, page, bounding, page_box, cmd)?;
|
||||
let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?;
|
||||
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
|
||||
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
|
||||
let shown = PlacedDocument {
|
||||
@@ -284,10 +319,10 @@ fn read_source(
|
||||
};
|
||||
let art = group(a.nodes, a.clip);
|
||||
blob.proxy = preview(&a.doc, &art, a.frame).map(Arc::new);
|
||||
let color_mode = a.doc.color_mode;
|
||||
let (color_mode, editing_data) = (a.doc.color_mode, a.editing_data);
|
||||
// Drawing it needn't read it again.
|
||||
vectorcraft_doc::placed_document::prime(&shown, blob.bytes.clone(), (a.doc, art, a.frame));
|
||||
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode };
|
||||
let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode, editing_data };
|
||||
if !confined {
|
||||
let mut m = lock_memo();
|
||||
if m.len() >= MEMO_SIZE {
|
||||
|
||||
@@ -540,6 +540,7 @@ struct Saved {
|
||||
recent_colors: Vec<vectorcraft_color::Color>,
|
||||
recent_urls: Vec<String>,
|
||||
global_edit_options: super::globaledit::Options,
|
||||
select_similar: &'static str,
|
||||
envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>,
|
||||
}
|
||||
|
||||
@@ -564,6 +565,7 @@ impl Saved {
|
||||
recent_colors: s.recent_colors.clone(),
|
||||
recent_urls: s.recent_urls.clone(),
|
||||
global_edit_options: s.global_edit_options.clone(),
|
||||
select_similar: s.select_similar,
|
||||
envelope_defaults: s.envelope_defaults,
|
||||
}
|
||||
}
|
||||
@@ -587,6 +589,7 @@ impl Saved {
|
||||
s.recent_colors = self.recent_colors;
|
||||
s.recent_urls = self.recent_urls;
|
||||
s.global_edit_options = self.global_edit_options;
|
||||
s.select_similar = self.select_similar;
|
||||
s.envelope_defaults = self.envelope_defaults;
|
||||
s.pending_paint = None;
|
||||
}
|
||||
|
||||
@@ -536,6 +536,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.same.textStrokeColor",
|
||||
"select.segments",
|
||||
"select.set",
|
||||
"select.similar",
|
||||
"select.storedPath",
|
||||
"select.toggle",
|
||||
"select.update",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -225,9 +225,69 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
same_attribute
|
||||
),
|
||||
cmd!(
|
||||
"select.similar",
|
||||
"Select Similar Objects",
|
||||
[],
|
||||
None,
|
||||
"{by?: \"all\"|\"fillColor\"|\"fillAndStroke\"|\"strokeColor\"|\"strokeWeight\"|\"opacity\"|\"blendingMode\"|\"appearance\"|\"graphicStyle\"|\"shapeType\"|\"symbolInstance\"} the Control bar's Select Similar Objects button and its menu: selects the objects like the first selected object by `by`, running the select.same command of that name; `all` selects the objects with its fill and stroke colours, stroke weight, opacity and blending mode (tints, compound paths and Live Paint faces as select.same.fillColor). A `by` given is kept for the session once the selection is made; without it, the kept one (`all` until one is given). Any other `by` is an error that keeps the selection and the kept attribute → {count, by}",
|
||||
has_selection,
|
||||
similar
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The attributes Select Similar Objects (`select.similar`) selects by, in its menu's order, each
|
||||
/// with the Select › Same command it runs; `all` compares the fill and stroke colours, the stroke
|
||||
/// weight, the opacity and the blending mode at once, with no command of its own.
|
||||
pub const SIMILAR: [(&str, Option<&str>); 11] = [
|
||||
("all", None),
|
||||
("fillColor", Some("select.same.fillColor")),
|
||||
("fillAndStroke", Some("select.same.fillAndStroke")),
|
||||
("strokeColor", Some("select.same.strokeColor")),
|
||||
("strokeWeight", Some("select.same.strokeWeight")),
|
||||
("opacity", Some("select.same.opacity")),
|
||||
("blendingMode", Some("select.same.blendingMode")),
|
||||
("appearance", Some("select.same.appearance")),
|
||||
("graphicStyle", Some("select.same.graphicStyle")),
|
||||
("shapeType", Some("select.same.shapeType")),
|
||||
("symbolInstance", Some("select.same.symbolInstance")),
|
||||
];
|
||||
|
||||
fn similar(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.similar";
|
||||
let by = match text_param(p, "by", C)? {
|
||||
Some(name) => *SIMILAR.iter().find(|(n, _)| *n == name).ok_or_else(|| {
|
||||
let names: Vec<&str> = SIMILAR.iter().map(|(n, _)| *n).collect();
|
||||
bad(C, format!("unknown `by` \"{name}\": expected one of {}", names.join(", ")))
|
||||
})?,
|
||||
None => *SIMILAR.iter().find(|(n, _)| *n == s.select_similar).unwrap_or(&SIMILAR[0]),
|
||||
};
|
||||
let mut r = match by.1 {
|
||||
Some(same_cmd) => s.execute(same_cmd, &json!({}))?,
|
||||
None => {
|
||||
let tint = s.prefs.select_same_tint_percent;
|
||||
let r = same_fill(s, C, |a, b| {
|
||||
same_paint(&fill_of(a), &fill_of(b), tint)
|
||||
&& same_paint(&stroke_of(a).0, &stroke_of(b).0, tint)
|
||||
&& (stroke_weight(a) - stroke_weight(b)).abs() < 1e-9
|
||||
&& (a.opacity - b.opacity).abs() < 1e-6
|
||||
&& a.blend == b.blend
|
||||
})?;
|
||||
// Select › Reselect repeats `all`, whichever attribute is kept by then.
|
||||
if let Some(last) = s.doc_mut()?.last_selection_cmd.as_mut() {
|
||||
last.1 = json!({ "by": by.0 });
|
||||
}
|
||||
r
|
||||
}
|
||||
};
|
||||
s.select_similar = by.0;
|
||||
// A recorded action or the journal repeats the attribute used, not the one kept by then.
|
||||
s.note_journal("by", json!(by.0));
|
||||
r["by"] = json!(by.0);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Selectable objects: children of visible, unlocked layers (or of the isolation container).
|
||||
/// The objects Select All takes: those of the isolated container, else of every layer (looking
|
||||
/// through sublayers, which are not objects). In isolation mode there are none while the isolated
|
||||
|
||||
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Options",
|
||||
["Window", "Stroke"],
|
||||
None,
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}",
|
||||
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}",
|
||||
has_doc,
|
||||
stroke_set
|
||||
),
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke Options",
|
||||
[],
|
||||
None,
|
||||
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn)",
|
||||
"{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn)",
|
||||
has_doc,
|
||||
stroke_advanced
|
||||
),
|
||||
@@ -303,7 +303,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.profile = pr.clone();
|
||||
}
|
||||
};
|
||||
edit_items(s, &ids, item, C, "Stroke", false, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects counted: with a design's art, those with a row equal to the art's.
|
||||
let ids = edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -372,7 +374,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
|
||||
}
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
|
||||
edit_items(s, &ids, item, c, label, false, |n, index| {
|
||||
edit_items(s, &ids, item, None, c, label, false, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -535,7 +537,8 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
arrows_and_profile(st);
|
||||
}
|
||||
edit_items(s, &ids, item, C, "Stroke", false, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| {
|
||||
let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) };
|
||||
arrows_and_profile(st);
|
||||
if let Some(b) = &brush {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2008,6 +2008,38 @@ fn glyph_form_is_one_character_attribute_saved_only_when_set() {
|
||||
assert!(runs(&s).iter().all(|r| r.style.glyph_form == GlyphForm::Default));
|
||||
}
|
||||
|
||||
/// A glyph choice (`text.setGlyphAlternate`) would keep drawing its own glyph over a glyph form,
|
||||
/// so setting a form other than "default" takes it away, in `text.setRangeStyle` and in
|
||||
/// `text.setFormat`; "default" (Revert To Default Forms) and calls without `glyphForm` keep it.
|
||||
#[test]
|
||||
fn a_glyph_form_takes_away_the_characters_glyph_choice() {
|
||||
use vectorcraft_doc::{GlyphChoice, GlyphForm};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "亜唖"})).unwrap()["id"].as_u64().unwrap();
|
||||
let choice = GlyphChoice { ch: '唖', gid: 42, font: "Test-Regular".into(), version: "1".into() };
|
||||
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(NodeId(id)).map(|n| &mut n.kind) {
|
||||
vectorcraft_text::edit::style_range(&mut t.runs, 3, 6, |st| st.glyph_alternate = Some(choice.clone()));
|
||||
}
|
||||
let state = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form, r.style.glyph_alternate.is_some())).collect::<Vec<_>>(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "size": 30})).unwrap();
|
||||
assert_eq!(state(&s), [("亜".into(), GlyphForm::Default, false), ("唖".into(), GlyphForm::Default, true)], "no glyphForm: kept");
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "glyphForm": "default"})).unwrap();
|
||||
assert_eq!(state(&s)[1], ("唖".into(), GlyphForm::Default, true), "default: kept");
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "glyphForm": "jis78"})).unwrap();
|
||||
assert_eq!(state(&s), [("亜".into(), GlyphForm::Default, false), ("唖".into(), GlyphForm::Jis78, false)]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(state(&s)[1], ("唖".into(), GlyphForm::Default, true), "one undo step brings both back");
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"glyphForm": "default"})).unwrap();
|
||||
assert!(state(&s).iter().any(|r| r.2), "default: kept");
|
||||
s.execute("text.setFormat", &json!({"glyphForm": "traditional"})).unwrap();
|
||||
assert!(state(&s).iter().all(|r| r.1 == GlyphForm::Traditional && !r.2), "{:?}", state(&s));
|
||||
}
|
||||
|
||||
/// No Break is a character attribute, saved only when on.
|
||||
#[test]
|
||||
fn no_break_is_a_character_attribute_saved_only_when_on() {
|
||||
|
||||
@@ -399,6 +399,12 @@ impl ScriptScope {
|
||||
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() }
|
||||
}
|
||||
|
||||
/// The scope of a script run from a file in the folder whose real path, with its links already
|
||||
/// followed, is `real`: that folder, which is not looked up again.
|
||||
pub(crate) fn of_real_folder(real: PathBuf) -> Self {
|
||||
Self { roots: vec![real] }
|
||||
}
|
||||
|
||||
/// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or
|
||||
/// stream, or a computer on the network?
|
||||
fn refused_by_name(path: &Path) -> bool {
|
||||
|
||||
@@ -344,6 +344,9 @@ pub struct Session {
|
||||
/// The Global Edit Options Start Global Edit matches with (`select.globalEditOptions`); not
|
||||
/// saved.
|
||||
pub global_edit_options: cmd::globaledit::Options,
|
||||
/// The attribute Select Similar Objects selects by (`select.similar`), one of
|
||||
/// [`cmd::SIMILAR`]; not saved.
|
||||
pub select_similar: &'static str,
|
||||
/// Set while [`Session::tool_typed_text`] passes keyboard input to the active tool
|
||||
/// ([`vectorcraft_tools::ToolContext::typed_from_keyboard`]).
|
||||
keyboard_text: bool,
|
||||
|
||||
@@ -295,12 +295,14 @@ fn display(path: &Path) -> Arc<str> {
|
||||
|
||||
impl Files {
|
||||
/// The files of a run of the script at `path` (`None` for a script given as text), with the
|
||||
/// `JSINCLUDE` folders `jsinclude`.
|
||||
pub(crate) fn new(path: Option<&str>, jsinclude: Vec<PathBuf>) -> Self {
|
||||
let real = path.and_then(|p| std::fs::canonicalize(p).ok());
|
||||
/// `JSINCLUDE` folders `jsinclude`. `checked` is the script's real path when the read of its text
|
||||
/// found it, which the run's folder then comes from; without it, `path` is looked up.
|
||||
pub(crate) fn new(path: Option<&str>, checked: Option<PathBuf>, jsinclude: Vec<PathBuf>) -> Self {
|
||||
let scope_of_checked = checked.as_deref().and_then(Path::parent).map(|d| ScriptScope::of_real_folder(d.to_path_buf()));
|
||||
let real = checked.or_else(|| path.and_then(|p| std::fs::canonicalize(p).ok()));
|
||||
let dir = real.as_deref().and_then(folder_of);
|
||||
Self {
|
||||
scope: dir.as_deref().map(ScriptScope::of_folder).unwrap_or_default(),
|
||||
scope: scope_of_checked.or_else(|| dir.as_deref().map(ScriptScope::of_folder)).unwrap_or_default(),
|
||||
jsinclude,
|
||||
include_path: Vec::new(),
|
||||
files: 0,
|
||||
|
||||
@@ -163,6 +163,9 @@ pub(crate) struct Request {
|
||||
pub name_given: bool,
|
||||
/// The file the script was read from, which its included files are read beside.
|
||||
pub file: Option<String>,
|
||||
/// The real path of `file` as the read of `source` found it, which the included files are then
|
||||
/// read beside instead of looking `file` up again.
|
||||
pub checked_real: Option<std::path::PathBuf>,
|
||||
pub source: String,
|
||||
pub args: Map<String, Value>,
|
||||
pub fuel: u64,
|
||||
@@ -429,7 +432,7 @@ struct World {
|
||||
}
|
||||
|
||||
/// The choices outside the documents that a script's commands can change: the preferences, the
|
||||
/// global edit options, the recent URLs, the chosen gradient stop, freeform point and appearance
|
||||
/// global edit options, the Select Similar Objects attribute, the recent URLs, the chosen gradient stop, freeform point and appearance
|
||||
/// item, the Eyedropper's sample, the envelope defaults and the Caps Lock state.
|
||||
#[derive(Clone)]
|
||||
struct Choices {
|
||||
@@ -437,6 +440,7 @@ struct Choices {
|
||||
caps_lock: bool,
|
||||
eyedropper_sample: Option<Arc<vectorcraft_doc::Node>>,
|
||||
global_edit_options: cmd::globaledit::Options,
|
||||
select_similar: &'static str,
|
||||
recent_urls: Vec<String>,
|
||||
gradient_stop: Option<(usize, cmd::gradient::StopOwner)>,
|
||||
freeform_point: Option<(usize, cmd::gradient::StopOwner)>,
|
||||
@@ -451,6 +455,7 @@ impl Choices {
|
||||
caps_lock: s.caps_lock,
|
||||
eyedropper_sample: s.eyedropper_sample.clone(),
|
||||
global_edit_options: s.global_edit_options.clone(),
|
||||
select_similar: s.select_similar,
|
||||
recent_urls: s.recent_urls.clone(),
|
||||
gradient_stop: s.gradient_stop,
|
||||
freeform_point: s.freeform_point,
|
||||
@@ -464,6 +469,7 @@ impl Choices {
|
||||
s.caps_lock = self.caps_lock;
|
||||
s.eyedropper_sample = self.eyedropper_sample;
|
||||
s.global_edit_options = self.global_edit_options;
|
||||
s.select_similar = self.select_similar;
|
||||
s.recent_urls = self.recent_urls;
|
||||
s.gradient_stop = self.gradient_stop;
|
||||
s.freeform_point = self.freeform_point;
|
||||
@@ -477,6 +483,7 @@ impl Choices {
|
||||
swap(&mut self.caps_lock, &mut s.caps_lock);
|
||||
swap(&mut self.eyedropper_sample, &mut s.eyedropper_sample);
|
||||
swap(&mut self.global_edit_options, &mut s.global_edit_options);
|
||||
swap(&mut self.select_similar, &mut s.select_similar);
|
||||
swap(&mut self.recent_urls, &mut s.recent_urls);
|
||||
swap(&mut self.gradient_stop, &mut s.gradient_stop);
|
||||
swap(&mut self.freeform_point, &mut s.freeform_point);
|
||||
@@ -1814,7 +1821,7 @@ impl Session {
|
||||
self.script_high_water.retain(|uid, _| open.contains(uid));
|
||||
self.script_stop.clear();
|
||||
self.script_report = None;
|
||||
let mut files = include::Files::new(request.file.as_deref(), include::Files::jsinclude_env());
|
||||
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
|
||||
let expanded = files.expand_script(&request.source);
|
||||
let name = match &expanded {
|
||||
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
|
||||
|
||||
@@ -141,6 +141,7 @@ impl Session {
|
||||
link_stamps: Default::default(),
|
||||
link_scan: None,
|
||||
global_edit_options: Default::default(),
|
||||
select_similar: crate::cmd::SIMILAR[0].0,
|
||||
keyboard_text: false,
|
||||
script_key: None,
|
||||
script_engines: crate::script::EnginesKey::new(),
|
||||
|
||||
@@ -612,6 +612,100 @@ fn eraser_size_follows_the_pen_pressure() {
|
||||
assert!(err.to_string().contains("sizeMode"), "{err}");
|
||||
}
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Rotation, Bearing,
|
||||
/// Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a
|
||||
/// drag without the reading erases at the value itself, an open path is cut where the varied tip
|
||||
/// covers it, and an unknown mode or a variation out of its range is refused with nothing erased.
|
||||
#[test]
|
||||
fn the_eraser_tip_varies_with_its_modes() {
|
||||
// Which of `probes` a level drag through the middle of a 400 by 200 rectangle erases, each of
|
||||
// its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation]).
|
||||
let erased = |tip: serde_json::Value, pen: serde_json::Value, probes: &[(f64, f64)]| -> Vec<bool> {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 400.0, 200.0);
|
||||
let points: Vec<_> = (0..=20)
|
||||
.map(|i| {
|
||||
let mut p = vec![json!(100.0 + f64::from(i) * 10.0), json!(100.0)];
|
||||
p.extend(pen.as_array().cloned().unwrap_or_default());
|
||||
serde_json::Value::Array(p)
|
||||
})
|
||||
.collect();
|
||||
s.execute("path.eraseRegion", &with(&json!({"points": points, "size": 20}), tip.clone())).unwrap();
|
||||
let filled = |x: f64, y: f64| {
|
||||
paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)))
|
||||
};
|
||||
assert!(filled(200.0, 150.0), "{tip} {pen}: the rest of the rectangle stays");
|
||||
probes.iter().map(|&(x, y)| !filled(x, y)).collect()
|
||||
};
|
||||
let none = json!(null);
|
||||
// A 20 by 2 pt tip lying level erases a band 2 pt tall; standing upright it erases one 20 pt tall.
|
||||
let level = json!({"roundness": 10});
|
||||
let probes = [(200.0, 100.5), (200.0, 108.0)];
|
||||
assert_eq!(erased(level.clone(), json!([]), &probes), [true, false], "Fixed");
|
||||
let on_rotation = with(&level, json!({"angleMode": "rotation", "angleVariation": 90}));
|
||||
// The barrel turned half way round reads the most, which turns the tip upright.
|
||||
assert_eq!(erased(on_rotation.clone(), json!([none, none, none, 180]), &probes), [true, true], "Rotation");
|
||||
assert_eq!(erased(on_rotation.clone(), json!([]), &probes), [true, false], "Rotation without a reading");
|
||||
// Leaning to the left (a bearing of 180°) reads the most too.
|
||||
let on_bearing = with(&level, json!({"angleMode": "bearing", "angleVariation": 90}));
|
||||
assert_eq!(erased(on_bearing.clone(), json!([none, -45, 0, none]), &probes), [true, true], "Bearing");
|
||||
assert_eq!(erased(on_bearing, json!([none, 45, 0, none]), &probes), [true, false], "Bearing at 0°");
|
||||
// A round tip: upright the pen gives 28 pt, nearly flat about 12 pt.
|
||||
let on_tilt = json!({"sizeMode": "tilt", "sizeVariation": 8});
|
||||
let wide = [(200.0, 105.0), (200.0, 113.0)];
|
||||
assert_eq!(erased(on_tilt.clone(), json!([none, 0, 0, none]), &wide), [true, true], "Tilt upright");
|
||||
assert_eq!(erased(on_tilt, json!([none, 89, 0, none]), &wide), [true, false], "Tilt flat");
|
||||
// Roundness from 10 % less 90 (kept to 1 %) at the lightest pressure to 100 % at the heaviest.
|
||||
let on_pressure = with(&level, json!({"roundnessMode": "pressure", "roundnessVariation": 90}));
|
||||
assert_eq!(erased(on_pressure.clone(), json!([1.0]), &probes), [true, true], "Pressure at the heaviest");
|
||||
// At the lightest the tip is 0.2 pt across, narrower than the 2 pt band Fixed erases.
|
||||
assert_eq!(erased(on_pressure, json!([0.0]), &[(200.0, 100.0), (200.0, 100.5)]), [true, false], "Pressure at the lightest");
|
||||
// Random: one size for the drag, from 16 to 24 pt.
|
||||
let random = json!({"sizeMode": "random", "sizeVariation": 4});
|
||||
assert_eq!(erased(random, json!([]), &[(200.0, 107.5), (200.0, 112.5)]), [true, false], "Random");
|
||||
// A press on a line with the tip turned upright by its rotation cuts 5 pt of it, not 20.
|
||||
let left_of_line = |pen: serde_json::Value| {
|
||||
let mut s = session();
|
||||
line(&mut s, 300.0, 150.0, 500.0, 150.0);
|
||||
let mut point = vec![json!(400), json!(150)];
|
||||
point.extend(pen.as_array().cloned().unwrap_or_default());
|
||||
let tip = json!({"points": [point], "size": 20, "roundness": 25, "angleMode": "rotation", "angleVariation": 90});
|
||||
s.execute("path.eraseRegion", &tip).unwrap();
|
||||
paths(&s).iter().map(|p| p.1.length()).sum::<f64>()
|
||||
};
|
||||
let upright = left_of_line(json!([none, none, none, 180]));
|
||||
assert!((upright - 195.0).abs() < 0.3, "the upright tip left {upright} pt of the line");
|
||||
let level_tip = left_of_line(json!([]));
|
||||
assert!((level_tip - 180.0).abs() < 0.3, "the level tip left {level_tip} pt of the line");
|
||||
// A 1500 pt tip on Tilt erases 1500 pt across with a mouse, as it does on Fixed.
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 4000.0, 4000.0);
|
||||
let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1500, "sizeMode": "tilt", "sizeVariation": 10});
|
||||
s.execute("path.eraseRegion", &big).unwrap();
|
||||
let filled =
|
||||
|x: f64, y: f64| paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y)));
|
||||
assert_eq!((filled(2000.0, 2740.0), filled(2000.0, 2760.0)), (false, true), "a 1500 pt tip");
|
||||
// A Size Variation kept while Size is Fixed leaves the size alone.
|
||||
let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000000}));
|
||||
assert_eq!(erased(kept, json!([]), &probes), [true, false], "Size on Fixed with a Variation");
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let stroke = json!({"points": [[-10, 50], [110, 50]]});
|
||||
let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
|
||||
for (extra, want) in [
|
||||
(json!({"angleMode": "wheel"}), format!("angleMode is one of {modes}, not `wheel`")),
|
||||
(json!({"roundnessMode": 3}), format!("roundnessMode is one of {modes}, not 3")),
|
||||
(json!({"sizeMode": "stylusWheel"}), format!("sizeMode is one of {modes}, not `stylusWheel`")),
|
||||
(json!({"angleVariation": 181}), "angleVariation must be at most 180".to_string()),
|
||||
(json!({"roundnessVariation": 101}), "roundnessVariation must be at most 100".to_string()),
|
||||
(json!({"roundnessVariation": -1}), "roundnessVariation must be 0 or more".to_string()),
|
||||
] {
|
||||
refuses_with(&mut s, "path.eraseRegion", &with(&stroke, extra), &want);
|
||||
}
|
||||
refuses_a_number_given_as_text(&mut s, "path.eraseRegion", &stroke, "angleVariation");
|
||||
}
|
||||
|
||||
/// A Blob Brush stroke merges with the topmost matching path it touches and with the touched
|
||||
/// matching paths next to it in stacking order in the same group or layer; matching paths in other
|
||||
/// layers or groups, or below an object of another kind, are left alone.
|
||||
|
||||
@@ -1791,3 +1791,350 @@ fn a_recovered_copy_of_an_imported_file_keeps_its_links_folder() {
|
||||
let mut saved: Value = serde_json::from_slice(&std::fs::read(&native).unwrap()).unwrap();
|
||||
assert_eq!(saved_image(&mut saved)["link"]["relative"].as_str(), Some("src/photo.png"));
|
||||
}
|
||||
|
||||
/// Image `id` of the active document without pixels in the document, as a linked file that could
|
||||
/// not be read leaves it.
|
||||
fn without_pixels(s: &mut Session, id: NodeId) {
|
||||
let key = image(s, id).key;
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.remove(&key);
|
||||
}
|
||||
|
||||
/// The text of `document.serialize`'s reply `r` (an SVG, or the SVGZ it holds).
|
||||
fn svg_text(r: &Value) -> String {
|
||||
match r["text"].as_str() {
|
||||
Some(text) => text.to_string(),
|
||||
None => {
|
||||
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
vectorcraft_svg::text_of(&bytes).unwrap().into_owned()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A caller confined to read roots: every SVG and SVGZ output that would name a linked image's file
|
||||
/// outside them (Images: Link, Preserve Editing Capabilities, or Embed for an image without pixels
|
||||
/// in the document) is refused before a file or folder is written, with an error that names no
|
||||
/// file or folder, and the document keeps the link. Embed with the pixels names no file.
|
||||
#[test]
|
||||
fn confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-image-away");
|
||||
let home = Folder::new("svg-image-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("assets.add", &json!({"ids": [a.0]})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "photo.png".to_string()];
|
||||
let refused = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
|
||||
}
|
||||
};
|
||||
let out = home.file("out");
|
||||
// Every SVG output, with the options `o` given flat.
|
||||
let every = |s: &mut Session, o: &Value| {
|
||||
for format in ["svg", "svgz"] {
|
||||
let file = |name: &str| home.file(&format!("{name}.{format}"));
|
||||
let with = |p: Value| {
|
||||
let mut p = p;
|
||||
if let (Some(m), Some(o)) = (p.as_object_mut(), o.as_object()) {
|
||||
m.extend(o.clone());
|
||||
}
|
||||
p
|
||||
};
|
||||
refused(s, "document.serialize", with(json!({"format": format})));
|
||||
refused(s, "document.export", with(json!({"format": format})));
|
||||
refused(s, "document.export", with(json!({"format": format, "path": file("export")})));
|
||||
refused(s, "document.export", with(json!({"format": format, "selectedOnly": true})));
|
||||
refused(s, "document.exportSelection", with(json!({"format": format, "path": file("selection")})));
|
||||
refused(s, "document.save", with(json!({"path": file("save")})));
|
||||
refused(s, "file.saveAs", with(json!({"format": format, "path": file("save-as")})));
|
||||
refused(s, "file.saveCopy", with(json!({"format": format, "path": file("copy")})));
|
||||
let row = with(json!({"format": format}));
|
||||
refused(s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, row]}));
|
||||
refused(s, "document.exportForScreens", json!({"zip": true, "formats": [row]}));
|
||||
refused(s, "assets.export", json!({"folder": out, "formats": [row]}));
|
||||
}
|
||||
};
|
||||
every(&mut s, &json!({"images": "link"}));
|
||||
every(&mut s, &json!({"preserveEditing": true}));
|
||||
refused(&mut s, "document.serialize", json!({"format": "svg", "svg": {"images": "link"}}));
|
||||
// Embedded pixels name no file.
|
||||
for format in ["svg", "svgz"] {
|
||||
let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": format}))).unwrap();
|
||||
let text = svg_text(&r);
|
||||
assert!(text.contains("data:image/png;base64,") && !text.contains(&hidden[0]), "{format}: {text}");
|
||||
}
|
||||
// Without its pixels, an embedded image names its file.
|
||||
without_pixels(&mut s, a);
|
||||
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
assert!(svg_text(&r).contains(&format!("xlink:href=\"{photo}\"")), "{r}");
|
||||
every(&mut s, &json!({}));
|
||||
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert!(written.is_empty(), "{written:?}");
|
||||
assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG leaves out hidden layers and objects, unless hidden layers are kept (as
|
||||
/// a save keeps them by default), and template layers always: a linked image file outside the read
|
||||
/// roots in art the file leaves out does not refuse it, and in art the file writes does.
|
||||
#[test]
|
||||
fn confined_svg_output_checks_only_the_linked_images_it_writes() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-image-unwritten-away");
|
||||
let home = Folder::new("svg-image-unwritten-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
// A visible rectangle, and the linked image in a layer of its own.
|
||||
let setup = || {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let layer = NodeId(s.execute("layer.new", &json!({"top": true})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.setCurrent", &json!({"id": layer.0})).unwrap();
|
||||
let a = place(&mut s, &photo);
|
||||
assert!(s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == a), "the image is in the new layer");
|
||||
(s, layer, a)
|
||||
};
|
||||
let written = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
|
||||
if cmd == "document.serialize" {
|
||||
let text = svg_text(&r);
|
||||
assert!(!text.contains(&photo) && !text.contains("photo.png"), "{cmd} {p}: {text}");
|
||||
}
|
||||
};
|
||||
let refused = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}");
|
||||
};
|
||||
// Exports leave hidden art out; hidden layers kept, and a save, write it.
|
||||
let hidden_art = |s: &mut Session, name: &str| {
|
||||
for format in ["svg", "svgz"] {
|
||||
written(s, "document.serialize", json!({"format": format, "images": "link"}));
|
||||
written(s, "document.export", json!({"format": format, "images": "link", "path": home.file(&format!("{name}.{format}"))}));
|
||||
written(s, "document.export", json!({"format": format, "images": "link", "svg": {"hiddenLayers": false}}));
|
||||
refused(s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
|
||||
refused(s, "document.export", json!({"format": format, "svg": {"images": "link", "hiddenLayers": true}}));
|
||||
refused(s, "document.save", json!({"path": home.file(&format!("{name}-save.{format}")), "images": "link"}));
|
||||
refused(s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("{name}-copy.{format}")), "images": "link"}));
|
||||
}
|
||||
// A save told to leave hidden layers out leaves the image out too.
|
||||
let copy = home.file(&format!("{name}-copy.svg"));
|
||||
written(s, "file.saveCopy", json!({"format": "svg", "path": copy, "images": "link", "hiddenLayers": false}));
|
||||
};
|
||||
let (mut s, layer, _) = setup();
|
||||
s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap();
|
||||
hidden_art(&mut s, "hidden-layer");
|
||||
let (mut s, _, a) = setup();
|
||||
s.execute("object.hide", &json!({"ids": [a.0]})).unwrap();
|
||||
hidden_art(&mut s, "hidden-object");
|
||||
// A template layer is never written, not even with hidden layers kept.
|
||||
let (mut s, layer, _) = setup();
|
||||
s.execute("layer.setProps", &json!({"ids": [layer.0], "template": true})).unwrap();
|
||||
for format in ["svg", "svgz"] {
|
||||
written(&mut s, "document.serialize", json!({"format": format, "images": "link"}));
|
||||
written(&mut s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
|
||||
written(&mut s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("template-copy.{format}")), "images": "link"}));
|
||||
}
|
||||
// Back to an ordinary layer, the image is written and refuses the file.
|
||||
s.execute("layer.setProps", &json!({"ids": [layer.0], "template": false})).unwrap();
|
||||
refused(&mut s, "document.serialize", json!({"format": "svg", "images": "link"}));
|
||||
// The layer of symbol editing mode is never written: editing a symbol no art uses leaves its
|
||||
// image out of the file.
|
||||
let (mut s, _, a) = setup();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Away"})).unwrap()["id"].clone();
|
||||
s.execute("edit.clear", &json!({"ids": [instance]})).unwrap();
|
||||
s.execute("symbol.edit", &json!({"name": "Away"})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.symbol_edit.is_some(), "in symbol editing mode");
|
||||
for format in ["svg", "svgz"] {
|
||||
written(&mut s, "document.serialize", json!({"format": format, "images": "link", "hiddenLayers": true}));
|
||||
written(&mut s, "file.saveCopy", json!({"format": format, "path": home.file(&format!("symbol-edit-copy.{format}")), "images": "link"}));
|
||||
}
|
||||
s.execute("symbol.exitEditing", &json!({})).unwrap();
|
||||
s.execute("symbol.place", &json!({"name": "Away"})).unwrap();
|
||||
refused(&mut s, "document.serialize", json!({"format": "svg", "images": "link"}));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG of a grayscale linked image outside the read roots that a solid fill
|
||||
/// colorizes: the file gets the colorized pixels, or leaves the image out without pixels, and names
|
||||
/// no file with Link or Embed. With Preserve Editing Capabilities the document the SVG carries
|
||||
/// keeps the link, and the SVG is refused.
|
||||
#[test]
|
||||
fn confined_svg_output_writes_a_colorized_gray_image_without_its_file() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-image-colorized-away");
|
||||
let home = Folder::new("svg-image-colorized-home");
|
||||
let photo = away.file("gray.png");
|
||||
let mut bytes = vec![];
|
||||
image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
write(&photo, &bytes);
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
|
||||
let colorized = s.doc().unwrap().doc.node(a).unwrap().extras().colorize.clone();
|
||||
assert!(matches!(colorized.as_deref(), Some(vectorcraft_color::Paint::Solid { .. })), "{colorized:?}");
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let written = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
|
||||
if cmd == "document.serialize" {
|
||||
let text = svg_text(&r);
|
||||
assert!(!text.contains(&away.0.to_string_lossy().into_owned()) && !text.contains("href=\"gray.png"), "{cmd} {p}: {text}");
|
||||
}
|
||||
};
|
||||
let refused = |s: &mut Session, p: Value| {
|
||||
let e = confine(roots.as_ref(), || s.execute("document.serialize", &p)).expect_err("preserveEditing").to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{p}: {e}");
|
||||
};
|
||||
let every = |s: &mut Session, name: &str| {
|
||||
for format in ["svg", "svgz"] {
|
||||
for images in ["link", "embed"] {
|
||||
written(s, "document.serialize", json!({"format": format, "images": images}));
|
||||
written(s, "document.export", json!({"format": format, "images": images, "path": home.file(&format!("{name}-{images}.{format}"))}));
|
||||
let copy = home.file(&format!("{name}-{images}-copy.{format}"));
|
||||
written(s, "file.saveCopy", json!({"format": format, "images": images, "path": copy}));
|
||||
}
|
||||
refused(s, json!({"format": format, "preserveEditing": true}));
|
||||
}
|
||||
};
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap());
|
||||
assert!(text.contains("data:image/png;base64,"), "{text}");
|
||||
every(&mut s, "pixels");
|
||||
without_pixels(&mut s, a);
|
||||
every(&mut s, "missing");
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let svg = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap()["svg"].as_str().unwrap().to_string();
|
||||
assert!(!svg.contains(&photo), "{svg}");
|
||||
assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG names each linked image file it may read, as stored: a file inside the
|
||||
/// read roots, a path relative to the document's folder that leads inside them, and a URL. The
|
||||
/// selected objects alone are exported when the image outside them is not selected, and a caller
|
||||
/// without roots gets a file outside them named too.
|
||||
#[test]
|
||||
fn svg_output_names_linked_image_files_a_caller_may_read() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-image-kept-away");
|
||||
let home = Folder::new("svg-image-kept-home");
|
||||
let inside = home.file("photo.png");
|
||||
let (nested, web) = (home.file("lib/photo.png"), home.file("web.png"));
|
||||
for f in [&inside, &nested, &web] {
|
||||
write(f, &png(60, 30, RED));
|
||||
}
|
||||
let url = "https://example.com/images/photo.png";
|
||||
let mut s = session();
|
||||
place(&mut s, &inside);
|
||||
place(&mut s, &nested);
|
||||
place(&mut s, &web);
|
||||
save(&mut s, &home.file("doc.vectorcraft"));
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.update_links_where(|l| l.path == nested, |l| l.path = "lib/photo.png".into());
|
||||
doc.update_links_where(|l| l.path == web, |l| l.path = url.into());
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let link = json!({"format": "svg", "images": "link"});
|
||||
for format in ["svg", "svgz"] {
|
||||
let p = json!({"format": format, "images": "link"});
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
|
||||
for file in [inside.as_str(), "lib/photo.png", url] {
|
||||
assert!(text.contains(&format!("xlink:href=\"{file}\"")), "{format} {file}: {text}");
|
||||
}
|
||||
}
|
||||
// An image outside them in a symbol no art uses is not written.
|
||||
let unused = away.file("unused.png");
|
||||
write(&unused, &png(60, 30, BLUE));
|
||||
let u = place(&mut s, &unused);
|
||||
s.execute("select.set", &json!({"ids": [u.0]})).unwrap();
|
||||
let instance = s.execute("symbol.new", &json!({"name": "Away"})).unwrap()["id"].clone();
|
||||
s.execute("edit.clear", &json!({"ids": [instance]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.symbols.len(), 1);
|
||||
for format in ["svg", "svgz"] {
|
||||
let p = json!({"format": format, "images": "link"});
|
||||
let text = svg_text(&confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap());
|
||||
assert!(!text.contains(&unused), "{format}: {text}");
|
||||
}
|
||||
let outside = away.file("photo.png");
|
||||
write(&outside, &png(60, 30, BLUE));
|
||||
place(&mut s, &outside);
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r["id"].clone()]})).unwrap();
|
||||
let p = json!({"format": "svg", "images": "link"});
|
||||
let r = confine(roots.as_ref(), || s.execute("document.exportSelection", &p)).unwrap();
|
||||
assert!(!r.to_string().contains(&outside), "{r}");
|
||||
let p = json!({"format": "svg", "images": "link", "selectedOnly": true});
|
||||
for cmd in ["document.serialize", "document.export"] {
|
||||
let r = confine(roots.as_ref(), || s.execute(cmd, &p)).unwrap();
|
||||
assert!(!r.to_string().contains(&outside), "{cmd}: {r}");
|
||||
}
|
||||
// The file of an artboard the image is not over.
|
||||
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap();
|
||||
let p = json!({"format": "svg", "images": "link", "range": "2"});
|
||||
let r = confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap();
|
||||
assert!(!r.to_string().contains(&outside), "{r}");
|
||||
let p = json!({"folder": home.file("screens"), "formats": [{"format": "svg", "images": "link"}], "range": "2"});
|
||||
confine(roots.as_ref(), || s.execute("document.exportForScreens", &p)).unwrap();
|
||||
// Without roots, a file outside them is named as stored.
|
||||
let text = svg_text(&s.execute("document.serialize", &link).unwrap());
|
||||
assert!(text.contains(&format!("xlink:href=\"{outside}\"")), "{text}");
|
||||
}
|
||||
|
||||
/// The clipboard's SVG for a confined caller: embedded pixels name no file; an image whose pixels
|
||||
/// the clipboard doesn't hold makes `clipboard.exportSvg` refuse with an error that names no file
|
||||
/// or folder, and the system clipboard gets no SVG. A caller without roots gets the file named.
|
||||
#[test]
|
||||
fn confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("clip-image-away");
|
||||
let home = Folder::new("clip-image-home");
|
||||
let photo = away.file("photo.png");
|
||||
write(&photo, &png(60, 30, RED));
|
||||
let mut s = session();
|
||||
let a = place(&mut s, &photo);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let r = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap();
|
||||
let svg = r["svg"].as_str().unwrap();
|
||||
assert!(svg.contains("data:image/png;base64,") && !svg.contains(&photo), "{svg}");
|
||||
|
||||
without_pixels(&mut s, a);
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let e = confine(roots.as_ref(), || s.execute("clipboard.exportSvg", &json!({}))).unwrap_err().to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{e}");
|
||||
assert!(!e.contains(&away.0.to_string_lossy().into_owned()) && !e.contains("photo.png"), "{e}");
|
||||
assert!(confine(roots.as_ref(), || s.clipboard_svg()).is_none());
|
||||
let svg = s.execute("clipboard.exportSvg", &json!({})).unwrap()["svg"].as_str().unwrap().to_string();
|
||||
assert!(svg.contains(&format!("xlink:href=\"{photo}\"")), "{svg}");
|
||||
}
|
||||
|
||||
/// A confined caller's SVG with Preserve Editing Capabilities is refused while the stored brush
|
||||
/// library holds an entry that does not read as a brush, or is not a list: the native document
|
||||
/// carries it as it is, and its links cannot be checked. Without Preserve Editing the SVG is written.
|
||||
#[test]
|
||||
fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let home = Folder::new("svg-brush-entry-home");
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
let preserve = json!({"format": "svg", "preserveEditing": true});
|
||||
confine(roots.as_ref(), || s.execute("document.serialize", &preserve)).unwrap();
|
||||
for stored in [json!(["not a brush"]), json!({"link": "/away/photo.png"})] {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.unknown.insert(vectorcraft_brush::DOC_KEY.into(), stored.clone());
|
||||
let e = confine(roots.as_ref(), || s.execute("document.serialize", &preserve)).unwrap_err().to_string();
|
||||
assert!(e.contains("a linked image file is outside the read roots"), "{stored}: {e}");
|
||||
confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2789,6 +2789,73 @@ fn select_same_fill_keeps_live_paint_faces_to_their_group() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Select Similar Objects (`select.similar`) runs the Select > Same command of the attribute it is
|
||||
/// given and keeps that attribute for its next run without one; `all`, the attribute until one is
|
||||
/// given, matches the fill and stroke colours, the stroke weight, the opacity and the blending mode
|
||||
/// together. An unknown attribute is an error that keeps the selection and the kept attribute.
|
||||
#[test]
|
||||
fn select_similar_selects_by_the_kept_attribute() {
|
||||
let mut s = session();
|
||||
let [a, b, faded, heavy, multiplied, blue] = [0.0, 20.0, 40.0, 60.0, 80.0, 100.0].map(|x| rect(&mut s, x, 0.0, 10.0, 10.0));
|
||||
for id in [a, b, faded, heavy, multiplied] {
|
||||
fill(&mut s, id, "#ff0000");
|
||||
}
|
||||
fill(&mut s, blue, "#0000ff");
|
||||
s.execute("transparency.set", &json!({"ids": [faded.0], "opacity": 50, "item": null})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [multiplied.0], "blend": "multiply", "item": null})).unwrap();
|
||||
sel(&mut s, &[heavy]);
|
||||
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
|
||||
let similar = |s: &mut Session, p: Value| {
|
||||
sel(s, &[a]);
|
||||
let r = s.execute("select.similar", &p).unwrap();
|
||||
let mut v = selected(s);
|
||||
v.sort();
|
||||
assert_eq!(r["count"], v.len(), "{p}");
|
||||
(r["by"].as_str().unwrap().to_string(), v)
|
||||
};
|
||||
assert_eq!(s.select_similar, "all");
|
||||
assert_eq!(similar(&mut s, json!({})), ("all".into(), vec![a, b]));
|
||||
assert_eq!(similar(&mut s, json!({"by": "fillColor"})), ("fillColor".into(), vec![a, b, faded, heavy, multiplied]));
|
||||
assert_eq!(similar(&mut s, json!({})), ("fillColor".into(), vec![a, b, faded, heavy, multiplied]));
|
||||
// The journal, and an action recorded around it, keep the attribute used.
|
||||
let last = s.journal.last().unwrap();
|
||||
assert_eq!((last.0.as_str(), &last.1), ("select.similar", &json!({"by": "fillColor"})));
|
||||
assert_eq!(similar(&mut s, json!({"by": "opacity"})), ("opacity".into(), vec![a, b, heavy, multiplied, blue]));
|
||||
assert_eq!(similar(&mut s, json!({"by": "blendingMode"})), ("blendingMode".into(), vec![a, b, faded, heavy, blue]));
|
||||
assert_eq!(similar(&mut s, json!({"by": "strokeWeight"})), ("strokeWeight".into(), vec![a, b, faded, multiplied, blue]));
|
||||
assert_eq!(similar(&mut s, json!({"by": "all"})).1, vec![a, b]);
|
||||
// Select > Reselect repeats `all`, whichever attribute is kept by then.
|
||||
s.select_similar = "fillColor";
|
||||
s.execute("select.reselect", &json!({})).unwrap();
|
||||
assert_eq!(selected(&s), vec![a, b]);
|
||||
// Every attribute names a command that runs. A path with no graphic style has none to match,
|
||||
// which is an error that keeps the attribute as it was.
|
||||
for (by, _) in crate::cmd::SIMILAR {
|
||||
sel(&mut s, &[a]);
|
||||
let was = s.select_similar;
|
||||
let r = s.execute("select.similar", &json!({ "by": by }));
|
||||
if by == "graphicStyle" {
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
assert_eq!(s.select_similar, was);
|
||||
} else {
|
||||
r.unwrap_or_else(|e| panic!("{by}: {e:?}"));
|
||||
assert_eq!(s.select_similar, by);
|
||||
}
|
||||
}
|
||||
// An unknown or malformed attribute changes nothing.
|
||||
s.select_similar = "opacity";
|
||||
for bad in [json!("color"), json!(""), json!("FillColor"), json!(3), json!(true), json!(["all"])] {
|
||||
sel(&mut s, &[a]);
|
||||
let r = s.execute("select.similar", &json!({ "by": bad }));
|
||||
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}");
|
||||
assert_eq!((selected(&s), s.select_similar), (vec![a], "opacity"), "{bad}");
|
||||
}
|
||||
// With nothing selected it does not run, and keeps the attribute.
|
||||
sel(&mut s, &[]);
|
||||
assert!(s.execute("select.similar", &json!({"by": "fillColor"})).is_err());
|
||||
assert_eq!(s.select_similar, "opacity");
|
||||
}
|
||||
|
||||
/// Select by Color needs no object to start from: it matches fills and strokes as
|
||||
/// `document.inspect` reports them, `#rrggbb`.
|
||||
#[test]
|
||||
|
||||
@@ -492,6 +492,111 @@ fn options_set_tile_type_spacing_and_overlap() {
|
||||
assert!(s.execute("pattern.options", &json!({"name": "Dots", "width": -1})).is_err());
|
||||
}
|
||||
|
||||
/// Move Tile with Art: in pattern editing mode, a move of all of the tile art moves the tile by the
|
||||
/// same offset, through `object.move`, `object.nudge` and `object.transform`. With the option off
|
||||
/// (a new pattern's default), a move of part of the art, a rotation or a copy, the tile stays.
|
||||
/// Undo puts the tile back, and Done keeps the moved tile.
|
||||
#[test]
|
||||
fn move_tile_with_art_moves_the_tile_when_all_of_the_art_moves() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 12.0, 0.0, 6.0, 6.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
|
||||
let tile = |s: &Session| doc(s).pattern("P").unwrap().tile;
|
||||
let start = tile(&s);
|
||||
let art: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
|
||||
assert_eq!(art.len(), 2);
|
||||
assert!(!doc(&s).pattern("P").unwrap().move_tile_with_art, "off for a new pattern");
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
assert_eq!(tile(&s), start, "with the option off the tile stays");
|
||||
s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap();
|
||||
|
||||
s.execute("pattern.options", &json!({"moveTileWithArt": true})).unwrap();
|
||||
assert_eq!(s.execute("pattern.list", &json!({})).unwrap()["patterns"][0]["moveTileWithArt"], true);
|
||||
s.execute("object.move", &json!({"dx": 3, "dy": 4})).unwrap();
|
||||
assert_eq!(tile(&s), start + vectorcraft_geom::Vec2::new(3.0, 4.0));
|
||||
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, -1, 2]})).unwrap();
|
||||
assert_eq!(tile(&s), start + vectorcraft_geom::Vec2::new(2.0, 6.0));
|
||||
let k = s.prefs.keyboard_increment;
|
||||
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
|
||||
assert_eq!(tile(&s), start + vectorcraft_geom::Vec2::new(2.0 + k, 6.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(tile(&s), start + vectorcraft_geom::Vec2::new(3.0, 4.0), "undo puts the tile back");
|
||||
let moved = tile(&s);
|
||||
|
||||
sel(&mut s, &art[..1]);
|
||||
s.execute("object.move", &json!({"dx": 7, "dy": 0})).unwrap();
|
||||
assert_eq!(tile(&s), moved, "a move of part of the art leaves the tile");
|
||||
sel(&mut s, &art);
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
assert_eq!(tile(&s), moved, "a rotation leaves the tile");
|
||||
s.execute("object.move", &json!({"dx": 1, "dy": 1, "copy": true})).unwrap();
|
||||
assert_eq!(tile(&s), moved, "a copy leaves the tile");
|
||||
|
||||
s.execute("object.pattern.done", &json!({})).unwrap();
|
||||
assert_eq!(tile(&s), moved, "Done keeps the moved tile");
|
||||
assert!(doc(&s).pattern("P").unwrap().move_tile_with_art);
|
||||
}
|
||||
|
||||
/// Move Tile with Art counts a group in the tile art as moved when each of its members moved, one
|
||||
/// by one selected.
|
||||
#[test]
|
||||
fn move_tile_with_art_counts_a_group_whose_members_all_moved() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 12.0, 0.0, 6.0, 6.0);
|
||||
sel(&mut s, &[a, b]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("object.pattern.make", &json!({"name": "G"})).unwrap();
|
||||
s.execute("pattern.options", &json!({"moveTileWithArt": true})).unwrap();
|
||||
let start = doc(&s).pattern("G").unwrap().tile;
|
||||
let layer = doc(&s).pattern_edit.as_ref().unwrap().layer;
|
||||
let group = doc(&s).node(layer).unwrap().children().unwrap()[0].clone();
|
||||
let members: Vec<NodeId> = group.children().unwrap().iter().map(|c| c.id).collect();
|
||||
assert_eq!(members.len(), 2);
|
||||
sel(&mut s, &members[..1]);
|
||||
s.execute("object.move", &json!({"dx": 4, "dy": 0})).unwrap();
|
||||
assert_eq!(doc(&s).pattern("G").unwrap().tile, start, "one member of two");
|
||||
sel(&mut s, &members);
|
||||
s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap();
|
||||
assert_eq!(doc(&s).pattern("G").unwrap().tile, start + vectorcraft_geom::Vec2::new(0.0, 5.0), "every member");
|
||||
}
|
||||
|
||||
/// Move Tile with Art moves the tile as far as the art moved: when the art is aligned to the pixel
|
||||
/// grid and a move snaps it to the grid, the tile moves by the snapped distance.
|
||||
#[test]
|
||||
fn move_tile_with_art_follows_art_that_snaps_to_the_pixel_grid() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
sel(&mut s, &[a]);
|
||||
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
|
||||
s.execute("pattern.options", &json!({"moveTileWithArt": true})).unwrap();
|
||||
let art = s.doc().unwrap().selection.objects[0];
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(art).unwrap().extras_mut().pixel_aligned = true;
|
||||
let start = doc(&s).pattern("P").unwrap().tile;
|
||||
let origin = |s: &Session| doc(s).node(art).unwrap().geometric_bounds().unwrap().origin();
|
||||
let before = origin(&s);
|
||||
s.execute("object.move", &json!({"dx": 0.3, "dy": 0})).unwrap();
|
||||
let moved = origin(&s) - before;
|
||||
assert!((moved.x - 0.3).abs() > 1e-6, "the art snapped to the grid: {moved:?}");
|
||||
assert_eq!(doc(&s).pattern("P").unwrap().tile, start + moved, "the tile moved as far");
|
||||
}
|
||||
|
||||
/// Pattern Options that change nothing record no undo step.
|
||||
#[test]
|
||||
fn options_that_change_nothing_record_no_undo_step() {
|
||||
let mut s = session();
|
||||
make_dots(&mut s);
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = steps(&s);
|
||||
s.execute("pattern.options", &json!({"name": "Dots", "moveTileWithArt": false, "copies": 5})).unwrap();
|
||||
assert_eq!(steps(&s), before);
|
||||
s.execute("pattern.options", &json!({"name": "Dots", "moveTileWithArt": true})).unwrap();
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_rename_updates_swatch_and_paints() {
|
||||
let mut s = session();
|
||||
@@ -1625,6 +1730,7 @@ fn pattern_commands_refuse_a_param_of_the_wrong_type() {
|
||||
("pattern.options", options(json!({"copies": "5"})), number("copies", json!("5"))),
|
||||
("pattern.options", options(json!({"dimCopies": "50"})), number("dimCopies", json!("50"))),
|
||||
("pattern.options", options(json!({"sizeTileToArt": "true"})), switch("sizeTileToArt")),
|
||||
("pattern.options", options(json!({"moveTileWithArt": "yes"})), switch("moveTileWithArt")),
|
||||
("pattern.options", options(json!({"showTileEdge": 1})), switch("showTileEdge")),
|
||||
("pattern.options", options(json!({"showSwatchBounds": "no"})), switch("showSwatchBounds")),
|
||||
("pattern.options", options(json!({"overlap": "right"})), "`overlap` must be an object, not \"right\"".into()),
|
||||
|
||||
@@ -666,6 +666,26 @@ fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() {
|
||||
assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
let dir = Folder::new("open-pdf-link-pages-blank");
|
||||
let src = dir.file("blank.pdf");
|
||||
let art = || PdfPage::new(100.0, 50.0, "1 0 0 rg 10 10 20 20 re f");
|
||||
write(&src, &pdf(&[art(), PdfPage::new(80.0, 40.0, ""), art()], None));
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let boards: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
|
||||
assert_eq!(boards.len(), 3, "{boards:?}");
|
||||
assert_eq!((boards[0].width(), boards[0].height()), (20.0, 20.0), "the art's bounds");
|
||||
assert_eq!((boards[1].width(), boards[1].height()), (80.0, 40.0), "the blank page's crop box");
|
||||
// The pages are read from the one copy every page's blob keeps: a page that read the file
|
||||
// again would count here.
|
||||
let blob = d.images.values().next().map(|b| b.bytes.clone()).unwrap();
|
||||
assert_eq!(vectorcraft_pdf::reads_of(&blob), 0, "the pages are read from the file read once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_pages_is_refused_without_a_path_for_other_files_and_with_a_password_or_outlines() {
|
||||
let dir = Folder::new("open-pdf-link-pages-refused");
|
||||
|
||||
@@ -52,6 +52,39 @@ fn invert_and_complement_recolour_the_active_item() {
|
||||
assert_eq!((item_hex(&s, id, 0), item_hex(&s, id, 2)), ("#ff0000".into(), "#0000ff".into()));
|
||||
}
|
||||
|
||||
/// With a mixed selection, Invert on the Appearance panel's active row remembers the color of the row it recolors in the
|
||||
/// first object, the row equal to the active one, which need not have the active row's index.
|
||||
#[test]
|
||||
fn invert_of_the_active_row_remembers_the_equal_row_it_recolors() {
|
||||
let mut s = session();
|
||||
let rect = |s: &mut Session, x: f64| {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
};
|
||||
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 100.0));
|
||||
// `a` paints first: [red Fill, Stroke, blue Fill]. `b`, selected first: [green Fill, red Fill, Stroke].
|
||||
let look = Appearance::basic(Paint::solid(Color::from_hex("#ff0000").unwrap()), Paint::solid(Color::BLACK), 1.0);
|
||||
let (mut a_look, mut b_look) = (look.clone(), look.clone());
|
||||
let (mut green, mut blue) = (look.items[0].clone(), look.items[0].clone());
|
||||
*green.paint_mut() = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
*blue.paint_mut() = Paint::solid(Color::from_hex("#0000ff").unwrap());
|
||||
b_look.items.insert(0, green);
|
||||
a_look.items.push(blue);
|
||||
s.edit("Looks", |d, _| {
|
||||
d.node_mut(a).unwrap().appearance = vectorcraft_doc::Shared::new(a_look.clone());
|
||||
d.node_mut(b).unwrap().appearance = vectorcraft_doc::Shared::new(b_look.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": 1})).unwrap();
|
||||
s.last_solid = Color::from_hex("#808080").unwrap();
|
||||
s.execute("paint.invert", &json!({})).unwrap();
|
||||
let hexes = (item_hex(&s, a, 0), item_hex(&s, a, 2), item_hex(&s, b, 0), item_hex(&s, b, 1));
|
||||
assert_eq!(hexes, ("#00ffff".into(), "#0000ff".into(), "#00ff00".into(), "#00ffff".into()));
|
||||
assert_eq!(s.last_solid.to_hex(), "#00ffff", "the last color is the inverted red, not row 1 of the first object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mixed_proxy_compares_the_active_item() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -300,6 +300,71 @@ fn an_installed_script_is_read_as_script_run_reads_a_file() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_installed_run_runs_the_text_its_own_read_checked() {
|
||||
let dir = folder("installed-run");
|
||||
let root = dir.join("Scripts");
|
||||
let script = touch(&root, "draw.jsx");
|
||||
std::fs::write(&script, "#include \"lib.jsxinc\"\nvc.log(x);").unwrap();
|
||||
std::fs::write(root.join("lib.jsxinc"), "var x = 1;").unwrap();
|
||||
// A folder in the Scripts folder that is a link: script.run by path alone follows it.
|
||||
let elsewhere = dir.join("elsewhere");
|
||||
std::fs::create_dir_all(&elsewhere).unwrap();
|
||||
std::fs::write(elsewhere.join("other.jsx"), "vc.log(2);").unwrap();
|
||||
link_folder(&elsewhere, &root.join("linked"));
|
||||
let linked = root.join("linked").join("other.jsx").to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
s.attach_scripts_dir(root.clone());
|
||||
let path = script.to_string_lossy().into_owned();
|
||||
let r = s.execute("script.run", &json!({"path": path, "installed": true})).unwrap();
|
||||
assert_eq!(r["log"], json!([1]));
|
||||
assert_eq!(s.execute("script.run", &json!({"path": linked})).unwrap()["log"], json!([2]));
|
||||
// With `installed`, the run's own read is the check: a script behind a link is not run.
|
||||
let e = s.execute("script.run", &json!({"path": linked, "installed": true})).unwrap_err();
|
||||
assert_eq!(e.to_string(), cmd::scripts::NOT_LISTED);
|
||||
let outside = touch(&dir, "outside.js");
|
||||
let e = s.execute("script.run", &json!({"path": outside.to_string_lossy(), "installed": true})).unwrap_err();
|
||||
assert_eq!(e.to_string(), cmd::scripts::NOT_LISTED);
|
||||
// `installed` is true or false, and takes a path.
|
||||
assert!(
|
||||
s.execute("script.run", &json!({"path": path, "installed": "yes"})).unwrap_err().to_string().contains("`installed` must be true or false")
|
||||
);
|
||||
assert!(s.execute("script.run", &json!({"source": "1", "installed": true})).unwrap_err().to_string().contains("`installed` takes a `path`"));
|
||||
assert_eq!(s.execute("script.run", &json!({"source": "vc.log(3);", "installed": false})).unwrap()["log"], json!([3]));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
|
||||
let dir = folder("installed-scope");
|
||||
let checked = dir.join("Scripts").join("tools");
|
||||
let swapped = dir.join("swapped");
|
||||
for (folder, x) in [(&checked, 1), (&swapped, 2)] {
|
||||
std::fs::create_dir_all(folder).unwrap();
|
||||
std::fs::write(folder.join("draw.jsx"), "").unwrap();
|
||||
std::fs::write(folder.join("lib.jsxinc"), format!("var x = {x};")).unwrap();
|
||||
}
|
||||
// The path now leads through a link to another folder, as after a link was put in place of the
|
||||
// folder once the script's text was read.
|
||||
let link = dir.join("link");
|
||||
link_folder(&swapped, &link);
|
||||
let mut s = Session::new();
|
||||
let request = script::Request {
|
||||
name: "draw.jsx".into(),
|
||||
name_given: false,
|
||||
file: Some(link.join("draw.jsx").to_string_lossy().into_owned()),
|
||||
checked_real: Some(std::fs::canonicalize(checked.join("draw.jsx")).unwrap()),
|
||||
source: "#include \"lib.jsxinc\"\nvc.log(x);".into(),
|
||||
args: Default::default(),
|
||||
fuel: script::DEFAULT_FUEL,
|
||||
locale: "en_US".into(),
|
||||
answers: Vec::new(),
|
||||
};
|
||||
s.script_start(request).unwrap();
|
||||
assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1]));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() {
|
||||
let dir = folder("roots");
|
||||
|
||||
@@ -290,6 +290,11 @@ fn a_failed_run_puts_back_the_choices_its_commands_made() {
|
||||
run(&mut s, source).unwrap();
|
||||
assert_eq!(s.global_edit_options, before, "the failed command's choice went back");
|
||||
|
||||
let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); \
|
||||
if (vc.run('select.similar', {by: 'opacity'}).by !== 'opacity') throw new Error('not run'); throw new Error('x');";
|
||||
assert!(matches!(run(&mut s, source), Err(e) if !format!("{e:?}").contains("not run")));
|
||||
assert_eq!(s.select_similar, "all", "the Select Similar Objects attribute went back");
|
||||
|
||||
assert!(!s.caps_lock);
|
||||
assert!(run(&mut s, "vc.run('view.capsLock', {on: true}); throw new Error('x');").is_err());
|
||||
assert!(!s.caps_lock, "the Caps Lock state went back");
|
||||
|
||||
@@ -4606,6 +4606,10 @@ proptest! {
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
|
||||
survive("mutated .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai symbols, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
|
||||
// The same symbols as files of versions 10 to 13 place them, by a `TransformMatrix`.
|
||||
let older = mutate_text(&older_symbols_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&older)].concat();
|
||||
survive("mutated older .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
// A symbol library: the same symbols and list, no layers.
|
||||
let library = mutate_text(&symbol_library_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&library)].concat();
|
||||
@@ -4860,6 +4864,53 @@ fn the_symbols_fuzz_data_opens_live() {
|
||||
assert_eq!(instances, 3);
|
||||
}
|
||||
|
||||
/// [`symbols_text`] with its instances placed by a `TransformMatrix`, as files of versions 10 to
|
||||
/// 13 write them. Art space's origin is at canvas (8091, 8242), from the template box: on the page
|
||||
/// the matrix takes the symbol's art to the canvas (y down), and in S2's art to S2's space.
|
||||
fn older_symbols_text() -> String {
|
||||
let mut text = symbols_text();
|
||||
for (newer, older) in [
|
||||
("1 0 0 -1 -8081 8237 /RTransformMatrix", "1 0 0 1 10 5 /TransformMatrix"),
|
||||
("1 0 0 -1 20 50 /RTransformMatrix", "1 0 0 1 8111 8192 /TransformMatrix"),
|
||||
("2 0 0 -2 100 50 /RTransformMatrix", "2 0 0 2 8191 8192 /TransformMatrix"),
|
||||
("1 0 0 -1 20 20 /RTransformMatrix", "1 0 0 1 8111 8222 /TransformMatrix"),
|
||||
] {
|
||||
assert!(text.contains(newer), "{newer}");
|
||||
text = text.replace(newer, older);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The older data [`ai_symbols_never_panic`] damages, as it is, opens with its instances live and
|
||||
/// placed as [`symbols_text`] places them, on the page and in S2's art.
|
||||
#[test]
|
||||
fn the_older_symbols_fuzz_data_opens_live() {
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
fn xfs(n: &Node, out: &mut Vec<[f64; 6]>) {
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => out.push(xf.as_coeffs()),
|
||||
_ => n.children().into_iter().flatten().for_each(|c| xfs(c, out)),
|
||||
}
|
||||
}
|
||||
let open = |text: &str| {
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
|
||||
let (doc, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0);
|
||||
assert!(layered, "{warnings:?}");
|
||||
let (mut page, mut nested) = (vec![], vec![]);
|
||||
doc.layers.iter().for_each(|l| xfs(l, &mut page));
|
||||
let s2 = doc.symbols.iter().find(|s| s.name == "S2").expect("S2");
|
||||
xfs(&s2.art, &mut nested);
|
||||
(page, nested)
|
||||
};
|
||||
let text = older_symbols_text();
|
||||
assert!(!text.contains("/RTransformMatrix"));
|
||||
let (older, newer) = (open(&text), open(&symbols_text()));
|
||||
assert_eq!((older.0.len(), older.1.len()), (3, 1));
|
||||
let same = |a: &[[f64; 6]], b: &[[f64; 6]]| a.len() == b.len() && a.iter().flatten().zip(b.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-9);
|
||||
assert!(same(&older.0, &newer.0), "{older:?} {newer:?}");
|
||||
assert!(same(&older.1, &newer.1), "{older:?} {newer:?}");
|
||||
}
|
||||
|
||||
/// Symbols the reader must stop at: sections that don't end, references and matrices it can't
|
||||
/// use, definitions nested deeper than it reads, and symbols that hold each other.
|
||||
#[test]
|
||||
|
||||
@@ -10457,7 +10457,7 @@ fn an_envelope_is_written_in_the_order_the_reader_reads_it() {
|
||||
/// Envelopes the reader would open in another shape, or not at all, are written as their distorted
|
||||
/// art with a warning, and open as that art: an envelope of type, one in a turned frame, a warp drawn
|
||||
/// without its style's net, a mesh the reader would lay out the other way round, a top object
|
||||
/// whose sides don't pair up, a Fidelity that isn't a whole number and bounds margins kept with
|
||||
/// with a side of more segments than the grid has columns, a Fidelity that isn't a whole number and bounds margins kept with
|
||||
/// Distort Appearance off. Other live objects keep their own warning.
|
||||
#[test]
|
||||
fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() {
|
||||
@@ -10494,15 +10494,10 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() {
|
||||
**kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: transpose(points, 3, 2), handles: vec![] };
|
||||
}
|
||||
});
|
||||
let mut uneven = kurbo::BezPath::new();
|
||||
uneven.move_to((30.0, 10.0));
|
||||
for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (30.0, 90.0)] {
|
||||
uneven.line_to(p);
|
||||
}
|
||||
uneven.close_path();
|
||||
let lopsided = change(&|k| {
|
||||
// A top side of 51 segments: more grid columns than the reader reads.
|
||||
let crowded = change(&|k| {
|
||||
if let NodeKind::Envelope { kind, .. } = k {
|
||||
**kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven), corners: None };
|
||||
**kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven_top_object(51)), corners: None };
|
||||
}
|
||||
});
|
||||
let fractional = change(&|k| {
|
||||
@@ -10521,7 +10516,7 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() {
|
||||
("turned", turned),
|
||||
("old warp", old_warp),
|
||||
("sideways mesh", sideways),
|
||||
("lopsided top object", lopsided),
|
||||
("top object past the grid's limit", crowded),
|
||||
("fractional fidelity", fractional),
|
||||
("margin kept", margin_kept),
|
||||
];
|
||||
@@ -10542,6 +10537,131 @@ fn transpose(points: Vec<kurbo::Point>, rows: usize, cols: usize) -> Vec<kurbo::
|
||||
(0..=cols).flat_map(|c| (0..=rows).map(move |r| (r, c))).map(|(r, c)| points[r * (cols + 1) + c]).collect()
|
||||
}
|
||||
|
||||
/// A top object over (30, 10)-(170, 90) whose top side is `top` straight segments, falling and
|
||||
/// rising by 10 pt between its anchors, and whose other sides are one straight segment each.
|
||||
fn uneven_top_object(top: usize) -> kurbo::BezPath {
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((30.0, 10.0));
|
||||
for k in 1..top {
|
||||
path.line_to((30.0 + 140.0 * k as f64 / top as f64, if k % 2 == 1 { 20.0 } else { 10.0 }));
|
||||
}
|
||||
for p in [(170.0, 10.0), (170.0, 90.0), (30.0, 90.0)] {
|
||||
path.line_to(p);
|
||||
}
|
||||
path.close_path();
|
||||
path
|
||||
}
|
||||
|
||||
/// Do the patches of top objects `a` and `b` lie within 0.001 pt of each other at every place of a
|
||||
/// 32 × 32 grid?
|
||||
fn same_top_object_patch(a: &vectorcraft_doc::live::EnvelopeKind, b: &vectorcraft_doc::live::EnvelopeKind) -> bool {
|
||||
use vectorcraft_doc::live::{Coons, EnvelopeKind};
|
||||
let (EnvelopeKind::TopObject { path, corners }, EnvelopeKind::TopObject { path: p, corners: c }) = (a, b) else { return false };
|
||||
let (Some(a), Some(b)) = (Coons::from_top_object(path, *corners), Coons::from_top_object(p, *c)) else { return false };
|
||||
let at = |i: u32| f64::from(i) / 32.0;
|
||||
(0..=32).all(|j| (0..=32).all(|i| a.eval(at(i), at(j)).distance(b.eval(at(i), at(j))) < 1e-3))
|
||||
}
|
||||
|
||||
/// A top object whose top and bottom sides have different numbers of segments is written live, its
|
||||
/// side with fewer segments split into as many as the side across from it has, with Edit Contents off
|
||||
/// and on: two straight segments over one straight one, three over one, and two over one curve.
|
||||
/// VectorCraft's reader opens it as a top object with its corners on the same four points, the same
|
||||
/// patch, contents, Fidelity, Edit Contents and Envelope Options, and saved again it opens the same.
|
||||
#[test]
|
||||
fn a_top_object_with_uneven_sides_is_read_back_live() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let mut curved = kurbo::BezPath::new();
|
||||
curved.move_to((30.0, 10.0));
|
||||
curved.line_to((100.0, 0.0));
|
||||
curved.line_to((170.0, 10.0));
|
||||
curved.line_to((170.0, 90.0));
|
||||
curved.curve_to((130.0, 105.0), (70.0, 105.0), (30.0, 90.0));
|
||||
curved.close_path();
|
||||
let shapes = [("two over one", uneven_top_object(2), 6), ("three over one", uneven_top_object(3), 8), ("two over a curve", curved, 6)];
|
||||
for (name, path, anchors) in shapes {
|
||||
let kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&path), corners: None };
|
||||
for editing in [false, true] {
|
||||
let what = format!("{name}, editing {editing}");
|
||||
let doc = envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW);
|
||||
let text = program(&doc);
|
||||
assert!(text.contains("AIDeformOptionsKey") && text.contains("%_3 /Int (AIDeformStyle) ,\n"), "{what}: {text}");
|
||||
let (back, warnings, notes) = envelope_back(&doc);
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}");
|
||||
assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}");
|
||||
let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { panic!("{what}: {back:#?}") };
|
||||
assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}");
|
||||
let EnvelopeKind::TopObject { path: outline, corners: Some(corners) } = &**got else { panic!("{what}: {got:?}") };
|
||||
let sp = &outline.subpaths[0];
|
||||
assert_eq!(sp.anchors.len(), anchors, "{what}: {outline:?}");
|
||||
let points = corners.map(|i| sp.anchors[i as usize].p);
|
||||
let want = [(30.0, 10.0), (170.0, 10.0), (170.0, 90.0), (30.0, 90.0)].map(kurbo::Point::from);
|
||||
assert!(points.iter().zip(want).all(|(a, b)| a.distance(b) < 1e-6), "{what}: {points:?}");
|
||||
assert!(same_top_object_patch(&kind, got), "{what}: {got:?}");
|
||||
let colors: Vec<Option<Color>> = content.iter().map(|c| c.appearance.fill_paint().color()).collect();
|
||||
assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}");
|
||||
let mut again = Document::new(200.0, 100.0);
|
||||
let layer = again.layers[0].id;
|
||||
again.insert(Some(layer), usize::MAX, back.clone()).unwrap();
|
||||
let (twice, warnings, notes) = envelope_back(&again);
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}");
|
||||
let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") };
|
||||
assert!(same_top_object_patch(&kind, twice), "{what}, saved again: {twice:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A top object with a top side of 50 segments over a bottom side of one is written live with a grid
|
||||
/// of 50 columns, the most the reader reads.
|
||||
#[test]
|
||||
fn a_top_object_split_to_the_grids_limit_is_read_back_live() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven_top_object(50)), corners: None };
|
||||
let doc = envelope_doc(kind.clone(), 50.0, false, EnvelopeOptions::NEW);
|
||||
let text = program(&doc);
|
||||
assert!(text.contains("[50 1] /Size X#"), "{text}");
|
||||
let (back, warnings, notes) = envelope_back(&doc);
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
let NodeKind::Envelope { kind: got, .. } = &back.kind else { panic!("{back:#?} {notes:?}") };
|
||||
assert!(same_top_object_patch(&kind, got), "{got:?}");
|
||||
}
|
||||
|
||||
/// A top object whose side with fewer segments would share out the content another way once split
|
||||
/// (two curves that aren't one curve, under three segments) is written as its art, with a warning.
|
||||
#[test]
|
||||
fn a_top_object_whose_split_side_would_map_another_way_is_written_as_its_art() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let mut path = uneven_top_object(3);
|
||||
path.truncate(5);
|
||||
path.curve_to((150.0, 110.0), (120.0, 110.0), (100.0, 90.0));
|
||||
path.curve_to((80.0, 95.0), (40.0, 80.0), (30.0, 90.0));
|
||||
path.close_path();
|
||||
let kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&path), corners: None };
|
||||
let doc = envelope_doc(kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
assert!(!program(&doc).contains("AIDeformOptionsKey"));
|
||||
let (back, warnings, _) = envelope_back(&doc);
|
||||
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
assert!(matches!(back.kind, NodeKind::Group { .. }), "{back:#?}");
|
||||
}
|
||||
|
||||
/// A top object whose split side would map the content another way only between the places of an
|
||||
/// even grid of eighths is written as its art too: a bottom side of a long straight segment, which is
|
||||
/// split, and a short curve in its last eighth, which the reader then samples at fewer points.
|
||||
#[test]
|
||||
fn a_top_object_whose_split_side_differs_between_eighths_is_written_as_its_art() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let mut path = uneven_top_object(3);
|
||||
path.truncate(5);
|
||||
path.curve_to((168.0, 85.0), (164.0, 85.0), (162.0, 90.0));
|
||||
path.line_to((30.0, 90.0));
|
||||
path.close_path();
|
||||
let kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&path), corners: None };
|
||||
let doc = envelope_doc(kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
assert!(!program(&doc).contains("AIDeformOptionsKey"));
|
||||
let (back, warnings, _) = envelope_back(&doc);
|
||||
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
assert!(matches!(back.kind, NodeKind::Group { .. }), "{back:#?}");
|
||||
}
|
||||
|
||||
/// An envelope with its contents in an opacity mask's art is written as its art there, and an
|
||||
/// envelope in a group stays live.
|
||||
#[test]
|
||||
|
||||
@@ -8,13 +8,14 @@
|
||||
//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain
|
||||
//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written
|
||||
//! for it, one grid edge to each segment of its sides. An envelope the reader would open in another
|
||||
//! shape is written as its distorted art.
|
||||
//! for it, one grid edge to each segment of its sides, a side with fewer segments than the side
|
||||
//! across from it split into more. An envelope the reader would open in another shape is written as
|
||||
//! its distorted art.
|
||||
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Point, Vec2};
|
||||
use kurbo::{CubicBez, ParamCurve, Point, Vec2};
|
||||
use vectorcraft_doc::live::{
|
||||
Coons, EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint, PreserveShape, WARP_NET, envelope_content_boxes,
|
||||
envelope_grid, envelope_stroke_margin, warp_grid,
|
||||
@@ -173,11 +174,44 @@ fn reads_as_written(rows: usize, cols: usize, pts: &[GridPoint]) -> bool {
|
||||
envelope_upright(&mesh).is_some_and(|(r, c, read)| (r as usize, c as usize) == (rows, cols) && read == pts)
|
||||
}
|
||||
|
||||
/// `pieces`, one side of a top object, split into `n` pieces: each piece is split into equal spans
|
||||
/// of its curve parameter, the extra pieces going one at a time to the piece with the longest
|
||||
/// control polygon for each of its spans. `None` where `n` is fewer pieces than it has, more than
|
||||
/// [`MAX_GRID`], or a split leaves a piece of no length.
|
||||
fn split_to(pieces: &[CubicBez], n: usize) -> Option<Vec<CubicBez>> {
|
||||
if n < pieces.len() || n > MAX_GRID {
|
||||
return None;
|
||||
}
|
||||
if n == pieces.len() {
|
||||
return Some(pieces.to_vec());
|
||||
}
|
||||
let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3);
|
||||
let lengths: Vec<f64> = pieces.iter().map(polygon).collect();
|
||||
let mut parts = vec![1usize; pieces.len()];
|
||||
for _ in pieces.len()..n {
|
||||
let most = (0..pieces.len()).max_by(|a, b| (lengths[*a] / parts[*a] as f64).total_cmp(&(lengths[*b] / parts[*b] as f64)))?;
|
||||
parts[most] += 1;
|
||||
}
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for (c, p) in pieces.iter().zip(parts) {
|
||||
for j in 0..p {
|
||||
let piece = c.subsegment(j as f64 / p as f64..(j + 1) as f64 / p as f64);
|
||||
if [piece.p1, piece.p2, piece.p3].iter().all(|q| q.distance(piece.p0) <= 1e-9) {
|
||||
return None;
|
||||
}
|
||||
out.push(piece);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The grid a top object with outline `path` and corners `corners` is written with: its edge runs
|
||||
/// through the outline's anchors clockwise from the top left corner, one grid edge to a segment, so
|
||||
/// the top and bottom sides need as many segments as each other, as do the left and right sides;
|
||||
/// the points inside blend the sides. `None` where that grid's edge, read back as the top object's
|
||||
/// outline, doesn't give the same patch ([`Coons::from_top_object`]) at every place checked.
|
||||
/// through the outline's anchors clockwise from the top left corner, one grid edge to a segment,
|
||||
/// the points inside blending the sides. The top and bottom sides need as many grid edges as each
|
||||
/// other, as do the left and right sides, so where one side of a pair has fewer segments than the
|
||||
/// other, its segments are split ([`split_to`]) without changing its shape. `None` where that
|
||||
/// grid's edge, read back as the top object's outline, doesn't give the same patch
|
||||
/// ([`Coons::from_top_object`]) at every place checked.
|
||||
fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, usize, Vec<GridPoint>)> {
|
||||
let coons = Coons::from_top_object(path, corners)?;
|
||||
// The outline, as the patch takes it: the largest subpath.
|
||||
@@ -214,10 +248,35 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize,
|
||||
}
|
||||
};
|
||||
let gap = |k: usize| (at[(k + 1) % 4] + count - at[k]) % count;
|
||||
let (cols, rows) = (gap(0), gap(1));
|
||||
if gap(2) != cols || gap(3) != rows || cols > MAX_GRID || rows > MAX_GRID {
|
||||
if (0..4).any(|k| gap(k) > MAX_GRID) {
|
||||
return None;
|
||||
}
|
||||
// Each side's segments from its corner on, a straight one as a cubic with its handles a third of
|
||||
// the way along, which the patch spreads evenly along, as it does a straight segment.
|
||||
let side = |k: usize| -> Vec<CubicBez> {
|
||||
(0..gap(k))
|
||||
.map(|j| {
|
||||
let i = (at[k] + j) % count;
|
||||
let seg = sp.segment(i);
|
||||
if sp.segment_is_line(i) {
|
||||
CubicBez::new(seg.p0, seg.p0.lerp(seg.p3, 1.0 / 3.0), seg.p0.lerp(seg.p3, 2.0 / 3.0), seg.p3)
|
||||
} else {
|
||||
seg
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut sides = [side(0), side(1), side(2), side(3)];
|
||||
// Opposite sides take as many segments as each other: the one with fewer has some split.
|
||||
for k in 0..2 {
|
||||
let n = sides[k].len().max(sides[k + 2].len());
|
||||
for s in [k, k + 2] {
|
||||
sides[s] = split_to(&sides[s], n)?;
|
||||
}
|
||||
}
|
||||
let (cols, rows) = (sides[0].len(), sides[1].len());
|
||||
let edge: Vec<CubicBez> = sides.concat();
|
||||
let total = edge.len();
|
||||
let width = cols + 1;
|
||||
let mut pts: Vec<GridPoint> = vec![(Point::ZERO, [Vec2::ZERO; 4]); (rows + 1) * width];
|
||||
// Where the `k`th anchor from the top left corner goes, and the slots of the handles of the
|
||||
@@ -233,20 +292,15 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize,
|
||||
(rows - (k - 2 * cols - rows), 0, H_UP, H_DOWN)
|
||||
}
|
||||
};
|
||||
for k in 0..count {
|
||||
let i = (at[0] + k) % count;
|
||||
let seg = sp.segment(i);
|
||||
// A straight segment's patch spreads evenly along it, as a cubic's with its handles a third
|
||||
// of the way does.
|
||||
let (p1, p2) = if sp.segment_is_line(i) { (seg.p0.lerp(seg.p3, 1.0 / 3.0), seg.p0.lerp(seg.p3, 2.0 / 3.0)) } else { (seg.p1, seg.p2) };
|
||||
for (k, seg) in edge.iter().enumerate() {
|
||||
let (r, c, out, into) = place(k);
|
||||
let (nr, nc, _, _) = place((k + 1) % count);
|
||||
let (nr, nc, _, _) = place((k + 1) % total);
|
||||
if let Some(q) = pts.get_mut(r * width + c) {
|
||||
q.0 = seg.p0;
|
||||
q.1[out] = p1 - seg.p0;
|
||||
q.1[out] = seg.p1 - seg.p0;
|
||||
}
|
||||
if let Some(q) = pts.get_mut(nr * width + nc) {
|
||||
q.1[into] = p2 - seg.p3;
|
||||
q.1[into] = seg.p2 - seg.p3;
|
||||
}
|
||||
}
|
||||
// The points inside, blended from the sides.
|
||||
@@ -274,9 +328,20 @@ fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize,
|
||||
let read = Coons::from_top_object(&outline, Some(corners))?;
|
||||
let [tl, tr, br, bl] = coons.corners();
|
||||
let reach = tl.distance(br).max(tr.distance(bl)).max(1.0) * TOP_OBJECT_TOLERANCE;
|
||||
const STEPS: usize = 8;
|
||||
let at = |i: usize| i as f64 / STEPS as f64;
|
||||
let same = (0..=STEPS).all(|j| (0..=STEPS).all(|i| coons.eval(at(i), at(j)).distance(read.eval(at(i), at(j))) <= reach));
|
||||
// Each side of both patches runs straight between the places the sides have points
|
||||
// ([`Coons::places`]), so two matching sides lie furthest apart at one of those places. A point
|
||||
// inside a patch blends its four sides and corners, so where every side lies within a third of
|
||||
// `reach` of the other patch's, the patches lie within `reach` of each other everywhere.
|
||||
let merge = |a: Vec<f64>, b: Vec<f64>| {
|
||||
let mut v = [a, b].concat();
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.dedup();
|
||||
v
|
||||
};
|
||||
let ([cu, cv], [ru, rv]) = (coons.places(), read.places());
|
||||
let (us, vs) = (merge(cu, ru), merge(cv, rv));
|
||||
let near = |u: f64, v: f64| coons.eval(u, v).distance(read.eval(u, v)) <= reach / 3.0;
|
||||
let same = us.iter().all(|&u| near(u, 0.0) && near(u, 1.0)) && vs.iter().all(|&v| near(0.0, v) && near(1.0, v));
|
||||
same.then_some((rows, cols, pts))
|
||||
}
|
||||
|
||||
|
||||
@@ -102,8 +102,10 @@
|
||||
//! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx
|
||||
//! ty /RTransformMatrix ;`, the matrix taking the symbol's art to art space; in a symbol's art,
|
||||
//! it takes it to art space about the canvas point of art space's origin, as a pattern's
|
||||
//! gradients are. Its hide and lock come before it (`Xw`, `A`) and its transparency (`Xy`) after
|
||||
//! it.
|
||||
//! gradients are. Files of versions 10 to 13 write `a b c d tx ty /TransformMatrix` instead,
|
||||
//! the matrix taking the symbol's art to the canvas (y down, art space's origin at the canvas
|
||||
//! point the template box gives); in a symbol's art, it takes the art to that symbol's space.
|
||||
//! Its hide and lock come before it (`Xw`, `A`) and its transparency (`Xy`) after it.
|
||||
//!
|
||||
//! Sections the reader doesn't need (styles, filters) are skipped; type, instances of symbols it
|
||||
//! can't read, fills with a pattern it can't read, placed files without a preview and operators
|
||||
|
||||
@@ -636,17 +636,22 @@ impl<'a> Reader<'a> {
|
||||
/// A symbol instance (`/SymbolInstance`): the symbol its `SymbolRef` names, placed by its
|
||||
/// `RTransformMatrix`, hidden and locked as the state says. In a symbol's art the matrix is
|
||||
/// written about the canvas point of art space's origin, and the name is the file's until the
|
||||
/// symbols are checked ([`Self::check_symbols`]). An instance of a symbol that wasn't read, one
|
||||
/// whose appearance differs from its symbol's, or one placed only by a `Matrix` or `Transform`,
|
||||
/// comes in as the page draws it, within the symbol's box placed by the matrix when the box is
|
||||
/// known.
|
||||
/// symbols are checked ([`Self::check_symbols`]). Files of versions 10 to 13 place an instance
|
||||
/// by a `TransformMatrix` instead, which takes the symbol's art to the canvas (y down); in a
|
||||
/// symbol's art, it takes the art to that symbol's space. The reader converts it with the canvas
|
||||
/// point of art space's origin, from the template box. An instance of a symbol that wasn't
|
||||
/// read, one whose appearance differs from its symbol's, or one placed only by a `Matrix` or
|
||||
/// `Transform`, comes in as the page draws it, within the symbol's box placed by the matrix
|
||||
/// when the box is known.
|
||||
fn symbol_instance(&mut self, o: &Obj) -> Result<(), String> {
|
||||
let name = self.names.entry(o, "SymbolRef");
|
||||
let affine = |n: &[f64]| match n {
|
||||
[a, b, c, d, e, f] if [a, b, c, d, e, f].iter().all(|v| v.is_finite()) => Some(super::Affine::new([*a, *b, *c, *d, *e, *f])),
|
||||
_ => None,
|
||||
};
|
||||
let live = affine(&o.nums("RTransformMatrix"));
|
||||
// The canvas → art space: y turned up about the canvas point of art space's origin.
|
||||
let from_canvas = self.canvas_origin().map(|o| super::Affine::new([1.0, 0.0, 0.0, -1.0, -o.x, o.y]));
|
||||
let live = affine(&o.nums("RTransformMatrix")).or_else(|| Some(from_canvas? * affine(&o.nums("TransformMatrix"))?));
|
||||
let boxed_only = live.is_none();
|
||||
let matrix = live.or_else(|| {
|
||||
o.get("Matrix")
|
||||
|
||||
@@ -5115,6 +5115,73 @@ fn an_instance_in_a_symbols_art_is_placed_from_the_canvas() {
|
||||
assert_eq!(instance_box(&doc, &a[0]), Rect::new(58.0, 53.0, 62.0, 57.0));
|
||||
}
|
||||
|
||||
/// Files of versions 10 to 13 place an instance by a `TransformMatrix` that takes the symbol's art
|
||||
/// to the canvas (y down): the instance stays live and lands where the `RTransformMatrix` of a
|
||||
/// newer file puts it, on the page and in a symbol's art.
|
||||
#[test]
|
||||
fn an_instance_placed_on_the_canvas_by_an_older_file_stays_live() {
|
||||
// The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242).
|
||||
let older = |name: &str, m: [f64; 6]| {
|
||||
let [a, b, c, d, e, f] = m;
|
||||
format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{a} {b} {c} {d} {e} {f} /TransformMatrix\n;\n")
|
||||
};
|
||||
let page = older("Dot", [1.0, 0.0, 0.0, 1.0, 8111.0, 8192.0]) + &older("Dot", [2.0, 0.0, 0.0, 2.0, 8191.0, 8192.0]);
|
||||
let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Dot", &dot(), 5)), layer(&page));
|
||||
let doc = read_ok(&body).doc;
|
||||
let a = art(&doc);
|
||||
assert_eq!(a.len(), 2);
|
||||
assert!(a.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "{a:#?}");
|
||||
assert_eq!(instance_box(&doc, &a[0]), Rect::new(18.0, 48.0, 22.0, 52.0));
|
||||
assert_eq!(instance_box(&doc, &a[1]), Rect::new(96.0, 46.0, 104.0, 54.0));
|
||||
// Turned and scaled, as the newer file writes the same instance: canvas x is art x + 8091 and
|
||||
// canvas y is 8242 - art y, so the second row of the matrix changes sign.
|
||||
let turned = [1.299, -0.4, 0.75, 0.6928, 8111.0, 8192.0];
|
||||
let newer = [1.299, 0.4, 0.75, -0.6928, 20.0, 50.0];
|
||||
let older_doc =
|
||||
read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Dot", &dot(), 5)), layer(&older("Dot", turned)))).doc;
|
||||
let newer_doc =
|
||||
read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Dot", &dot(), 5)), layer(&instance("Dot", newer)))).doc;
|
||||
let xf = |d: &Document| match &art(d)[0].kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => xf.as_coeffs(),
|
||||
k => panic!("{k:?}"),
|
||||
};
|
||||
let (o, n) = (xf(&older_doc), xf(&newer_doc));
|
||||
assert!(o.iter().zip(n).all(|(a, b)| (a - b).abs() < 1e-9), "{o:?} {n:?}");
|
||||
// In a symbol's art the matrix takes the art to the symbol's own space: Dot at (10, 5) in Pair's
|
||||
// art, which the page instance puts at (50, 50).
|
||||
let nested = older("Dot", [1.0, 0.0, 0.0, 1.0, 10.0, 5.0]);
|
||||
let defs = symbols(&(symbol("Dot", &dot(), 5) + &symbol("Pair", &nested, 1)));
|
||||
let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&older("Pair", [1.0, 0.0, 0.0, 1.0, 8141.0, 8192.0])));
|
||||
let doc = read_ok(&body).doc;
|
||||
let a = art(&doc);
|
||||
assert_eq!(instance_box(&doc, &a[0]), Rect::new(58.0, 53.0, 62.0, 57.0));
|
||||
// One document saved in both forms: the template box's center is (100.5, 99.5), so art space's
|
||||
// origin is at canvas (8091, 8291). Dot sits at (5, 2.5) in Pair's art, and the page instance
|
||||
// puts Pair at (57, 145.5). Both instances get the newer file's matrices, coefficient by
|
||||
// coefficient.
|
||||
let saved = |inner: String, pair: String| {
|
||||
let defs = symbols(&(symbol("Dot", &dot(), 5) + &symbol("Pair", &inner, 1)));
|
||||
read_ok(&format!("%AI3_TemplateBox: 100.5 99.5 100.5 99.5\n{defs}{}", layer(&pair))).doc
|
||||
};
|
||||
let older_doc = saved(older("Dot", [1.0, 0.0, 0.0, 1.0, 5.0, 2.5]), older("Pair", [1.0, 0.0, 0.0, 1.0, 8148.0, 8145.5]));
|
||||
let newer_doc = saved(instance("Dot", [1.0, 0.0, 0.0, -1.0, -8086.0, 8288.5]), instance("Pair", [1.0, 0.0, 0.0, -1.0, 57.0, 145.5]));
|
||||
fn first_xf(n: &Node) -> Option<[f64; 6]> {
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => Some(xf.as_coeffs()),
|
||||
_ => n.children()?.iter().find_map(|c| first_xf(c)),
|
||||
}
|
||||
}
|
||||
let both = |d: &Document| (xf(d), first_xf(&d.symbols[1].art).expect("Dot's instance in Pair's art"));
|
||||
let ((op, on), (np, nn)) = (both(&older_doc), both(&newer_doc));
|
||||
assert!(op.iter().zip(np).all(|(a, b)| (a - b).abs() < 1e-9), "{op:?} {np:?}");
|
||||
assert!(on.iter().zip(nn).all(|(a, b)| (a - b).abs() < 1e-9), "{on:?} {nn:?}");
|
||||
// Without a template box the canvas's place isn't known: the instance isn't read, though Dot is
|
||||
// defined and the same instance with a template box is read above.
|
||||
let defs = symbols(&symbol("Dot", &dot(), 5));
|
||||
let e = read(stream(&format!("{defs}{}", layer(&older("Dot", [1.0, 0.0, 0.0, 1.0, 8111.0, 8192.0])))).as_bytes());
|
||||
assert!(e.is_err_and(|e| e.contains("symbols")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_in_a_symbols_art_is_placed_from_the_canvas() {
|
||||
// The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). The
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//!
|
||||
//! The editing copy of a file keeps the characters of its text objects, with their fonts, sizes,
|
||||
//! colours and where they sit, in one text document of its own: between `%AI11_BeginTextDocument`
|
||||
//! and `%AI11_EndTextDocument`, ASCII85 of nested dictionaries with numbers for keys. A text object
|
||||
//! in a layer is only a stub naming its story in it (`/StoryIndex`).
|
||||
//! and `%AI11_EndTextDocument`, ASCII85 of nested dictionaries with numbers for keys (names in files
|
||||
//! saved for version 11, and for keys newer than the version a file is saved for: see [`names`]).
|
||||
//! A text object in a layer is only a stub naming its story in it (`/StoryIndex`).
|
||||
//!
|
||||
//! The format isn't documented. Most of what is read here was worked out from the files of the
|
||||
//! project's users, used locally and never committed, by comparing it with the type their pages
|
||||
@@ -32,6 +33,8 @@ use vectorcraft_doc::{
|
||||
};
|
||||
use vectorcraft_geom::{Affine, PathData, Point, Rect};
|
||||
|
||||
mod names;
|
||||
|
||||
/// Longest story read (bytes).
|
||||
pub(crate) const MAX_STORY: usize = 1 << 20;
|
||||
/// Biggest text document read (bytes, decoded).
|
||||
@@ -631,7 +634,7 @@ impl Texts {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let doc = read(&bytes)?;
|
||||
let doc = names::numbered(read(&bytes)?);
|
||||
let fonts = doc
|
||||
.get("0")?
|
||||
.get("1")?
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
//! The keys of a text document written by name.
|
||||
//!
|
||||
//! Files saved for version 11 write every key of the text document by its name
|
||||
//! (`/DocumentResources << /FontSet << /Resources [ ...`) and a typed node's kind under
|
||||
//! `/StreamTag`, with the long names of the layout's strikes (`/FrameStrike`, `/LineStrike`). Later
|
||||
//! versions write each key as its number (`/0 << /1 << /0 [ ...`, the kind under `/99`, `/F`,
|
||||
//! `/L`), except the keys that are newer than the version the file is saved for, which they still
|
||||
//! write by name (`/ParagraphDirection`, `/VersionString`). A key's number depends on the
|
||||
//! dictionary it is in (`Leading` is 5 in a character style and 11 in a line), so the names are
|
||||
//! read with the dictionary each one sits in, from the root down.
|
||||
//!
|
||||
//! A public reader of the format lists the names and numbers of the document's resources and
|
||||
//! objects, the character and paragraph features, a story's model and view, a frame's data, the
|
||||
//! line and glyph strikes, a font record's name, type and axes, and a color's type and values:
|
||||
//! <https://github.com/Zignixx/firepixel/blob/60e3d5517df3106674b3208eb71e65471b4daec4/crates/fp-fwpng/src/ate_keys.rs>.
|
||||
//! The other names here (the sets' lists, a resource and its kind, a font record's version, the
|
||||
//! styles' name, parent and features, a Kinsoku set's name and data, a frame's point, curve, first
|
||||
//! baseline and path options, the runs and their kerning, a strike's kind and origin, the tab stops
|
||||
//! and the paints) are VectorCraft's own reading of the format, matched to the numbers the reader
|
||||
//! already uses.
|
||||
//!
|
||||
//! Only the keys the text document's reader looks at, and the dictionaries on the way to them, are
|
||||
//! given numbers; any other key keeps its name and is skipped as before. A key that the dictionary
|
||||
//! also has as a number keeps the number's value.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::Val;
|
||||
|
||||
/// The kind of a dictionary of the text document, which gives its keys' numbers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Kind {
|
||||
Root,
|
||||
Resources,
|
||||
Objects,
|
||||
FontSet,
|
||||
FontEntry,
|
||||
Font,
|
||||
FontRecord,
|
||||
KinsokuSet,
|
||||
KinsokuEntry,
|
||||
Kinsoku,
|
||||
CharSheetSet,
|
||||
CharSheetEntry,
|
||||
CharSheet,
|
||||
ParaSheetSet,
|
||||
ParaSheetEntry,
|
||||
ParaSheet,
|
||||
FrameSet,
|
||||
FrameEntry,
|
||||
Frame,
|
||||
Bezier,
|
||||
FrameData,
|
||||
FirstBaseline,
|
||||
PathOptions,
|
||||
TextObject,
|
||||
Model,
|
||||
ParaRuns,
|
||||
ParaRun,
|
||||
ParaRunData,
|
||||
CharRuns,
|
||||
CharRun,
|
||||
CharRunData,
|
||||
KernRuns,
|
||||
KernRun,
|
||||
KernRunData,
|
||||
View,
|
||||
FrameRef,
|
||||
Strike,
|
||||
Transform,
|
||||
CharFeatures,
|
||||
ParaFeatures,
|
||||
TabStops,
|
||||
TabStop,
|
||||
Paint,
|
||||
Color,
|
||||
/// A dictionary none of whose keys are read: its keys stay as they are.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// A key of a dictionary: its name, its number, and the kind of the dictionaries its value holds
|
||||
/// (the value itself, or the elements of a list).
|
||||
type Key = (&'static str, &'static str, Kind);
|
||||
|
||||
/// The keys of a set of resources (`FontSet`, `StyleSheetSet`, ...), whose list holds `entry`.
|
||||
const fn set(entry: Kind) -> [Key; 2] {
|
||||
[("Resources", "0", entry), ("DisplayList", "1", Kind::Other)]
|
||||
}
|
||||
|
||||
const FONT_SET: [Key; 2] = set(Kind::FontEntry);
|
||||
const KINSOKU_SET: [Key; 2] = set(Kind::KinsokuEntry);
|
||||
const CHAR_SHEET_SET: [Key; 2] = set(Kind::CharSheetEntry);
|
||||
const PARA_SHEET_SET: [Key; 2] = set(Kind::ParaSheetEntry);
|
||||
const FRAME_SET: [Key; 2] = set(Kind::FrameEntry);
|
||||
|
||||
/// The character features the reader looks at.
|
||||
const CHAR_FEATURES: [Key; 20] = [
|
||||
("Font", "0", Kind::Other),
|
||||
("FontSize", "1", Kind::Other),
|
||||
("AutoLeading", "4", Kind::Other),
|
||||
("Leading", "5", Kind::Other),
|
||||
("HorizontalScale", "6", Kind::Other),
|
||||
("VerticalScale", "7", Kind::Other),
|
||||
("Tracking", "8", Kind::Other),
|
||||
("BaselineShift", "9", Kind::Other),
|
||||
("FontCaps", "12", Kind::Other),
|
||||
("BaselineDirection", "35", Kind::Other),
|
||||
("LeftAki", "49", Kind::Other),
|
||||
("RightAki", "50", Kind::Other),
|
||||
("FillColor", "53", Kind::Paint),
|
||||
("StrokeColor", "54", Kind::Paint),
|
||||
("FillFlag", "56", Kind::Other),
|
||||
("StrokeFlag", "57", Kind::Other),
|
||||
("LineCap", "61", Kind::Other),
|
||||
("LineJoin", "62", Kind::Other),
|
||||
("LineWidth", "63", Kind::Other),
|
||||
("MiterLimit", "64", Kind::Other),
|
||||
];
|
||||
|
||||
/// The paragraph features the reader looks at.
|
||||
const PARA_FEATURES: [Key; 22] = [
|
||||
("Justification", "0", Kind::Other),
|
||||
("FirstLineIndent", "1", Kind::Other),
|
||||
("StartIndent", "2", Kind::Other),
|
||||
("EndIndent", "3", Kind::Other),
|
||||
("SpaceBefore", "4", Kind::Other),
|
||||
("SpaceAfter", "5", Kind::Other),
|
||||
("AutoLeading", "7", Kind::Other),
|
||||
("AutoHyphenate", "9", Kind::Other),
|
||||
("HyphenatedWordSize", "10", Kind::Other),
|
||||
("PreHyphen", "11", Kind::Other),
|
||||
("PostHyphen", "12", Kind::Other),
|
||||
("ConsecutiveHyphens", "13", Kind::Other),
|
||||
("Zone", "14", Kind::Other),
|
||||
("HyphenateCapitalized", "15", Kind::Other),
|
||||
("KeepTogether", "23", Kind::Other),
|
||||
("BurasagariType", "24", Kind::Other),
|
||||
("KinsokuOrder", "25", Kind::Other),
|
||||
("Kinsoku", "27", Kind::Other),
|
||||
("TabStops", "30", Kind::TabStops),
|
||||
("DefaultTabWidth", "31", Kind::Other),
|
||||
("DefaultStyle", "32", Kind::Other),
|
||||
("ParagraphDirection", "33", Kind::Other),
|
||||
];
|
||||
|
||||
/// The keys of a strike of the layout. A glyph strike has no children; its own keys start at 5. Its
|
||||
/// glyph data (key 21) has no name here: the public list above does not name it, and the files
|
||||
/// checked do not write it by name.
|
||||
const STRIKE: [Key; 5] = [
|
||||
("StreamTag", "99", Kind::Other),
|
||||
("Transform", "0", Kind::Transform),
|
||||
("Bounds", "1", Kind::Other),
|
||||
("ChildProcession", "5", Kind::Other),
|
||||
("Children", "6", Kind::Strike),
|
||||
];
|
||||
const GLYPH_STRIKE: [Key; 3] = [("StreamTag", "99", Kind::Other), ("Transform", "0", Kind::Transform), ("Bounds", "1", Kind::Other)];
|
||||
|
||||
/// The long names of the strikes' kinds, with the short ones later versions write.
|
||||
const STRIKE_KINDS: [(&str, &str); 6] =
|
||||
[("PathSelectGroupCharacter", "PC"), ("FrameStrike", "F"), ("RowColStrike", "R"), ("LineStrike", "L"), ("Segment", "S"), ("GlyphStrike", "G")];
|
||||
|
||||
impl Kind {
|
||||
/// The keys of a dictionary of this kind; `tag` is the kind of typed node it is, for a strike.
|
||||
fn keys(self, tag: Option<&str>) -> &'static [Key] {
|
||||
use Kind as K;
|
||||
match self {
|
||||
K::Root => &[("DocumentResources", "0", K::Resources), ("DocumentObjects", "1", K::Objects)],
|
||||
K::Resources => &[
|
||||
("FontSet", "1", K::FontSet),
|
||||
("KinsokuSet", "4", K::KinsokuSet),
|
||||
("StyleSheetSet", "5", K::CharSheetSet),
|
||||
("ParagraphSheetSet", "6", K::ParaSheetSet),
|
||||
("TextFrameSet", "8", K::FrameSet),
|
||||
],
|
||||
K::Objects => &[
|
||||
("DocumentSettings", "0", K::Other),
|
||||
("TextObjects", "1", K::TextObject),
|
||||
("OriginalNormalStyleFeatures", "2", K::CharFeatures),
|
||||
("OriginalNormalParagraphFeatures", "3", K::ParaFeatures),
|
||||
],
|
||||
K::FontSet => &FONT_SET,
|
||||
K::FontEntry => &[("Resource", "0", K::Font)],
|
||||
K::Font => &[("StreamTag", "99", K::Other), ("Identifier", "0", K::FontRecord)],
|
||||
K::FontRecord => &[("Name", "0", K::Other), ("Type", "2", K::Other), ("MMAxis", "4", K::Other), ("VersionString", "5", K::Other)],
|
||||
K::KinsokuSet => &KINSOKU_SET,
|
||||
K::KinsokuEntry => &[("Resource", "0", K::Kinsoku)],
|
||||
K::Kinsoku => &[("Name", "0", K::Other), ("Data", "5", K::Other)],
|
||||
K::CharSheetSet => &CHAR_SHEET_SET,
|
||||
K::CharSheetEntry => &[("Resource", "0", K::CharSheet)],
|
||||
K::CharSheet => &[("Name", "0", K::Other), ("Parent", "5", K::Other), ("Features", "6", K::CharFeatures)],
|
||||
K::ParaSheetSet => &PARA_SHEET_SET,
|
||||
K::ParaSheetEntry => &[("Resource", "0", K::ParaSheet)],
|
||||
K::ParaSheet => &[("Name", "0", K::Other), ("Features", "5", K::ParaFeatures), ("Parent", "6", K::Other)],
|
||||
K::FrameSet => &FRAME_SET,
|
||||
K::FrameEntry => &[("Resource", "0", K::Frame)],
|
||||
K::Frame => &[("Point", "0", K::Other), ("Bezier", "1", K::Bezier), ("Data", "2", K::FrameData)],
|
||||
K::Bezier => &[("Points", "0", K::Other)],
|
||||
K::FrameData => &[
|
||||
("Type", "0", K::Other),
|
||||
("LineOrientation", "1", K::Other),
|
||||
("FrameMatrix", "2", K::Other),
|
||||
("RowCount", "3", K::Other),
|
||||
("ColumnCount", "4", K::Other),
|
||||
("TextOnPathTRange", "6", K::Other),
|
||||
("RowGutter", "7", K::Other),
|
||||
("ColumnGutter", "8", K::Other),
|
||||
("FirstBaselineAlignment", "10", K::FirstBaseline),
|
||||
("PathData", "11", K::PathOptions),
|
||||
],
|
||||
K::FirstBaseline => &[("Flag", "0", K::Other), ("Min", "1", K::Other)],
|
||||
K::PathOptions => &[("Flip", "0", K::Other), ("Effect", "1", K::Other), ("Alignment", "2", K::Other), ("CS3Behavior", "6", K::Other)],
|
||||
K::TextObject => &[("Model", "0", K::Model), ("View", "1", K::View)],
|
||||
K::Model => &[("Text", "0", K::Other), ("ParagraphRun", "5", K::ParaRuns), ("StyleRun", "6", K::CharRuns), ("KernRun", "8", K::KernRuns)],
|
||||
K::ParaRuns => &[("RunArray", "0", K::ParaRun)],
|
||||
K::ParaRun => &[("RunData", "0", K::ParaRunData), ("Length", "1", K::Other)],
|
||||
K::ParaRunData => &[("ParagraphSheet", "0", K::ParaSheet)],
|
||||
K::CharRuns => &[("RunArray", "0", K::CharRun)],
|
||||
K::CharRun => &[("RunData", "0", K::CharRunData), ("Length", "1", K::Other)],
|
||||
K::CharRunData => &[("StyleSheet", "0", K::CharSheet)],
|
||||
K::KernRuns => &[("RunArray", "0", K::KernRun)],
|
||||
K::KernRun => &[("RunData", "0", K::KernRunData), ("Length", "1", K::Other)],
|
||||
K::KernRunData => &[("ManualKern", "0", K::Other)],
|
||||
K::View => &[("Frames", "0", K::FrameRef), ("Strikes", "2", K::Strike)],
|
||||
K::FrameRef => &[("Resource", "0", K::Other)],
|
||||
K::Strike if matches!(tag, Some("GlyphStrike" | "G")) => &GLYPH_STRIKE,
|
||||
K::Strike => &STRIKE,
|
||||
K::Transform => &[("Origin", "0", K::Other)],
|
||||
K::CharFeatures => &CHAR_FEATURES,
|
||||
K::ParaFeatures => &PARA_FEATURES,
|
||||
K::TabStops => &[("TabStops", "0", K::TabStop)],
|
||||
K::TabStop => &[("TabAdvance", "0", K::Other), ("TabType", "1", K::Other)],
|
||||
K::Paint => &[("StreamTag", "99", K::Other), ("Color", "0", K::Color), ("CAIKnownStyleID", "5", K::Other)],
|
||||
K::Color => &[("Type", "0", K::Other), ("Values", "1", K::Other)],
|
||||
K::Other => &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The text document `doc` (its top-level keys) with the keys it writes by name given their
|
||||
/// numbers, as later versions write them.
|
||||
pub(super) fn numbered(doc: Val) -> Val {
|
||||
value(doc, Kind::Root)
|
||||
}
|
||||
|
||||
/// `v`, whose dictionaries are of kind `kind`, with its keys numbered.
|
||||
fn value(v: Val, kind: Kind) -> Val {
|
||||
match v {
|
||||
Val::Dict(d) if kind != Kind::Other => Val::Dict(dict(d, kind)),
|
||||
Val::List(l) if kind != Kind::Other => Val::List(l.into_iter().map(|x| value(x, kind)).collect()),
|
||||
v => v,
|
||||
}
|
||||
}
|
||||
|
||||
/// A run's style written by name as the number `n` of a paragraph style (`kind` `ParaSheet`) or a
|
||||
/// character style (`CharSheet`) of the document: a style with nothing of its own, based on that
|
||||
/// one.
|
||||
fn based_on(kind: Kind, n: f64) -> Option<Val> {
|
||||
let parent = match kind {
|
||||
Kind::ParaSheet => "6",
|
||||
Kind::CharSheet => "5",
|
||||
_ => return None,
|
||||
};
|
||||
Some(Val::Dict(BTreeMap::from([(parent.to_string(), Val::Num(n))])))
|
||||
}
|
||||
|
||||
/// The entries of a dictionary of kind `kind` with their keys numbered.
|
||||
fn dict(d: BTreeMap<String, Val>, kind: Kind) -> BTreeMap<String, Val> {
|
||||
let tag = match d.get("StreamTag").or_else(|| d.get("99")) {
|
||||
Some(Val::Name(n)) => Some(n.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let keys = kind.keys(tag.as_deref());
|
||||
let mut out = BTreeMap::new();
|
||||
let mut named = vec![];
|
||||
for (k, v) in d {
|
||||
match keys.iter().find(|(name, number, _)| *name == k || *number == k) {
|
||||
Some((name, number, child)) => {
|
||||
let v = match (*number, v) {
|
||||
("99", Val::Name(n)) => Val::Name(STRIKE_KINDS.iter().find(|(long, _)| *long == n).map_or(n, |(_, short)| short.to_string())),
|
||||
(_, Val::Num(n)) if k == *name => based_on(*child, n).unwrap_or(Val::Num(n)),
|
||||
(_, v) => value(v, *child),
|
||||
};
|
||||
if k == *name {
|
||||
named.push((number.to_string(), v));
|
||||
} else {
|
||||
out.insert(k, v);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
out.insert(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (k, v) in named {
|
||||
out.entry(k).or_insert(v);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::read;
|
||||
use super::*;
|
||||
|
||||
fn parse(s: &str) -> Val {
|
||||
read(s.as_bytes()).unwrap_or_else(|| panic!("{s}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_keys_take_the_numbers_of_the_dictionary_they_are_in() {
|
||||
// `Leading` is 5 in a character style and 11 in a line; `Name` is 0 in a style and in a font
|
||||
// record.
|
||||
let named = parse(
|
||||
"/DocumentResources << /FontSet << /Resources [ << /Resource << /StreamTag /CoolTypeFont /Identifier << /Name (Serif) \
|
||||
/VersionString (Version 2) >> >> >> ] >> /StyleSheetSet << /Resources [ << /Resource << /Name (Red) /Parent 0 \
|
||||
/Features << /Leading 18.0 /FillColor << /StreamTag /SimplePaint /Color << /Type 1 /Values [ 1.0 1.0 0.0 0.0 ] >> >> >> >> >> ] >> >> \
|
||||
/DocumentObjects << /TextObjects [ << /Model << /Text (Hi) /ParagraphRun << /RunArray [ << /RunData << /ParagraphSheet 1 >> /Length 2 >> ] >> \
|
||||
/StyleRun << /RunArray [ << /RunData << /StyleSheet << /Parent 0 /Features << /FontSize 9.0 >> >> >> /Length 2 >> ] >> >> \
|
||||
/View << /Frames [ << /Resource 0 >> ] /Strikes [ << /StreamTag /FrameStrike /Transform << /Origin [ 1.0 2.0 ] >> \
|
||||
/Children [ << /StreamTag /LineStrike /Leading 14.4 /Children [ << /StreamTag /GlyphStrike /Glyphs [ 1 2 ] >> ] >> ] >> ] >> >> ] >>",
|
||||
);
|
||||
let numbered_form = parse(
|
||||
"/0 << /1 << /0 [ << /0 << /99 /CoolTypeFont /0 << /0 (Serif) /5 (Version 2) >> >> >> ] >> /5 << /0 [ << /0 << /0 (Red) /5 0 \
|
||||
/6 << /5 18.0 /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 1.0 0.0 0.0 ] >> >> >> >> >> ] >> >> \
|
||||
/1 << /1 [ << /0 << /0 (Hi) /5 << /0 [ << /0 << /0 << /6 1 >> >> /1 2 >> ] >> \
|
||||
/6 << /0 [ << /0 << /0 << /5 0 /6 << /1 9.0 >> >> >> /1 2 >> ] >> >> \
|
||||
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /F /0 << /0 [ 1.0 2.0 ] >> \
|
||||
/6 [ << /99 /L /Leading 14.4 /6 [ << /99 /G /Glyphs [ 1 2 ] >> ] >> ] >> ] >> >> ] >>",
|
||||
);
|
||||
// A character style's `Leading` is its key 5; a line's and a glyph's keys the reader doesn't
|
||||
// look at keep their names.
|
||||
assert_eq!(numbered(named), numbered_form);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_wins_over_the_same_key_by_name() {
|
||||
let doc = numbered(parse("/1 << /3 << /33 1 /ParagraphDirection 0 /Justification 2 >> >>"));
|
||||
assert_eq!(doc, parse("/1 << /3 << /33 1 /0 2 >> >>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_of_dictionaries_no_reader_looks_at_keep_their_names() {
|
||||
let doc = numbered(parse("/DocumentObjects << /DocumentSettings << /Name (x) /Leading 3 >> /Elsewhere << /Name (y) >> >>"));
|
||||
assert_eq!(doc, parse("/1 << /0 << /Name (x) /Leading 3 >> /Elsewhere << /Name (y) >> >>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_numbered_document_stays_as_it_is() {
|
||||
let s = "/0 << /1 << /0 [ << /0 << /99 /CoolTypeFont /0 << /0 (Serif) >> >> >> ] >> >> \
|
||||
/1 << /1 [ << /0 << /0 (Hi) /5 << /0 [ << /0 << /0 1 >> /1 2 >> ] >> /6 << /0 [ << /0 << /0 0 >> /1 2 >> ] >> >> \
|
||||
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 1.0 2.0 ] >> >> ] >> ] >> >> ] /2 << /1 12.0 >> >>";
|
||||
// A run's style written as a number under its key's number stays a number.
|
||||
assert_eq!(numbered(parse(s)), parse(s));
|
||||
}
|
||||
}
|
||||
@@ -2197,6 +2197,34 @@ fn an_ai_file_gets_its_layers_and_the_art_outside_its_artboard() {
|
||||
assert!(!d.layers[2].visible);
|
||||
}
|
||||
|
||||
/// A `.ai` of versions 10 to 13, whose symbol instances are placed by a `TransformMatrix` on the
|
||||
/// canvas, opens from its layers: the art outside its artboard, an instance among it, comes in,
|
||||
/// rather than the PDF part alone, which has none of it.
|
||||
#[test]
|
||||
fn an_older_ai_files_symbols_keep_its_layers_and_the_art_outside_its_artboard() {
|
||||
// The template box's center is (50.5, 50.5): art space's origin is at canvas (8141, 8242). The
|
||||
// instance puts Box at (150, 50) in art space, right of the artboard (x 0 to 100).
|
||||
let instance = "/SymbolInstance :\n(Box) /SymbolRef ,\n1 0 0 1 8291 8192 /TransformMatrix\n;\n9 () XW";
|
||||
let layers = format!(
|
||||
"{}{}{}",
|
||||
stroked_box_symbol(),
|
||||
layer("Jig", true, &square(10, 10)),
|
||||
layer("Parts", true, &format!("{}\n{instance}", square(30, 110)))
|
||||
);
|
||||
let art = native(&layers).replacen("%AI5_NumLayers", "%AI3_TemplateBox: 50.5 50.5 50.5 50.5\n%AI5_NumLayers", 1);
|
||||
let (d, warnings, read) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, false, 1.0);
|
||||
assert!(read, "{warnings:?}");
|
||||
assert_eq!(names(&d), ["Jig", "Parts"], "{warnings:?}");
|
||||
let parts = d.layers[1].children().unwrap();
|
||||
let above = parts[0].visual_bounds().unwrap();
|
||||
assert!(above.y1 <= 1e-6, "the square above the artboard is kept, outside it: {above:?}");
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &parts[1].kind else { panic!("an instance: {:?} {warnings:?}", parts[1].kind) };
|
||||
assert_eq!(symbol, "Box");
|
||||
let b = parts[1].visual_bounds_with(&d.symbol_boxes()).unwrap();
|
||||
let near = [b.x0 - 149.0, b.y0 - 49.5, b.x1 - 151.0, b.y1 - 50.5].iter().all(|v| v.abs() < 0.3);
|
||||
assert!(near, "the instance right of the artboard: {b:?}");
|
||||
}
|
||||
|
||||
/// A `.ai` whose PDF part was read in points from a page of 10 points a unit (its `UserUnit`), and
|
||||
/// whose editing data has the page in those units: its layers come in at the page's size, ten
|
||||
/// times as large as the editing data has them, with stroke weights and dashes ten times as large.
|
||||
@@ -3169,6 +3197,29 @@ fn text_document(stories: &[Story<'_>]) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// [`text_document`] with its keys written by name, as files saved for version 11 write them: a
|
||||
/// typed node's kind under `/StreamTag`, the strikes' kinds by their long names.
|
||||
fn named_text_document(stories: &[Story<'_>]) -> String {
|
||||
let story = |(text, align, anchor, _t, start): &Story<'_>| {
|
||||
let n = text.chars().count();
|
||||
format!(
|
||||
"<< /Model << /Text ({text}) /ParagraphRun << /RunArray [ << /RunData << /ParagraphSheet << /Name () /Features << /Justification {align} >> /Parent 0 >> >> /Length {n} >> ] >> \
|
||||
/StyleRun << /RunArray [ << /RunData << /StyleSheet << /Name () /Parent 0 /Features << /Font 0 /FontSize 14.0 /FillColor << /StreamTag /CAITextPaint /Color << /Type 2 /Values [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /Length {n} >> ] >> >> \
|
||||
/View << /Frames [ << /Resource 0 >> ] /Strikes [ << /StreamTag /PathSelectGroupCharacter /Children [ << /StreamTag /FrameStrike /Transform << /Origin [ {} {} ] >> \
|
||||
/Children [ << /StreamTag /RowColStrike /Children [ << /StreamTag /RowColStrike /Children [ << /StreamTag /LineStrike /Children [ \
|
||||
<< /StreamTag /Segment /Transform << /Origin [ {start} 0.0 ] >> /Mapping << /CharacterCount {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>",
|
||||
anchor.0, anchor.1
|
||||
)
|
||||
};
|
||||
let frame = |(_, _, _, t, _): &Story<'_>| format!("<< /Resource << /Point [ 0 0 ] /Data << /FrameMatrix [ 1 0 0 1 {} {} ] >> >> >>", t.0, t.1);
|
||||
format!(
|
||||
"/DocumentResources << /FontSet << /Resources [ << /Resource << /StreamTag /CoolTypeFont /Identifier << /Name (Helvetica) >> >> >> ] >> \
|
||||
/TextFrameSet << /Resources [ {} ] >> >>\n/DocumentObjects << /TextObjects [ {} ] /OriginalNormalStyleFeatures << /FontSize 12.0 >> >>\n",
|
||||
stories.iter().map(frame).collect::<Vec<_>>().join(" "),
|
||||
stories.iter().map(story).collect::<Vec<_>>().join(" ")
|
||||
)
|
||||
}
|
||||
|
||||
/// The editing copy of a 100 × 100 file with `layers` and the text `document`; its template box is
|
||||
/// centred at (50, 50).
|
||||
fn native_with_text(layers: &str, document: &str) -> String {
|
||||
@@ -3319,6 +3370,8 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() {
|
||||
// A record whose name differs from the copies' in punctuation alone still picks its version.
|
||||
assert_eq!(version("/0 (Vertest-Ink-Regular) /5 (1.1)"), "1.1");
|
||||
assert_eq!(version("/0 (Vertest-Ink-Regular)"), "1.0");
|
||||
// Files saved for versions older than the key write it by name among the numbered ones.
|
||||
assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1");
|
||||
}
|
||||
|
||||
/// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character
|
||||
@@ -3728,6 +3781,81 @@ fn shown_type_keeps_the_pages_and_type_off_the_page_comes_from_the_text_document
|
||||
assert!(!r.warnings.iter().any(|w| w.contains("order the page paints")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_document_with_named_keys_gives_type_off_the_page_too() {
|
||||
// Files saved for version 11 write the text document's keys by name. Story 1 is off the page:
|
||||
// only the text document has it, and story 0 stays in its own text object.
|
||||
let stories = [("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Away\r", 0, (8300.0, 8180.0), (0.0, 0.0), 0.0)];
|
||||
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &named_text_document(&stories));
|
||||
let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 58.5 61.5 moveto (Hi there) show";
|
||||
let r = import(&eps(page, &art)).unwrap();
|
||||
let texts = text_of(&r.document.layers[0]);
|
||||
assert_eq!(texts.iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["Hi there", "Away"], "{:?}", r.warnings);
|
||||
let x = |t: &vectorcraft_doc::TextObject| t.xf.as_coeffs()[4];
|
||||
assert!((x(texts[0]) - 58.5).abs() < 1e-6 && (x(texts[1]) - 158.5).abs() < 1e-6, "{:?} {:?}", texts[0].xf, texts[1].xf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_document_with_named_keys_reads_as_the_same_one_with_numbers() {
|
||||
// Type on a hidden layer comes only from the text document: its styles, paints, frames and
|
||||
// layout read the same whichever way its keys are written.
|
||||
let stories = [("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)];
|
||||
let spare = |doc: &str| {
|
||||
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &(text_object(0) + &text_object(1)))), doc);
|
||||
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
|
||||
let texts: Vec<vectorcraft_doc::TextObject> = text_of(&r.document.layers[1]).into_iter().cloned().collect();
|
||||
(texts, r.warnings)
|
||||
};
|
||||
let (numbered, _) = spare(&text_document(&stories));
|
||||
let (named, warnings) = spare(&named_text_document(&stories));
|
||||
assert_eq!(numbered.len(), 2);
|
||||
assert_eq!(named, numbered, "{warnings:?}");
|
||||
assert_eq!(named[1].para.justify, vectorcraft_doc::Justify::Center);
|
||||
let magenta = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(0.0, 1.0, 0.0, 0.0));
|
||||
assert_eq!(named[0].runs[0].style.fill, magenta);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_document_with_named_keys_takes_a_runs_style_by_its_number() {
|
||||
// Files saved for version 11 name a run's paragraph and character styles by their numbers in the
|
||||
// document's style sets, and give point type a curve of four equal points. Styles 1 center the
|
||||
// paragraph and paint the type magenta; paragraph style 2 sets its direction right to left.
|
||||
let magenta = "<< /StreamTag /CAITextPaint /Color << /Type 2 /Values [ 1.0 0.0 1.0 0.0 0.0 ] >> >>";
|
||||
let story = |text: &str, para: u8, chars: u8, x: f64| {
|
||||
let n = text.chars().count();
|
||||
format!(
|
||||
"<< /Model << /Text ({text}) /ParagraphRun << /RunArray [ << /RunData << /ParagraphSheet {para} >> /Length {n} >> ] >> \
|
||||
/StyleRun << /RunArray [ << /RunData << /StyleSheet {chars} >> /Length {n} >> ] >> >> \
|
||||
/View << /Frames [ << /Resource 0 >> ] /Strikes [ << /StreamTag /PathSelectGroupCharacter /Children [ << /StreamTag /FrameStrike \
|
||||
/Transform << /Origin [ {x} 8180.0 ] >> /Children [ << /StreamTag /RowColStrike /Children [ << /StreamTag /RowColStrike /Children [ \
|
||||
<< /StreamTag /LineStrike /Children [ << /StreamTag /Segment /Transform << /Origin [ 0.0 0.0 ] >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>"
|
||||
)
|
||||
};
|
||||
let doc = format!(
|
||||
"/DocumentResources << /FontSet << /Resources [ << /Resource << /StreamTag /CoolTypeFont /Identifier << /Name (Helvetica) >> >> >> ] >> \
|
||||
/StyleSheetSet << /Resources [ << /Resource << /Name (Normal) /Features << /Font 0 /FontSize 14.0 >> >> >> \
|
||||
<< /Resource << /Name (Magenta) /Parent 0 /Features << /FillColor {magenta} >> >> >> ] >> \
|
||||
/ParagraphSheetSet << /Resources [ << /Resource << /Name (Normal) /Features << /Justification 0 >> >> >> \
|
||||
<< /Resource << /Name (Centered) /Parent 0 /Features << /Justification 2 >> >> >> \
|
||||
<< /Resource << /Name (Leftward) /Parent 0 /Features << /ParagraphDirection 1 >> >> >> ] >> \
|
||||
/TextFrameSet << /Resources [ << /Resource << /Bezier << /Points [ 8191.5 8191.5 8191.5 8191.5 8191.5 8191.5 8191.5 8191.5 ] >> \
|
||||
/Data << /Type 0 /FrameMatrix [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
|
||||
/DocumentObjects << /TextObjects [ {} {} ] /OriginalNormalStyleFeatures << /FontSize 12.0 >> >>\n",
|
||||
story("Mid\r", 1, 1, 8200.0),
|
||||
story("Back\r", 2, 0, 8300.0)
|
||||
);
|
||||
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &(text_object(0) + &text_object(1)))), &doc);
|
||||
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
|
||||
let texts = text_of(&r.document.layers[1]);
|
||||
assert_eq!(texts.iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["Mid", "Back"], "{:?}", r.warnings);
|
||||
assert_eq!(texts[0].para.justify, vectorcraft_doc::Justify::Center);
|
||||
let magenta = vectorcraft_color::Paint::solid(vectorcraft_color::Color::cmyk(0.0, 1.0, 0.0, 0.0));
|
||||
assert_eq!(texts[0].runs[0].style.fill, magenta);
|
||||
assert_eq!(texts[1].para.direction, Some(vectorcraft_doc::ParaDirection::RightToLeft));
|
||||
assert_eq!(texts[1].para.justify, vectorcraft_doc::Justify::Right);
|
||||
assert_ne!(texts[1].runs[0].style.fill, magenta);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_object_written_as_comments_is_read_like_any_other() {
|
||||
let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
|
||||
|
||||
@@ -1366,7 +1366,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.exportAs",
|
||||
"Export As…",
|
||||
"",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, as document.export refuses it",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
|
||||
),
|
||||
(
|
||||
"ui.fileInfoDialog",
|
||||
@@ -1737,7 +1737,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.runInstalledScript",
|
||||
"Run Script",
|
||||
"",
|
||||
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (the script is checked again, then script.run runs it by its path, so its #include lines and $.evalFile read beside it), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again",
|
||||
"{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again",
|
||||
),
|
||||
(
|
||||
"ui.checkScript",
|
||||
|
||||
@@ -139,6 +139,7 @@ impl Exporter<'_> {
|
||||
let doc = self.doc;
|
||||
let out = self.out.clone();
|
||||
let profiles = !out.standard.cmyk_only();
|
||||
let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit });
|
||||
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 {
|
||||
@@ -148,12 +149,14 @@ impl Exporter<'_> {
|
||||
let icc = out.cmyk_image_icc(blob);
|
||||
crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref())
|
||||
} else {
|
||||
crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles)
|
||||
crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles, to_srgb)
|
||||
};
|
||||
if let Some(w) = r.warning {
|
||||
let img = r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles));
|
||||
// An image left out gets the warning below instead.
|
||||
for w in [r.warning, r.note].into_iter().flatten().filter(|_| img.is_some()) {
|
||||
self.warn(w);
|
||||
}
|
||||
r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles))
|
||||
img
|
||||
});
|
||||
if img.is_none() {
|
||||
self.warn(UNDECODED);
|
||||
|
||||
+179
-19
@@ -6,6 +6,13 @@
|
||||
//! monochrome (greyscale that is only black and white). An image already as asked (not resampled,
|
||||
//! a JPEG kept as JPEG or another kept lossless) is embedded as it is; the others are decoded,
|
||||
//! resampled and encoded again. JPEG needs opaque pixels: images with transparency stay lossless.
|
||||
//! A gray or RGB image that carries a profile the Output settings convert from ([`ToSrgb`]) is
|
||||
//! always decoded: its pixels are converted to sRGB and written without the profile, at 16 bits a
|
||||
//! sample when it has them and is otherwise kept as it is; a JPEG kept as JPEG whose samples the
|
||||
//! conversion leaves unchanged (an sRGB profile) keeps its JPEG data. A black-and-white image whose
|
||||
//! converted levels are grey is compressed as greyscale. A colour image the Output settings also
|
||||
//! convert to their destination ([`Pixels`]) goes from its profile to sRGB, then to the
|
||||
//! destination; a grey one keeps its profile there, as grey pixels are not converted.
|
||||
//!
|
||||
//! CMYK images ([`ImageBlob::cmyk`]) stay CMYK: a CMYK JPEG already as asked is embedded as it is
|
||||
//! when its numbers are kept; the others' ink amounts are resampled, converted when the Output
|
||||
@@ -22,6 +29,7 @@ use image::imageops::FilterType;
|
||||
use image::{DynamicImage, ExtendedColorType, ImageDecoder, ImageFormat, ImageReader};
|
||||
use krilla::image::{BitsPerComponent, CustomImage, Image, ImageColorspace};
|
||||
|
||||
use vectorcraft_color::cms::{IccProfile, Intent};
|
||||
use vectorcraft_doc::ImageBlob;
|
||||
use vectorcraft_doc::cmyk::{Inks, jpeg_components};
|
||||
use vectorcraft_doc::resample::{Resample, premultiply, resized, unpremultiply};
|
||||
@@ -306,6 +314,100 @@ pub(crate) struct Recoded {
|
||||
pub image: Option<Image>,
|
||||
/// Set when the image isn't compressed as asked.
|
||||
pub warning: Option<&'static str>,
|
||||
/// Set when the image's colors are converted to the destination without its ICC profile,
|
||||
/// which can't be read.
|
||||
pub note: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB (Convert to
|
||||
/// Destination, [`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB,
|
||||
/// else the step before the image's [`Pixels`] conversion.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct ToSrgb {
|
||||
/// The rendering intent of the conversion.
|
||||
pub intent: Intent,
|
||||
/// 16-bit samples may be written (PDF 1.5 and later).
|
||||
pub sixteen_bit: bool,
|
||||
}
|
||||
|
||||
/// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of
|
||||
/// colour space `space` (`GRAY` or `RGB `, [`valid_icc`]): `None` without one, `Some(None)` when
|
||||
/// the CMS can't read it.
|
||||
fn source_profile(bytes: &[u8], space: [u8; 4]) -> Option<Option<IccProfile>> {
|
||||
let icc = source_icc(bytes).filter(|icc| valid_icc(icc, space))?;
|
||||
Some(IccProfile::from_bytes(None, &icc).ok())
|
||||
}
|
||||
|
||||
const UNCONVERTED: &str = "an image's ICC profile couldn't be read: the image keeps it and is not converted to sRGB";
|
||||
const CONVERTED_AS_SRGB: &str = "an image's ICC profile couldn't be read: its colors are converted to the destination as sRGB";
|
||||
|
||||
const UNDECODED: &str = "an image couldn't be decoded and is not converted to sRGB";
|
||||
|
||||
/// `img` converted from ICC profile `p` to sRGB with `intent`: at 16 bits a sample when it has
|
||||
/// more than 8, else at 8, with its alpha; and whether any sample changed. A grey image stays grey, each level as the sRGB grey it converts to. `None` when the
|
||||
/// pixels can't be converted.
|
||||
fn into_srgb(img: DynamicImage, p: &IccProfile, intent: Intent) -> Option<(DynamicImage, bool)> {
|
||||
let kind = img.color();
|
||||
let deep = kind.bits_per_pixel() > 8 * u16::from(kind.channel_count());
|
||||
let to8 = |v: f32| v.round() as u8;
|
||||
let to16 = |v: f32| v.round() as u16;
|
||||
Some(match (kind.has_color(), deep) {
|
||||
(true, true) => {
|
||||
let mut s = img.into_rgba16();
|
||||
let changed = convert_samples(&mut s, 3, p, intent, 65_535.0, to16)?;
|
||||
(DynamicImage::ImageRgba16(s), changed)
|
||||
}
|
||||
(true, false) => {
|
||||
let mut s = img.into_rgba8();
|
||||
let changed = convert_samples(&mut s, 3, p, intent, 255.0, to8)?;
|
||||
(DynamicImage::ImageRgba8(s), changed)
|
||||
}
|
||||
(false, true) => {
|
||||
let mut s = img.into_luma_alpha16();
|
||||
let changed = convert_samples(&mut s, 1, p, intent, 65_535.0, to16)?;
|
||||
(DynamicImage::ImageLumaA16(s), changed)
|
||||
}
|
||||
(false, false) => {
|
||||
let mut s = img.into_luma_alpha8();
|
||||
let changed = convert_samples(&mut s, 1, p, intent, 255.0, to8)?;
|
||||
(DynamicImage::ImageLumaA8(s), changed)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Convert the `n` colour samples (1: grey, 3: RGB) of each pixel of `samples` (followed by an
|
||||
/// alpha sample each, which is left as it is) from ICC profile `p` to sRGB with `intent`, a run of
|
||||
/// pixels at a time; `max` is a sample's largest value, `back` turns a value of 0 to `max` into a
|
||||
/// sample. Grey pixels take the mean of the sRGB values. Whether any sample changed; `None` when
|
||||
/// the transform fails.
|
||||
fn convert_samples<T: Copy + PartialEq + Into<f32>>(
|
||||
samples: &mut [T],
|
||||
n: usize,
|
||||
p: &IccProfile,
|
||||
intent: Intent,
|
||||
max: f32,
|
||||
back: impl Fn(f32) -> T,
|
||||
) -> Option<bool> {
|
||||
const RUN: usize = 4096;
|
||||
let mut src = Vec::with_capacity(RUN * n);
|
||||
let mut dst = vec![0.0f32; RUN * 3];
|
||||
let mut changed = false;
|
||||
for run in samples.chunks_mut(RUN * (n + 1)) {
|
||||
src.clear();
|
||||
src.extend(run.chunks_exact(n + 1).flat_map(|px| px.iter().take(n).map(|v| (*v).into() / max)));
|
||||
let out = dst.get_mut(..src.len() / n * 3)?;
|
||||
p.to_srgb_pixels(&src, out, intent)?;
|
||||
for (px, rgb) in run.chunks_exact_mut(n + 1).zip(out.as_chunks::<3>().0) {
|
||||
let grey = [rgb.iter().sum::<f32>() / 3.0];
|
||||
let values: &[f32] = if n == 1 { &grey } else { rgb };
|
||||
for (v, c) in px.iter_mut().zip(values) {
|
||||
let new = back(c * max);
|
||||
changed |= new != *v;
|
||||
*v = new;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
|
||||
/// Is `img` (a grey image) only black and white?
|
||||
@@ -372,8 +474,11 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic
|
||||
/// 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
|
||||
/// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces).
|
||||
/// `interpolate` lets viewers smooth it. An image that can't be decoded is kept as it is.
|
||||
/// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces);
|
||||
/// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB
|
||||
/// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as
|
||||
/// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be
|
||||
/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB.
|
||||
pub(crate) fn recode(
|
||||
bytes: &[u8],
|
||||
size: (f64, f64),
|
||||
@@ -381,39 +486,94 @@ pub(crate) fn recode(
|
||||
interpolate: bool,
|
||||
convert: Option<&Pixels>,
|
||||
profiles: bool,
|
||||
to_srgb: Option<ToSrgb>,
|
||||
) -> Recoded {
|
||||
let keep = Recoded { image: None, warning: None };
|
||||
let keep = Recoded { image: None, warning: None, note: None };
|
||||
let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep };
|
||||
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);
|
||||
// Pixels in a profile they are converted from are decoded, whatever the Compression settings.
|
||||
// Grey pixels, which `convert` leaves as they are, keep their profile when it converts.
|
||||
let to_srgb = to_srgb.filter(|_| !(grey && convert.is_some()));
|
||||
// Converted to the destination as sRGB, as before, when the profile can't be read.
|
||||
let mut note = None;
|
||||
let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) {
|
||||
Some((Some(p), t)) => Some((p, t)),
|
||||
Some((None, _)) if convert.is_some() => {
|
||||
note = Some(CONVERTED_AS_SRGB);
|
||||
None
|
||||
}
|
||||
Some((None, _)) => return Recoded { image: None, warning: Some(UNCONVERTED), note: None },
|
||||
None => None,
|
||||
};
|
||||
// Pixels that can't be decoded are kept as they are, with a warning when they were to be
|
||||
// converted.
|
||||
let keep = if source.is_some() { Recoded { image: None, warning: Some(UNDECODED), note: None } } else { keep };
|
||||
// What the header declares is decoded within the image allowance, not whatever it asks for.
|
||||
if decoder.set_limits(limits()).is_err() {
|
||||
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 (kind, pixels) = if grey {
|
||||
let (mut kind, pixels) = if grey {
|
||||
// Only the pixels tell monochrome images from greyscale ones: decoded unless both keep it.
|
||||
let (g, m) = (rule(c, Kind::Gray), rule(c, Kind::Mono));
|
||||
if kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead {
|
||||
return Recoded { image: None, warning: g.instead };
|
||||
if source.is_none() && kept(&g, dims, size, jpeg) && kept(&m, dims, size, jpeg) && g.instead == m.instead {
|
||||
return Recoded { image: None, warning: g.instead, note: None };
|
||||
}
|
||||
let Ok(img) = DynamicImage::from_decoder(decoder) else { return keep };
|
||||
(if bilevel(&img) { Kind::Mono } else { Kind::Gray }, Some(img))
|
||||
} else {
|
||||
(Kind::Color, None)
|
||||
};
|
||||
let rule = rule(c, kind);
|
||||
let mut rule = rule(c, kind);
|
||||
let convert = convert.filter(|_| kind == Kind::Color);
|
||||
if kept(&rule, dims, size, jpeg) && convert.is_none() {
|
||||
return Recoded { image: None, warning: rule.instead };
|
||||
if kept(&rule, dims, size, jpeg) && convert.is_none() && source.is_none() {
|
||||
return Recoded { image: None, warning: rule.instead, note: None };
|
||||
}
|
||||
let Some(mut img) = pixels.or_else(|| decoded(bytes)) else { return keep };
|
||||
if let Some((p, t)) = &source {
|
||||
let srgb = match into_srgb(img, p, t.intent) {
|
||||
Some(s) => Some(s),
|
||||
None if convert.is_some() => {
|
||||
// Converted to the destination as sRGB: decoded again (a colour image), as the
|
||||
// conversion took the pixels.
|
||||
note = Some(CONVERTED_AS_SRGB);
|
||||
None
|
||||
}
|
||||
None => return Recoded { image: None, warning: Some(UNCONVERTED), note: None },
|
||||
};
|
||||
img = match srgb {
|
||||
Some((srgb, changed)) => {
|
||||
// The converted levels of a black-and-white image may be grey.
|
||||
if kind == Kind::Mono && !bilevel(&srgb) {
|
||||
(kind, rule) = (Kind::Gray, self::rule(c, Kind::Gray));
|
||||
}
|
||||
// Written as it is only when nothing converts it further.
|
||||
let as_is = kept(&rule, dims, size, jpeg) && convert.is_none();
|
||||
// A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB
|
||||
// profile): its JPEG data, without the profile.
|
||||
if !changed && as_is && jpeg {
|
||||
let image = Image::from_jpeg_with_icc(bytes.to_vec().into(), None, interpolate).ok();
|
||||
return Recoded { image, warning: rule.instead, note: None };
|
||||
}
|
||||
// Not resampled and lossless: written at its own depth.
|
||||
if as_is && jpeg_quality(&rule, jpeg).is_none() {
|
||||
return Recoded { image: from_decoded(srgb, None, interpolate, t.sixteen_bit), warning: rule.instead, note: None };
|
||||
}
|
||||
srgb
|
||||
}
|
||||
None => {
|
||||
let Some(img) = decoded(bytes) else { return keep };
|
||||
img
|
||||
}
|
||||
};
|
||||
}
|
||||
let Some(img) = pixels.or_else(|| decoded(bytes)) else { return keep };
|
||||
// Pixels that keep their colours keep the profile they are in; converted ones are in the
|
||||
// destination's.
|
||||
let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" };
|
||||
let icc = (profiles && convert.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want));
|
||||
let icc = (profiles && convert.is_none() && source.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want));
|
||||
let rgb_icc = icc.is_some() && kind == Kind::Color;
|
||||
let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8();
|
||||
if kind == Kind::Mono {
|
||||
@@ -441,7 +601,7 @@ pub(crate) fn recode(
|
||||
to_jpeg(&samples, space, width, height, q, interpolate, icc.as_deref().map(Vec::as_slice))
|
||||
});
|
||||
let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert, icc));
|
||||
Recoded { image, warning: rule.instead }
|
||||
Recoded { image, warning: rule.instead, note }
|
||||
}
|
||||
|
||||
/// A colorized image's coverage (one sample a pixel, `w` × `h`, see
|
||||
@@ -492,16 +652,16 @@ pub(crate) fn recode_cmyk(
|
||||
let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS)
|
||||
.then(|| Image::from_jpeg_with_icc(blob.bytes.as_ref().clone().into(), icc.map(|i| i.to_vec().into()), interpolate).ok())
|
||||
.flatten();
|
||||
return Recoded { image, warning: rule.instead };
|
||||
return Recoded { image, warning: rule.instead, note: None };
|
||||
}
|
||||
}
|
||||
let Some(inks) = blob.cmyk() else {
|
||||
return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }) };
|
||||
return Recoded { image: None, warning: Some(if jpeg { CMYK_KEPT } else { CMYK_RGB }), note: None };
|
||||
};
|
||||
let (width, height) = sized(&rule, (inks.width, inks.height), size);
|
||||
let (inks, alpha) = match resampled_inks(inks, alpha, &rule, (width, height)) {
|
||||
Ok(r) => r,
|
||||
Err(warning) => return Recoded { image: None, warning },
|
||||
Err(warning) => return Recoded { image: None, warning, note: None },
|
||||
};
|
||||
let (samples, space) = match convert {
|
||||
Some(p) => p.convert(&inks),
|
||||
@@ -510,7 +670,7 @@ pub(crate) fn recode_cmyk(
|
||||
// JPEG needs opaque pixels.
|
||||
let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate, icc));
|
||||
let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate, icc));
|
||||
Recoded { image, warning: rule.instead }
|
||||
Recoded { image, warning: rule.instead, note: None }
|
||||
}
|
||||
|
||||
/// Ink amounts (four bytes a pixel) and their alpha (one byte a pixel), if any.
|
||||
|
||||
@@ -10,8 +10,12 @@
|
||||
//! colours of the other model (and Lab ones), keeping the numbers of those already in it.
|
||||
//! Grey stays grey. Images (and freeform gradients' images) are converted the same way, pixel
|
||||
//! by pixel (CMYK images too: they keep their numbers unless converted, see [`CmykPixels`]);
|
||||
//! printer's marks are not. The destination is a profile name; empty, the document's
|
||||
//! profile for its colour mode.
|
||||
//! printer's marks are not. With `destination` and an sRGB destination, a gray or RGB image
|
||||
//! that carries an ICC profile is converted from it to sRGB with the same intent and written
|
||||
//! without it ([`ColorOut::image_srgb_intent`]); with `destination` and a destination its
|
||||
//! pixels are converted to (CMYK, another RGB space), a colour image is converted from its
|
||||
//! profile to sRGB and then to the destination. Without conversion it keeps its profile. The
|
||||
//! destination is a profile name; empty, the document's profile for its colour mode.
|
||||
//! - Profiles ([`ProfileInclusion`]): with `all`, with `destination`, and with `taggedSource` on a
|
||||
//! document that was assigned profiles, colours are written in ICC-based colour spaces: CMYK
|
||||
//! with the CMYK profile in effect (the destination when converting to CMYK, else the
|
||||
@@ -50,6 +54,8 @@ struct Dest {
|
||||
keep: bool,
|
||||
/// The destination is sRGB (what images are).
|
||||
srgb: bool,
|
||||
/// Convert to Destination was asked for (not Preserve Numbers, nor PDF/X-1a's own conversion).
|
||||
destination: bool,
|
||||
}
|
||||
|
||||
/// How an export writes colours (see the module documentation).
|
||||
@@ -233,11 +239,12 @@ impl ColorOut {
|
||||
};
|
||||
let cms = Cms::new(&settings).map_err(|e| PdfError::BadSetting(format!("output.destination: {e}")))?;
|
||||
// PDF/X-1a converts without being asked: as Preserve Numbers does.
|
||||
let keep = set.output.conversion != ColorConversion::Destination || cms::canonical_name(&own) == name;
|
||||
let destination = set.output.conversion == ColorConversion::Destination;
|
||||
let keep = !destination || cms::canonical_name(&own) == name;
|
||||
if model == Model::Cmyk {
|
||||
out.cmyk_profile = name.clone();
|
||||
}
|
||||
out.dest = Some(Dest { srgb: name == cms::SRGB, cms, model, keep });
|
||||
out.dest = Some(Dest { srgb: name == cms::SRGB, cms, model, keep, destination });
|
||||
}
|
||||
out.tagged = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4)
|
||||
|| (!set.standard.cmyk_only()
|
||||
@@ -338,6 +345,18 @@ impl ColorOut {
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The intent a gray or RGB image that carries an ICC profile is converted from it to sRGB
|
||||
/// with ([`crate::images::recode`]): the colour settings' intent, with Convert to Destination
|
||||
/// and an sRGB destination, also when the document's RGB space is sRGB, or a destination
|
||||
/// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space).
|
||||
/// `None` otherwise, Preserve Numbers and an RGB destination that is the document's own RGB
|
||||
/// profile (which leaves RGB colours and RGB images as they are) included: such an image
|
||||
/// keeps its profile, or its numbers are converted as sRGB ones.
|
||||
pub(crate) fn image_srgb_intent(&self) -> Option<Intent> {
|
||||
let d = self.dest.as_ref().filter(|d| d.destination)?;
|
||||
((d.model == Model::Rgb && d.srgb) || self.pixels().is_some()).then_some(self.intent)
|
||||
}
|
||||
|
||||
/// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it
|
||||
/// carries, when its numbers are kept and the Profiles setting or the standard includes source
|
||||
/// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK.
|
||||
|
||||
@@ -297,6 +297,17 @@ impl Opened {
|
||||
bleed,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far page `index`'s (0-based) bleed box reaches past its trim box, `[top, bottom, left,
|
||||
/// right]` in points, as the page shows (rotated); `None` past the last page, and when the bleed
|
||||
/// box doesn't hold the trim box.
|
||||
pub fn page_bleed(&self, index: usize) -> Option<[f64; 4]> {
|
||||
let page = self.pdf.pages().get(index)?;
|
||||
let init = Affine::new(page.initial_transform(true).as_coeffs());
|
||||
let (trim, bleed) = (init.transform_rect_bbox(page_box(page, CropTo::Trim)), init.transform_rect_bbox(page_box(page, CropTo::Bleed)));
|
||||
let sides = [trim.y0 - bleed.y0, bleed.y1 - trim.y1, trim.x0 - bleed.x0, bleed.x1 - trim.x1];
|
||||
sides.iter().all(|b| b.is_finite() && *b >= 0.0).then_some(sides)
|
||||
}
|
||||
}
|
||||
|
||||
/// A PDF's pages as an import on their trim boxes sizes them ([`Opened::trim_pages`]).
|
||||
|
||||
@@ -266,7 +266,7 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() {
|
||||
assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None);
|
||||
assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all");
|
||||
let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap();
|
||||
let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, true);
|
||||
let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, true, None);
|
||||
assert!(r.image.is_none(), "kept as it is");
|
||||
}
|
||||
|
||||
@@ -529,9 +529,14 @@ fn tagged_tiffs_keep_their_icc_profile() {
|
||||
);
|
||||
}
|
||||
}
|
||||
// Converted pixels are in the destination's colours, not the image's profile.
|
||||
// Converted pixels are in the destination's colours, not the image's profile, which the CMS
|
||||
// can't read (it has no tags): they are converted as sRGB ones, with a warning.
|
||||
for destination in [vectorcraft_color::cms::DISPLAY_P3, vectorcraft_color::cms::GENERIC_CMYK] {
|
||||
let spaces = export(&tiff(&colour(), &rgb), json!({"output": {"conversion": "destination", "destination": destination}}));
|
||||
let mut settings: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "destination", "destination": destination}})).unwrap();
|
||||
settings.compression.compress_text = false;
|
||||
let r = export_with_report(&tiff(&colour(), &rgb), &PdfOptions { settings, ..Default::default() }).unwrap();
|
||||
assert!(r.warnings.len() == 1 && r.warnings[0].contains("converted to the destination as sRGB"), "{destination}: {:?}", r.warnings);
|
||||
let spaces = image_spaces(&r.bytes);
|
||||
assert!(spaces.len() == 1 && spaces[0].icc.as_deref() != Some(rgb.as_slice()), "converted to {destination}: {spaces:?}");
|
||||
}
|
||||
// PDF/X-1a allows no ICC-based color spaces: a tagged gray TIFF (8 or 16 bits), PNG or JPEG is
|
||||
@@ -555,3 +560,423 @@ fn tagged_tiffs_keep_their_icc_profile() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gray ICC profile (version 2.1, display class) with a D50 white point whose tone curve is `trc`:
|
||||
/// one entry, a gamma (u8Fixed8), or two, the ends of a table. 192 bytes.
|
||||
fn gray_profile(trc: &[u16]) -> Vec<u8> {
|
||||
let mut icc = vec![0u8; 192];
|
||||
icc[..4].copy_from_slice(&192u32.to_be_bytes());
|
||||
icc[8..12].copy_from_slice(&[2, 0x10, 0, 0]);
|
||||
icc[12..16].copy_from_slice(b"mntr");
|
||||
icc[16..20].copy_from_slice(b"GRAY");
|
||||
icc[20..24].copy_from_slice(b"XYZ ");
|
||||
icc[36..40].copy_from_slice(b"acsp");
|
||||
let d50 = [0x0000_F6D6u32, 0x0001_0000, 0x0000_D32D];
|
||||
for (i, v) in d50.iter().enumerate() {
|
||||
icc[68 + i * 4..72 + i * 4].copy_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
icc[128..132].copy_from_slice(&2u32.to_be_bytes());
|
||||
let curve_len = 12 + 2 * trc.len() as u32;
|
||||
for (i, (sig, at, len)) in [(b"kTRC", 156u32, curve_len), (b"wtpt", 172, 20)].into_iter().enumerate() {
|
||||
let e = 132 + i * 12;
|
||||
icc[e..e + 4].copy_from_slice(sig);
|
||||
icc[e + 4..e + 8].copy_from_slice(&at.to_be_bytes());
|
||||
icc[e + 8..e + 12].copy_from_slice(&len.to_be_bytes());
|
||||
}
|
||||
icc[156..160].copy_from_slice(b"curv");
|
||||
icc[164..168].copy_from_slice(&(trc.len() as u32).to_be_bytes());
|
||||
for (i, v) in trc.iter().enumerate() {
|
||||
icc[168 + i * 2..170 + i * 2].copy_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
icc[172..176].copy_from_slice(b"XYZ ");
|
||||
for (i, v) in d50.iter().enumerate() {
|
||||
icc[180 + i * 4..184 + i * 4].copy_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
icc
|
||||
}
|
||||
|
||||
/// The samples of `img` converted from ICC profile `icc` to sRGB with `intent`, as an image
|
||||
/// XObject holds them: RGB (or grey, the mean of the sRGB values, when `img` is grey) at 8 bits a
|
||||
/// sample, or at 16 big-endian with `deep`.
|
||||
fn srgb_samples(img: &DynamicImage, icc: &[u8], intent: vectorcraft_color::cms::Intent, deep: bool) -> Vec<u8> {
|
||||
let p = vectorcraft_color::cms::IccProfile::from_bytes(None, icc).unwrap();
|
||||
let (max, n) = (if deep { 65_535.0 } else { 255.0 }, if img.color().has_color() { 3 } else { 1 });
|
||||
let values: Vec<f32> = match (n, deep) {
|
||||
(3, true) => img.to_rgb16().into_raw().into_iter().map(f32::from).collect(),
|
||||
(3, false) => img.to_rgb8().into_raw().into_iter().map(f32::from).collect(),
|
||||
(_, true) => img.to_luma16().into_raw().into_iter().map(f32::from).collect(),
|
||||
_ => img.to_luma8().into_raw().into_iter().map(f32::from).collect(),
|
||||
};
|
||||
let mut out = vec![];
|
||||
for px in values.chunks(n) {
|
||||
let v: Vec<f32> = px.iter().map(|v| v / max).collect();
|
||||
let rgb = p.to_srgb(&v, intent).unwrap();
|
||||
let rgb = if n == 1 { vec![rgb.iter().sum::<f32>() / 3.0] } else { rgb.to_vec() };
|
||||
for c in rgb {
|
||||
let s = (c * max).round();
|
||||
if deep { out.extend_from_slice(&(s as u16).to_be_bytes()) } else { out.push(s as u8) }
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Do samples `a` and `b` (8 bits each, or 16 big-endian with `deep`) differ by at most `tolerance`?
|
||||
fn samples_close(a: &[u8], b: &[u8], deep: bool, tolerance: i32) -> bool {
|
||||
let values = |s: &[u8]| -> Vec<i32> {
|
||||
if deep { s.chunks(2).map(|v| i32::from(u16::from_be_bytes([v[0], v[1]]))).collect() } else { s.iter().map(|v| i32::from(*v)).collect() }
|
||||
};
|
||||
let (a, b) = (values(a), values(b));
|
||||
a.len() == b.len() && a.iter().zip(&b).all(|(a, b)| (a - b).abs() <= tolerance)
|
||||
}
|
||||
|
||||
/// The image XObjects of `d` exported with `settings`, which add no warning, and the file.
|
||||
fn export_images(d: &Document, settings: Value) -> (Vec<Written>, Vec<u8>) {
|
||||
let mut settings: PdfSettings = serde_json::from_value(settings).unwrap();
|
||||
settings.compression.compress_text = false;
|
||||
let r = export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap();
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
(image_spaces(&r.bytes), r.bytes)
|
||||
}
|
||||
|
||||
/// With Convert to Destination and an sRGB destination, a gray or RGB image that carries an ICC
|
||||
/// profile is converted from it to sRGB and written without it: an 8-bit TIFF, a 16-bit one (at
|
||||
/// 16 bits a sample from PDF 1.5 on, else at 8), a PNG, a gray TIFF, a resampled image and a JPEG
|
||||
/// kept as JPEG. Without conversion each keeps its profile. An image in an sRGB profile keeps its
|
||||
/// samples (a JPEG its JPEG data), and a black-and-white image converted to grays stays gray.
|
||||
#[test]
|
||||
fn convert_to_srgb_converts_tagged_images_from_their_profile() {
|
||||
use vectorcraft_color::cms::{DISPLAY_P3, Intent, SRGB, icc_bytes};
|
||||
// Marked version 4.2: PDF 1.7 holds ICC profiles up to that version.
|
||||
let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec();
|
||||
p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]);
|
||||
// Gamma 1.8.
|
||||
let gray = gray_profile(&[0x01CD]);
|
||||
let to_srgb = |more: Value| {
|
||||
let mut s = json!({"output": {"conversion": "destination", "destination": SRGB}});
|
||||
s.as_object_mut().unwrap().extend(more.as_object().unwrap().clone());
|
||||
s
|
||||
};
|
||||
let device = |space: &str, bits: u8, filter: &str| vec![Written { space: space.into(), icc: None, bits, filter: filter.into(), smask: false }];
|
||||
let flate = "FlateDecode";
|
||||
let deep = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(600, 600, |x, y| {
|
||||
image::Rgb([((x * 109 + y) % 65_521) as u16, ((y * 257 + 3) ^ 0x5a) as u16, ((x * y) % 65_521) as u16])
|
||||
}));
|
||||
let cases = [
|
||||
("RGB TIFF", colour(), tagged(&colour(), &p3, ImageFormat::Tiff), "image/tiff", &p3, json!({}), device("DeviceRGB", 8, flate), false),
|
||||
("RGB PNG", colour(), tagged(&colour(), &p3, ImageFormat::Png), "image/png", &p3, json!({}), device("DeviceRGB", 8, flate), false),
|
||||
(
|
||||
"16-bit RGB TIFF",
|
||||
deep.clone(),
|
||||
tagged(&deep, &p3, ImageFormat::Tiff),
|
||||
"image/tiff",
|
||||
&p3,
|
||||
json!({"compatibility": "1.7"}),
|
||||
device("DeviceRGB", 16, flate),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"16-bit RGB TIFF, PDF 1.4",
|
||||
deep.clone(),
|
||||
tagged(&deep, &p3, ImageFormat::Tiff),
|
||||
"image/tiff",
|
||||
&p3,
|
||||
json!({"compatibility": "1.4"}),
|
||||
device("DeviceRGB", 8, flate),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"gray TIFF",
|
||||
colour().grayscale(),
|
||||
tagged(&colour().grayscale(), &gray, ImageFormat::Tiff),
|
||||
"image/tiff",
|
||||
&gray,
|
||||
json!({}),
|
||||
device("DeviceGray", 8, flate),
|
||||
false,
|
||||
),
|
||||
];
|
||||
for (what, img, bytes, mime, icc, more, want, sixteen) in cases {
|
||||
let d = doc(bytes, mime);
|
||||
let (spaces, pdf) = export_images(&d, to_srgb(more.clone()));
|
||||
assert_eq!(spaces, want, "{what}");
|
||||
let samples = image_samples(&pdf);
|
||||
// 16-bit samples are converted, then reduced to 8 bits before PDF 1.5.
|
||||
let deep_source = matches!(img, DynamicImage::ImageRgb16(_));
|
||||
let want = srgb_samples(&img, icc, Intent::RelativeColorimetric, deep_source);
|
||||
let want: Vec<u8> = if deep_source && !sixteen {
|
||||
want.chunks(2).map(|v| (f32::from(u16::from_be_bytes([v[0], v[1]])) / 257.0).round() as u8).collect()
|
||||
} else {
|
||||
want
|
||||
};
|
||||
assert!(samples.len() == 1 && samples_close(&samples[0], &want, sixteen, if sixteen { 2 } else { 1 }), "{what}: converted samples");
|
||||
let unconverted: Vec<u8> = match &img {
|
||||
DynamicImage::ImageRgb16(s) if sixteen => s.iter().flat_map(|v| v.to_be_bytes()).collect(),
|
||||
s if s.color().has_color() => s.to_rgb8().into_raw(),
|
||||
s => s.to_luma8().into_raw(),
|
||||
};
|
||||
assert!(!samples_close(&samples[0], &unconverted, sixteen, 0), "{what}: the samples changed");
|
||||
// Without conversion the image keeps its profile (a version 4 profile from PDF 1.5 on).
|
||||
let mut plain = more;
|
||||
plain["compatibility"] = json!("1.7");
|
||||
let (spaces, _) = export_images(&d, plain);
|
||||
assert!(
|
||||
spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(icc.as_slice()),
|
||||
"{what}, no conversion: {spaces:?}"
|
||||
);
|
||||
}
|
||||
// Resampled, or kept as a JPEG: converted and written without the profile.
|
||||
let resampled = to_srgb(json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}));
|
||||
let (spaces, _) = export_images(&doc(tagged(&colour(), &p3, ImageFormat::Tiff), "image/tiff"), resampled);
|
||||
assert_eq!(spaces, device("DeviceRGB", 8, flate), "resampled");
|
||||
let (spaces, _) = export_images(&doc(tagged(&colour(), &p3, ImageFormat::Jpeg), "image/jpeg"), to_srgb(json!({})));
|
||||
assert_eq!(spaces, device("DeviceRGB", 8, "DCTDecode"), "JPEG");
|
||||
// An image in an sRGB profile keeps its samples, and a JPEG its JPEG data, written without the
|
||||
// profile; so does an image whose samples the conversion leaves unchanged (black in P3).
|
||||
let srgb = icc_bytes(SRGB).unwrap().to_vec();
|
||||
let (spaces, pdf) = export_images(&doc(tagged(&colour(), &srgb, ImageFormat::Png), "image/png"), to_srgb(json!({"compatibility": "1.7"})));
|
||||
assert_eq!(spaces, device("DeviceRGB", 8, flate), "sRGB PNG");
|
||||
assert!(image_samples(&pdf) == [colour().to_rgb8().into_raw()], "sRGB PNG: the samples unchanged");
|
||||
let jpeg = tagged(&colour(), &srgb, ImageFormat::Jpeg);
|
||||
let (spaces, pdf) = export_images(&doc(jpeg.clone(), "image/jpeg"), to_srgb(json!({"compatibility": "1.7"})));
|
||||
assert_eq!(spaces, device("DeviceRGB", 8, "DCTDecode"), "sRGB JPEG");
|
||||
assert!(image_data(&pdf) == [jpeg], "sRGB JPEG: the JPEG data unchanged");
|
||||
let black = DynamicImage::ImageRgb8(image::RgbImage::new(600, 600));
|
||||
let (spaces, _) = export_images(&doc(tagged(&black, &p3, ImageFormat::Png), "image/png"), to_srgb(json!({"compatibility": "1.7"})));
|
||||
assert_eq!(spaces, device("DeviceRGB", 8, flate), "black P3 PNG");
|
||||
// A black-and-white image whose profile makes black a gray is written in those grays, not
|
||||
// thresholded back to black and white when it is resampled.
|
||||
let bilevel =
|
||||
DynamicImage::ImageLuma8(image::GrayImage::from_fn(600, 600, |x, y| image::Luma([if (x / 10 + y / 10) % 2 == 0 { 0 } else { 255 }])));
|
||||
let lifted = gray_profile(&[0x3333, 0xFFFF]);
|
||||
let resample = json!({"downsample": "bicubic", "ppi": 150, "abovePpi": 225});
|
||||
let (spaces, pdf) = export_images(
|
||||
&doc(tagged(&bilevel, &lifted, ImageFormat::Tiff), "image/tiff"),
|
||||
to_srgb(json!({"compression": {"gray": resample.clone(), "mono": resample}})),
|
||||
);
|
||||
assert_eq!(spaces, device("DeviceGray", 8, flate), "lifted black and white");
|
||||
let samples = image_samples(&pdf);
|
||||
assert!(samples.len() == 1 && samples[0].iter().all(|v| *v > 0) && samples[0].iter().any(|v| *v > 200), "lifted black and white: grays kept");
|
||||
// A well-formed profile the CMS can't read (no tags) is kept, with a warning.
|
||||
let unread = icc_profile(b"RGB ", 600);
|
||||
let mut settings: PdfSettings = serde_json::from_value(to_srgb(json!({}))).unwrap();
|
||||
settings.compression.compress_text = false;
|
||||
let r = export_with_report(&doc(tagged(&colour(), &unread, ImageFormat::Tiff), "image/tiff"), &PdfOptions { settings, ..Default::default() })
|
||||
.unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings);
|
||||
let spaces = image_spaces(&r.bytes);
|
||||
assert!(spaces.len() == 1 && spaces[0].icc.as_deref() == Some(unread.as_slice()), "unread profile: {spaces:?}");
|
||||
// A tagged image whose header declares more pixels than the decoding allowance is kept as it
|
||||
// is, with a warning when it was to be converted.
|
||||
let declared = |img: &DynamicImage, icc: &[u8]| {
|
||||
let mut png = tagged(img, icc, ImageFormat::Png);
|
||||
png[16..24].copy_from_slice(&[0, 0, 0x75, 0x30, 0, 0, 0x75, 0x30]);
|
||||
let mut crc = flate2::Crc::new();
|
||||
crc.update(&png[12..29]);
|
||||
png[29..33].copy_from_slice(&crc.sum().to_be_bytes());
|
||||
png
|
||||
};
|
||||
let c: CompressionSettings = serde_json::from_value(json!({})).unwrap();
|
||||
let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true });
|
||||
for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] {
|
||||
let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out);
|
||||
assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning);
|
||||
let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, None);
|
||||
assert!(r.image.is_none() && r.warning.is_none(), "{what}, no conversion: {:?}", r.warning);
|
||||
// Too large to embed as it is too: the export leaves it out, and says only that.
|
||||
let mut settings: PdfSettings = serde_json::from_value(to_srgb(json!({}))).unwrap();
|
||||
settings.compression.compress_text = false;
|
||||
let r = export_with_report(&doc(png, "image/png"), &PdfOptions { settings, ..Default::default() }).unwrap();
|
||||
assert!(r.warnings.len() == 1 && r.warnings[0].contains("missing from the picture"), "{what}, exported: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// An RGB ICC profile (version 2.1, display class, XYZ connection space) of two lookup tables of
|
||||
/// two grid points each: the colorimetric one (`A2B1`) maps device RGB linearly onto sRGB's
|
||||
/// primaries adapted to D50, the perceptual one (`A2B0`) onto half of them. 436 bytes.
|
||||
fn rgb_two_intents() -> Vec<u8> {
|
||||
let mut icc = vec![0u8; 436];
|
||||
icc[..4].copy_from_slice(&436u32.to_be_bytes());
|
||||
icc[8..12].copy_from_slice(&[2, 0x10, 0, 0]);
|
||||
icc[12..16].copy_from_slice(b"mntr");
|
||||
icc[16..20].copy_from_slice(b"RGB ");
|
||||
icc[20..24].copy_from_slice(b"XYZ ");
|
||||
icc[36..40].copy_from_slice(b"acsp");
|
||||
let d50 = [0x0000_F6D6u32, 0x0001_0000, 0x0000_D32D];
|
||||
for (i, v) in d50.iter().enumerate() {
|
||||
icc[68 + i * 4..72 + i * 4].copy_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
icc[128..132].copy_from_slice(&3u32.to_be_bytes());
|
||||
for (i, (sig, at, len)) in [(b"A2B0", 168u32, 124u32), (b"A2B1", 292, 124), (b"wtpt", 416, 20)].into_iter().enumerate() {
|
||||
let e = 132 + i * 12;
|
||||
icc[e..e + 4].copy_from_slice(sig);
|
||||
icc[e + 4..e + 8].copy_from_slice(&at.to_be_bytes());
|
||||
icc[e + 8..e + 12].copy_from_slice(&len.to_be_bytes());
|
||||
}
|
||||
let primaries = [[0.4361f32, 0.2225, 0.0139], [0.3851, 0.7169, 0.0971], [0.1431, 0.0606, 0.7141]];
|
||||
for (at, scale) in [(168usize, 0.5f32), (292, 1.0)] {
|
||||
let mut lut = vec![];
|
||||
lut.extend_from_slice(b"mft2");
|
||||
lut.extend_from_slice(&[0, 0, 0, 0, 3, 3, 2, 0]);
|
||||
// The identity matrix, as s15Fixed16 numbers.
|
||||
for v in [1u32, 0, 0, 0, 1, 0, 0, 0, 1] {
|
||||
lut.extend_from_slice(&(v << 16).to_be_bytes());
|
||||
}
|
||||
lut.extend_from_slice(&2u16.to_be_bytes());
|
||||
lut.extend_from_slice(&2u16.to_be_bytes());
|
||||
for _ in 0..3 {
|
||||
lut.extend_from_slice(&[0, 0, 0xFF, 0xFF]);
|
||||
}
|
||||
for corner in 0..8u32 {
|
||||
let on = [corner >> 2 & 1, corner >> 1 & 1, corner & 1].map(|b| b as f32);
|
||||
let xyz = primaries.iter().zip(on).fold([0.0f32; 3], |sum, (p, o)| [sum[0] + o * p[0], sum[1] + o * p[1], sum[2] + o * p[2]]);
|
||||
for v in xyz {
|
||||
lut.extend_from_slice(&((v * scale * 32_768.0).round() as u16).to_be_bytes());
|
||||
}
|
||||
}
|
||||
for _ in 0..3 {
|
||||
lut.extend_from_slice(&[0, 0, 0xFF, 0xFF]);
|
||||
}
|
||||
icc[at..at + 124].copy_from_slice(&lut);
|
||||
}
|
||||
icc[416..420].copy_from_slice(b"XYZ ");
|
||||
for (i, v) in d50.iter().enumerate() {
|
||||
icc[424 + i * 4..428 + i * 4].copy_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
icc
|
||||
}
|
||||
|
||||
/// The conversion of a tagged image to an sRGB destination uses the colour settings' intent: an
|
||||
/// RGB profile with a perceptual table and a colorimetric one converts with the table the intent
|
||||
/// picks.
|
||||
#[test]
|
||||
fn convert_to_srgb_converts_images_with_the_color_settings_intent() {
|
||||
use vectorcraft_color::cms::{self, ColorSettings, Intent, SRGB};
|
||||
let icc = rgb_two_intents();
|
||||
let img = colour();
|
||||
let d = doc(tagged(&img, &icc, ImageFormat::Tiff), "image/tiff");
|
||||
let settings = json!({"output": {"conversion": "destination", "destination": SRGB}});
|
||||
let mut seen = vec![];
|
||||
for intent in [Intent::RelativeColorimetric, Intent::Perceptual] {
|
||||
let active = std::sync::Arc::new(cms::Cms::new(&ColorSettings { intent, ..ColorSettings::default() }).unwrap());
|
||||
let samples = image_samples(&cms::with_active(active, || export_images(&d, settings.clone())).1);
|
||||
let want = srgb_samples(&img, &icc, intent, false);
|
||||
assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "{intent:?}: converted samples");
|
||||
seen.push(samples[0].clone());
|
||||
}
|
||||
assert!(seen[0] != seen[1], "the two intents give different samples");
|
||||
}
|
||||
|
||||
/// A 600 × 600 image of sixteen blocks of colour, saturated ones (the primaries and secondaries)
|
||||
/// among them.
|
||||
fn colour_blocks() -> DynamicImage {
|
||||
const LEVELS: [u8; 4] = [0, 90, 200, 255];
|
||||
image::RgbImage::from_fn(600, 600, |x, y| {
|
||||
let (i, j) = ((x / 150) as usize, (y / 150) as usize);
|
||||
image::Rgb([LEVELS[i], LEVELS[j], LEVELS[(i + 2 * j) % 4]])
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
/// The samples (8 bits each) of `img`'s pixels as `convert` gives each one's: each distinct
|
||||
/// colour converts once.
|
||||
fn converted_samples(img: &DynamicImage, convert: impl Fn([u8; 3]) -> Vec<u8>) -> Vec<u8> {
|
||||
let mut seen: std::collections::HashMap<[u8; 3], Vec<u8>> = std::collections::HashMap::new();
|
||||
let mut out = vec![];
|
||||
for p in img.to_rgb8().pixels() {
|
||||
out.extend_from_slice(seen.entry(p.0).or_insert_with(|| convert(p.0)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The largest difference between samples `a` and `b` (8 bits each) and where it is: (difference,
|
||||
/// sample index, the two samples), or the two lengths when they differ.
|
||||
fn max_diff(a: &[u8], b: &[u8]) -> String {
|
||||
if a.len() != b.len() {
|
||||
return format!("lengths {} and {}", a.len(), b.len());
|
||||
}
|
||||
let worst = a.iter().zip(b).enumerate().max_by_key(|(_, (a, b))| a.abs_diff(**b));
|
||||
worst.map_or_else(String::new, |(i, (x, y))| format!("largest difference {} at sample {i}: {x} vs {y}", x.abs_diff(*y)))
|
||||
}
|
||||
|
||||
/// With Convert to Destination and a CMYK destination, or an RGB one other than sRGB, a colour
|
||||
/// image that carries an ICC profile is converted from that profile (to sRGB, then to the
|
||||
/// destination) rather than from its numbers read as sRGB ones; an untagged image is converted
|
||||
/// from sRGB as before. A gray image keeps its profile (gray stays gray), and an RGB profile the
|
||||
/// CMS can't read leaves the numbers converted as sRGB ones, with a warning. An RGB destination
|
||||
/// other than sRGB that is the document's own RGB profile leaves RGB images as they are, so the image keeps its
|
||||
/// profile.
|
||||
#[test]
|
||||
fn convert_to_destination_converts_tagged_images_from_their_profile() {
|
||||
use vectorcraft_color::cms::{self, ColorSettings, DISPLAY_P3, GENERIC_CMYK, Intent, WIDE_GAMUT_RGB, icc_bytes};
|
||||
let intent = Intent::RelativeColorimetric;
|
||||
let active = std::sync::Arc::new(cms::Cms::new(&ColorSettings { intent, ..ColorSettings::default() }).unwrap());
|
||||
let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec();
|
||||
p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]);
|
||||
let p3_profile = cms::IccProfile::from_bytes(None, &p3).unwrap();
|
||||
// A P3 pixel's sRGB samples.
|
||||
let from_p3 = |rgb: [u8; 3]| p3_profile.to_srgb(&rgb.map(|v| f32::from(v) / 255.0), intent).unwrap().map(|v| (v * 255.0).round() as u8);
|
||||
let img = colour_blocks();
|
||||
let tagged_png = doc(tagged(&img, &p3, ImageFormat::Png), "image/png");
|
||||
let untagged_png = doc(encoded(img.clone(), ImageFormat::Png), "image/png");
|
||||
let device = |space: &str| vec![Written { space: space.into(), icc: None, bits: 8, filter: "FlateDecode".into(), smask: false }];
|
||||
// Each destination: the space images are written in, and how an sRGB pixel's samples convert
|
||||
// to it (the tables the export builds from the destination's color settings).
|
||||
let cmyk = cms::Cms::new(&ColorSettings { intent, cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
let wide = cms::Cms::new(&ColorSettings { intent, rgb: WIDE_GAMUT_RGB.into(), ..ColorSettings::default() }).unwrap();
|
||||
let cmy = cms::ProofLut::build(|rgb| {
|
||||
let v = cmyk.srgb_to_cmyk(rgb, intent);
|
||||
[v[0], v[1], v[2]]
|
||||
});
|
||||
let black = cms::ProofLut::build(|rgb| [cmyk.srgb_to_cmyk(rgb, intent)[3], 0.0, 0.0]);
|
||||
let wide_lut = cms::ProofLut::build(|rgb| wide.srgb_to_rgb(rgb));
|
||||
let to_cmyk = |rgb: [u8; 3]| [cmy.apply8(rgb).as_slice(), &black.apply8(rgb)[..1]].concat();
|
||||
let to_wide = |rgb: [u8; 3]| wide_lut.apply8(rgb).to_vec();
|
||||
type ToDest<'a> = &'a dyn Fn([u8; 3]) -> Vec<u8>;
|
||||
let destinations: [(&str, &str, ToDest<'_>); 2] = [(GENERIC_CMYK, "DeviceCMYK", &to_cmyk), (WIDE_GAMUT_RGB, "DeviceRGB", &to_wide)];
|
||||
for (name, space, to_dest) in destinations {
|
||||
let settings = json!({"output": {"conversion": "destination", "destination": name}});
|
||||
let export = |d: &Document| cms::with_active(active.clone(), || export_images(d, settings.clone()));
|
||||
let (spaces, pdf) = export(&tagged_png);
|
||||
assert_eq!(spaces, device(space), "{name}: tagged");
|
||||
let samples = image_samples(&pdf);
|
||||
let want = converted_samples(&img, |rgb| to_dest(from_p3(rgb)));
|
||||
let as_srgb = converted_samples(&img, to_dest);
|
||||
assert!(
|
||||
samples.len() == 1 && samples_close(&samples[0], &want, false, 1),
|
||||
"{name}: converted from the profile, {}",
|
||||
max_diff(&samples[0], &want)
|
||||
);
|
||||
assert!(!samples_close(&samples[0], &as_srgb, false, 8), "{name}: not converted as sRGB");
|
||||
// An untagged image is converted from sRGB, as before.
|
||||
let (spaces, pdf) = export(&untagged_png);
|
||||
assert_eq!(spaces, device(space), "{name}: untagged");
|
||||
let samples = image_samples(&pdf);
|
||||
assert!(
|
||||
samples.len() == 1 && samples_close(&samples[0], &as_srgb, false, 1),
|
||||
"{name}: untagged converted as sRGB, {}",
|
||||
max_diff(&samples[0], &as_srgb)
|
||||
);
|
||||
}
|
||||
// A destination that is the document's own RGB profile leaves RGB images as they are: the
|
||||
// image keeps its profile, as untagged images keep their numbers.
|
||||
let own = std::sync::Arc::new(cms::Cms::new(&ColorSettings { intent, rgb: WIDE_GAMUT_RGB.into(), ..ColorSettings::default() }).unwrap());
|
||||
let settings = json!({"compatibility": "1.7", "output": {"conversion": "destination", "destination": WIDE_GAMUT_RGB}});
|
||||
let (spaces, _) = cms::with_active(own, || export_images(&tagged_png, settings));
|
||||
assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(p3.as_slice()), "own RGB profile: {spaces:?}");
|
||||
// A gray image keeps its gray profile in a CMYK destination.
|
||||
let gray = gray_profile(&[0x01CD]);
|
||||
let settings = json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}});
|
||||
let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff");
|
||||
let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings.clone()));
|
||||
assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), "gray: {spaces:?}");
|
||||
// A profile the CMS can't read: converted as sRGB, with a warning.
|
||||
let unread = icc_profile(b"RGB ", 600);
|
||||
let mut s: PdfSettings = serde_json::from_value(settings).unwrap();
|
||||
s.compression.compress_text = false;
|
||||
let unread_doc = doc(tagged(&img, &unread, ImageFormat::Png), "image/png");
|
||||
let r = cms::with_active(active, || export_with_report(&unread_doc, &PdfOptions { settings: s, ..Default::default() })).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("converted to the destination as sRGB")), "{:?}", r.warnings);
|
||||
assert_eq!(image_spaces(&r.bytes), device("DeviceCMYK"), "unread profile");
|
||||
let as_srgb = converted_samples(&img, to_cmyk);
|
||||
assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile: converted as sRGB");
|
||||
}
|
||||
|
||||
@@ -28,6 +28,8 @@ serde_json = { workspace = true }
|
||||
# SVGZ (gzip, pure-Rust backend: builds for wasm).
|
||||
flate2 = { workspace = true }
|
||||
image = { workspace = true }
|
||||
# Image data URLs decoded as usvg decodes them, within a byte limit (MIT OR Apache-2.0; already used by usvg).
|
||||
data-url = "0.3.2"
|
||||
# Colour / transform / length parsing for the <text> fallback (MIT OR Apache-2.0; already used by usvg).
|
||||
svgtypes = "0.16"
|
||||
simplecss = "0.2.2"
|
||||
|
||||
+25
-4
@@ -168,8 +168,8 @@ pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props {
|
||||
if spacing != 0.0 {
|
||||
p.push(("letter-spacing", len(spacing / 1000.0 * st.size * st.v_scale / 100.0)));
|
||||
}
|
||||
if st.kerning.is_some() {
|
||||
// Manual kerning replaces the font's pair kerning.
|
||||
if st.kerning.is_some() || st.glyph_form.is_width() {
|
||||
// Manual kerning replaces the font's pair kerning, and a monospaced width form turns it off.
|
||||
p.push(("font-kerning", "none".into()));
|
||||
}
|
||||
let mut v: Vec<String> = st
|
||||
@@ -190,8 +190,9 @@ pub(crate) fn type_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props {
|
||||
.filter(|(tag, _)| tag.len() == 4 && tag.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||
.map(|(tag, value)| format!("\"{tag}\" {value}"))
|
||||
.collect();
|
||||
// Proportional Metrics: `palt` (SVG writes vertical type as outlines).
|
||||
if st.proportional_metrics {
|
||||
// Proportional Metrics: `palt` (SVG writes vertical type as outlines), not with a monospaced
|
||||
// width form, which sets the characters on a fixed width.
|
||||
if st.proportional_metrics && !st.glyph_form.is_width() {
|
||||
v.push("\"palt\" 1".into());
|
||||
}
|
||||
// The East Asian glyph form: its one feature.
|
||||
@@ -876,4 +877,24 @@ mod tests {
|
||||
assert_eq!(css_string("w\r\"</style>"), r#""w\d \"\3c /style\3e ""#);
|
||||
assert_eq!(css_string("wght"), "\"wght\"");
|
||||
}
|
||||
|
||||
/// A monospaced width form sets the characters on a fixed width: Proportional Metrics' `palt`
|
||||
/// is not written with it and the font's pair kerning is turned off, and with the other forms
|
||||
/// `palt` is written and kerning stays.
|
||||
#[test]
|
||||
fn width_forms_leave_out_proportional_metrics() {
|
||||
use vectorcraft_doc::GlyphForm;
|
||||
let prop = |form, key: &str| {
|
||||
let st = CharStyle { proportional_metrics: true, glyph_form: form, ..CharStyle::default() };
|
||||
type_props(&st, &|v| format!("{v}px")).into_iter().find(|(k, _)| *k == key).map(|(_, v)| v)
|
||||
};
|
||||
assert_eq!(prop(GlyphForm::Default, "font-feature-settings").as_deref(), Some("\"palt\" 1"));
|
||||
assert_eq!(prop(GlyphForm::Jis78, "font-feature-settings").as_deref(), Some("\"palt\" 1, \"jp78\" 1"));
|
||||
assert_eq!(prop(GlyphForm::Jis78, "font-kerning"), None);
|
||||
for form in [GlyphForm::FullWidth, GlyphForm::HalfWidth, GlyphForm::ThirdWidth, GlyphForm::QuarterWidth] {
|
||||
let tag = std::str::from_utf8(form.feature().unwrap()).unwrap();
|
||||
assert_eq!(prop(form, "font-feature-settings"), Some(format!("\"{tag}\" 1")), "{form:?}");
|
||||
assert_eq!(prop(form, "font-kerning").as_deref(), Some("none"), "{form:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ use text::TextSlots;
|
||||
|
||||
pub use depth::MAX_ELEMENT_DEPTH;
|
||||
pub(crate) use depth::xml_too_deep;
|
||||
pub use files::{MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT};
|
||||
pub use files::{MAX_DATA_URL_BYTES, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT};
|
||||
pub(crate) use fx::BLEND;
|
||||
|
||||
/// Most objects an imported SVG may expand to: a guard against `<use>` and nested-image
|
||||
@@ -205,7 +205,7 @@ pub(crate) fn import_finding(
|
||||
symbol_suffixes: HashMap::new(),
|
||||
pattern_suffixes: HashMap::new(),
|
||||
blends: fx::blends(&xml, &scan.markers),
|
||||
filter_sources: fx::sources(&xml, &scan.markers),
|
||||
filter_sources: fx::sources(&xml, &scan.markers, |h| files.data_href(h)),
|
||||
files,
|
||||
non_scaling: found.non_scaling,
|
||||
data: found.data,
|
||||
|
||||
@@ -556,10 +556,12 @@ impl Styles {
|
||||
}
|
||||
|
||||
/// The properties rules with a `:not()` set on `n`, each with its value after the cascade.
|
||||
/// Only the rules [`Index::candidates`] gives for `n` are tested, as in [`Styles::matched_bytes`].
|
||||
pub(super) fn set_by_not_rules(&self, n: XNode) -> Vec<(String, String)> {
|
||||
let declared = self.declared(n);
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for r in self.rules.iter().filter(|r| r.selector.has_not() && r.selector.matches(n)) {
|
||||
let rules = self.index.candidates(n).into_iter().filter_map(|i| self.rules.get(i));
|
||||
for r in rules.filter(|r| r.selector.has_not() && r.selector.matches(n)) {
|
||||
for (k, ..) in r.decls.iter() {
|
||||
if !out.iter().any(|(o, _)| o == k)
|
||||
&& let Some(v) = declared.get(k)
|
||||
|
||||
@@ -334,6 +334,26 @@ fn not_selectors() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The `:not()` rules filed under classes an element lacks are not tested against it, so
|
||||
/// [`Styles::set_by_not_rules`] tests no more rules than [`Styles::matched_bytes`] counts.
|
||||
#[test]
|
||||
fn not_rules_test_only_the_indexed_candidates() {
|
||||
const N: usize = 2_000;
|
||||
let rules: String = (0..N).map(|i| format!(".c{i}:not(.skip) {{ fill: #{i:06x} }}\n")).collect();
|
||||
let rects: String = (0..N).map(|i| format!(r#"<rect id="r{i}" class="c{i}"/>"#)).collect();
|
||||
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg"><style>{rules}</style>{rects}<rect id="skip" class="c0 skip"/></svg>"#);
|
||||
with_doc(&svg, |doc, st| {
|
||||
let before = selector_tests();
|
||||
for i in 0..N {
|
||||
assert_eq!(st.set_by_not_rules(by_id(doc, &format!("r{i}"))), [("fill".to_string(), format!("#{i:06x}"))]);
|
||||
}
|
||||
assert!(st.set_by_not_rules(by_id(doc, "skip")).is_empty());
|
||||
// Testing every `:not()` rule against every element would test N × N selectors.
|
||||
let tests = selector_tests() - before;
|
||||
assert!(tests <= 3 * N as u64, "finding the :not() rules of {N} elements tested {tests} selectors");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decl_comments_are_stripped() {
|
||||
let d = |k: &str, v: &str| (k.to_string(), v.to_string(), false);
|
||||
|
||||
+388
-33
@@ -11,6 +11,12 @@
|
||||
//! A raster image, linked or a data URL, whose orientation (EXIF, or a TIFF's Orientation tag)
|
||||
//! turns or flips its pixels is turned before usvg gets it, so it is sized, fitted and stored as
|
||||
//! it is shown.
|
||||
//!
|
||||
//! usvg decodes a data URL each time it converts the element holding it, a `<use>` copy
|
||||
//! included, before the resolver sees it. So before usvg reads an SVG (the imported one, and
|
||||
//! each SVG image), each `<image>` and `<feImage>` href that is a data URL is changed to a key,
|
||||
//! and the resolver decodes the URL once, the first time a key comes, within what the data URLs
|
||||
//! may decode to together ([`MAX_DATA_URL_BYTES`]); every later use of it gets the same image.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
@@ -34,6 +40,13 @@ pub const MAX_NESTED_SVG_READS: usize = 1024;
|
||||
/// Most bytes of nested SVG image text an imported SVG may read, decoded or not, all reads together.
|
||||
pub const MAX_NESTED_SVG_TEXT: u64 = 512 << 20;
|
||||
|
||||
/// Most bytes the image data URLs an imported SVG shows may decode to, those in its SVG images
|
||||
/// included, all together; each URL is decoded once, however often it is shown.
|
||||
pub const MAX_DATA_URL_BYTES: u64 = 512 << 20;
|
||||
|
||||
/// What a data URL's key starts with, the URL's number following it.
|
||||
const DATA_URL_KEY: &str = "vectorcraft-data-url-";
|
||||
|
||||
/// The files an SVG's images link to.
|
||||
#[derive(Default)]
|
||||
pub(in crate::import) struct Files {
|
||||
@@ -74,6 +87,12 @@ pub(in crate::import) struct Files {
|
||||
/// The CMYK TIFF stored in place of a turned CMYK image, by the address of the PNG usvg got
|
||||
/// (kept here too, so the address stays its own).
|
||||
cmyk: Mutex<HashMap<usize, (Bytes, Bytes)>>,
|
||||
/// The data URLs changed to keys before usvg read them.
|
||||
data: Mutex<DataUrls>,
|
||||
/// The bytes the image data URLs decoded to so far, whether or not they are images.
|
||||
data_bytes: AtomicU64,
|
||||
/// Images were left out for their data URLs decoding past [`MAX_DATA_URL_BYTES`].
|
||||
too_much_data: AtomicBool,
|
||||
/// What usvg makes of the SVG and of the SVG images read so far, all together ([`budget`]):
|
||||
/// elements, bytes of copied style values and selector tests.
|
||||
spent: Mutex<budget::Cost>,
|
||||
@@ -82,6 +101,34 @@ pub(in crate::import) struct Files {
|
||||
refused: Mutex<Option<SvgError>>,
|
||||
}
|
||||
|
||||
/// The hrefs changed to keys, by number: an href's key is [`DATA_URL_KEY`] and its number.
|
||||
#[derive(Default)]
|
||||
struct DataUrls {
|
||||
/// The number of each href.
|
||||
numbers: HashMap<Arc<str>, usize>,
|
||||
/// Each href: a data URL, then what it decoded to, or a link.
|
||||
urls: Vec<DataUrl>,
|
||||
/// Each href as it was written, for the filters kept as written ([`Files::data_href`]).
|
||||
hrefs: Vec<Arc<str>>,
|
||||
}
|
||||
|
||||
enum DataUrl {
|
||||
Encoded(Arc<str>),
|
||||
Decoded(Decoded),
|
||||
/// A link that starts as a key does, looked up as it is.
|
||||
Link(Arc<str>),
|
||||
}
|
||||
|
||||
/// What a data URL decoded to, as usvg gets it.
|
||||
#[derive(Clone)]
|
||||
enum Decoded {
|
||||
Raster(RasterKind, Bytes),
|
||||
/// SVG text (unpacked when it was SVGZ), read where it is shown ([`Files::svg`]).
|
||||
Svg(Arc<str>),
|
||||
/// Not an image VectorCraft reads, or left out.
|
||||
Nothing,
|
||||
}
|
||||
|
||||
/// Encoded image bytes, shared.
|
||||
type Bytes = Arc<Vec<u8>>;
|
||||
|
||||
@@ -254,7 +301,7 @@ fn key(bytes: &Arc<Vec<u8>>) -> usize {
|
||||
impl Files {
|
||||
/// Read the files the `<image>` elements of `xml` (the text `svg`) link to. Placeholders
|
||||
/// stretch to the image's box (`preserveAspectRatio="none"`), which the file fills once
|
||||
/// relinked.
|
||||
/// relinked. The data URLs of its images are changed to keys ([`Files::take_data_urls`]).
|
||||
pub(in crate::import) fn read(svg: &str, xml: &roxmltree::Document, opts: &ImportOptions, edits: &mut Edits, warnings: &mut Vec<String>) -> Self {
|
||||
let mut files = Files::default();
|
||||
let mut reading = Reading {
|
||||
@@ -269,9 +316,41 @@ impl Files {
|
||||
measured: budget::Cost::default(),
|
||||
};
|
||||
files.sources = files.links_of(svg, xml, opts.folder, None, edits, &mut reading);
|
||||
files.take_data_urls(xml, edits);
|
||||
files
|
||||
}
|
||||
|
||||
/// Change each href of the `<image>` and `<feImage>` elements of `xml` that usvg would decode
|
||||
/// as a data URL to that URL's key, numbering the URLs not seen before: usvg gives a key to
|
||||
/// the resolver as it is ([`Files::data_url`]). An href that starts as a key does, a link,
|
||||
/// gets a key too, which the resolver reads as that link.
|
||||
fn take_data_urls(&self, xml: &roxmltree::Document, edits: &mut Edits) {
|
||||
let Ok(mut data) = self.data.lock() else { return };
|
||||
let hrefs = xml
|
||||
.descendants()
|
||||
.filter(|n| n.is_element() && matches!(n.tag_name().name(), "image" | "feImage"))
|
||||
.flat_map(|n| n.attributes())
|
||||
.filter(|a| a.name() == "href" && matches!(a.namespace(), None | Some("http://www.w3.org/1999/xlink")));
|
||||
for a in hrefs {
|
||||
let url = data_url::DataUrl::process(a.value()).is_ok();
|
||||
if !url && !a.value().starts_with(DATA_URL_KEY) {
|
||||
continue;
|
||||
}
|
||||
let n = match data.numbers.get(a.value()) {
|
||||
Some(n) => *n,
|
||||
None => {
|
||||
let href: Arc<str> = Arc::from(a.value());
|
||||
let n = data.urls.len();
|
||||
data.numbers.insert(href.clone(), n);
|
||||
data.hrefs.push(href.clone());
|
||||
data.urls.push(if url { DataUrl::Encoded(href) } else { DataUrl::Link(href) });
|
||||
n
|
||||
}
|
||||
};
|
||||
edits.set_value(a, &format!("{DATA_URL_KEY}{n}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// What usvg gets for each href the `<image>` elements of `xml` (the text `svg`) link to,
|
||||
/// relative paths taken from `folder`. `inside` is how deep the SVG images `xml` shows nest in
|
||||
/// it and the SVGs around it, measured when an SVG file is read (`None` for `xml` itself).
|
||||
@@ -507,6 +586,9 @@ impl Files {
|
||||
MAX_NESTED_SVG_TEXT >> 20
|
||||
));
|
||||
}
|
||||
if self.too_much_data.load(Ordering::Relaxed) {
|
||||
notes.push(format!("images were left out: together their data URLs decode to more than {} MB", MAX_DATA_URL_BYTES >> 20));
|
||||
}
|
||||
notes
|
||||
}
|
||||
|
||||
@@ -537,47 +619,145 @@ impl Files {
|
||||
}
|
||||
}
|
||||
|
||||
/// usvg's image resolver, for an SVG whose elements nest `height` deep: data URLs as usvg
|
||||
/// reads them, other hrefs only from the files read. SVG images are read here
|
||||
/// ([`Files::svg_data`], [`Files::svg`]), never by usvg's own resolver, which caps neither how
|
||||
/// deep they nest nor what they unpack to.
|
||||
/// usvg's image resolver, for an SVG whose elements nest `height` deep: data URLs by their
|
||||
/// keys ([`Files::data_url`]), and those usvg decoded itself as it reads them, within
|
||||
/// [`MAX_DATA_URL_BYTES`]; other hrefs only from the files read. SVG images are read here
|
||||
/// ([`Files::svg`]), never by usvg's own resolver, which caps neither how deep they nest nor
|
||||
/// what they unpack to.
|
||||
pub(in crate::import) fn resolver(&self, height: usize) -> ImageHrefResolver<'_> {
|
||||
self.depth.store(height, Ordering::Relaxed);
|
||||
ImageHrefResolver {
|
||||
// By type as usvg reads them, and TIFF; one without a type (`text/plain`) by its
|
||||
// bytes: one of those rasters, else SVG. A raster as [`shown`] gives it.
|
||||
resolve_data: Box::new(move |mime, bytes, opts| {
|
||||
use image::ImageFormat as F;
|
||||
let format = match mime {
|
||||
"image/jpg" | "image/jpeg" => F::Jpeg,
|
||||
"image/png" => F::Png,
|
||||
"image/gif" => F::Gif,
|
||||
"image/webp" => F::WebP,
|
||||
"image/tiff" => F::Tiff,
|
||||
"image/svg+xml" => return self.svg_data(&bytes, opts),
|
||||
"text/plain" => match image::guess_format(&bytes).ok().filter(|f| raster(*f).is_some() || *f == F::Tiff) {
|
||||
Some(format) => format,
|
||||
None => return self.svg_data(&bytes, opts),
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
let (kind, bytes) = self.keep(shown(bytes, format)?);
|
||||
Some(kind(bytes))
|
||||
let spent = self.data_bytes.load(Ordering::Relaxed).saturating_add(bytes.len() as u64);
|
||||
if spent > MAX_DATA_URL_BYTES {
|
||||
return leave_out(&self.too_much_data, true);
|
||||
}
|
||||
self.data_bytes.store(spent, Ordering::Relaxed);
|
||||
self.show(self.decoded(mime, bytes), opts)
|
||||
}),
|
||||
resolve_string: Box::new(move |h, opts| match self.find(h)? {
|
||||
Source::Raster(kind, bytes) => Some(kind(bytes)),
|
||||
Source::Svg(file) => self.svg(&file.text.clone(), Some(file), opts),
|
||||
resolve_string: Box::new(move |h, opts| {
|
||||
let link = match self.data_number(h).map(|n| self.data_url(n, opts)) {
|
||||
Some(Ok(image)) => return image,
|
||||
Some(Err(link)) => link,
|
||||
None => Arc::from(h),
|
||||
};
|
||||
match self.find(&link)? {
|
||||
Source::Raster(kind, bytes) => Some(kind(bytes)),
|
||||
Source::Svg(file) => self.svg(&file.text.clone(), Some(file), opts),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The SVG image of data `bytes` (SVG or SVGZ), as [`Files::svg`] reads it. Unpacked here,
|
||||
/// within what the SVGZ images have left, so usvg unpacks nothing itself; past it, `None`,
|
||||
/// noted.
|
||||
fn svg_data(&self, bytes: &[u8], opts: &usvg::Options) -> Option<ImageKind> {
|
||||
/// The number of the href whose key is `h`.
|
||||
fn data_number(&self, h: &str) -> Option<usize> {
|
||||
let n: usize = h.strip_prefix(DATA_URL_KEY)?.parse().ok()?;
|
||||
let known = n < self.data.lock().ok()?.urls.len();
|
||||
(known && h.len() == DATA_URL_KEY.len() + n.to_string().len()).then_some(n)
|
||||
}
|
||||
|
||||
/// The href whose key is `h`, as it was written: a filter kept as an effect holds its
|
||||
/// `<feImage>` hrefs as written, not their keys ([`super::fx::sources`]).
|
||||
pub(in crate::import) fn data_href(&self, h: &str) -> Option<Arc<str>> {
|
||||
let n = self.data_number(h)?;
|
||||
self.data.lock().ok()?.hrefs.get(n).cloned()
|
||||
}
|
||||
|
||||
/// The image of data URL `n`: decoded the first time ([`Files::decode`]), then kept; the link
|
||||
/// when href `n` is one.
|
||||
fn data_url(&self, n: usize, opts: &usvg::Options) -> Result<Option<ImageKind>, Arc<str>> {
|
||||
// The lock is let go before the image is shown: an SVG image takes it again.
|
||||
let state = match self.data.lock().ok().as_deref().and_then(|d| d.urls.get(n)) {
|
||||
Some(DataUrl::Decoded(decoded)) => Ok(decoded.clone()),
|
||||
Some(DataUrl::Encoded(url)) => Err(url.clone()),
|
||||
Some(DataUrl::Link(link)) => return Err(link.clone()),
|
||||
None => return Ok(None),
|
||||
};
|
||||
let url = match state {
|
||||
Ok(decoded) => return Ok(self.show(decoded, opts)),
|
||||
Err(url) => url,
|
||||
};
|
||||
let decoded = self.decode(&url);
|
||||
if let Ok(mut data) = self.data.lock()
|
||||
&& let Some(slot) = data.urls.get_mut(n)
|
||||
{
|
||||
*slot = DataUrl::Decoded(decoded.clone());
|
||||
}
|
||||
Ok(self.show(decoded, opts))
|
||||
}
|
||||
|
||||
/// What data URL `url` decodes to, as usvg decodes it, in what is left of
|
||||
/// [`MAX_DATA_URL_BYTES`]: decoding stops where it would go past, the image left out, noted.
|
||||
fn decode(&self, url: &str) -> Decoded {
|
||||
let Ok(parsed) = data_url::DataUrl::process(url) else { return Decoded::Nothing };
|
||||
let spent = self.data_bytes.load(Ordering::Relaxed);
|
||||
let room = MAX_DATA_URL_BYTES.saturating_sub(spent);
|
||||
let mut body = Vec::new();
|
||||
let decoded = parsed.decode(|bytes| {
|
||||
if (body.len() as u64).saturating_add(bytes.len() as u64) > room {
|
||||
return Err(());
|
||||
}
|
||||
body.extend_from_slice(bytes);
|
||||
Ok(())
|
||||
});
|
||||
self.data_bytes.store(spent.saturating_add(body.len() as u64), Ordering::Relaxed);
|
||||
match decoded {
|
||||
Ok(_) => {}
|
||||
Err(data_url::forgiving_base64::DecodeError::WriteError(())) => {
|
||||
self.too_much_data.store(true, Ordering::Relaxed);
|
||||
return Decoded::Nothing;
|
||||
}
|
||||
Err(_) => return Decoded::Nothing,
|
||||
}
|
||||
let mime = format!("{}/{}", parsed.mime_type().type_, parsed.mime_type().subtype);
|
||||
self.decoded(&mime, Arc::new(body))
|
||||
}
|
||||
|
||||
/// What usvg gets for data `bytes` of type `mime`: by type as usvg reads them, and TIFF; one
|
||||
/// without a type (`text/plain`) by its bytes: one of those rasters, else SVG. A raster as
|
||||
/// [`shown`] gives it; SVG or SVGZ as [`Files::svg_text`] gives it.
|
||||
fn decoded(&self, mime: &str, bytes: Bytes) -> Decoded {
|
||||
use image::ImageFormat as F;
|
||||
let format = match mime {
|
||||
"image/jpg" | "image/jpeg" => F::Jpeg,
|
||||
"image/png" => F::Png,
|
||||
"image/gif" => F::Gif,
|
||||
"image/webp" => F::WebP,
|
||||
"image/tiff" => F::Tiff,
|
||||
"image/svg+xml" => return self.svg_text(&bytes),
|
||||
"text/plain" => match image::guess_format(&bytes).ok().filter(|f| raster(*f).is_some() || *f == F::Tiff) {
|
||||
Some(format) => format,
|
||||
None => return self.svg_text(&bytes),
|
||||
},
|
||||
_ => return Decoded::Nothing,
|
||||
};
|
||||
match shown(bytes, format) {
|
||||
Some(shown) => {
|
||||
let (kind, bytes) = self.keep(shown);
|
||||
Decoded::Raster(kind, bytes)
|
||||
}
|
||||
None => Decoded::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of SVG image data `bytes` (SVG or SVGZ). Unpacked here, within what the SVGZ
|
||||
/// images have left, so usvg unpacks nothing itself; past it, nothing, noted.
|
||||
fn svg_text(&self, bytes: &[u8]) -> Decoded {
|
||||
match crate::text_within(bytes, &self.unpacked) {
|
||||
Ok(text) => self.svg(&text, None, opts),
|
||||
Err(e) => leave_out(&self.too_big, matches!(e, SvgError::TooBig(_))),
|
||||
Ok(text) => Decoded::Svg(Arc::from(text.as_ref())),
|
||||
Err(e) => {
|
||||
leave_out(&self.too_big, matches!(e, SvgError::TooBig(_)));
|
||||
Decoded::Nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The image usvg gets for `decoded`: an SVG image read here, where it is shown.
|
||||
fn show(&self, decoded: Decoded, opts: &usvg::Options) -> Option<ImageKind> {
|
||||
match decoded {
|
||||
Decoded::Raster(kind, bytes) => Some(kind(bytes)),
|
||||
Decoded::Svg(text) => self.svg(&text, None, opts),
|
||||
Decoded::Nothing => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -641,6 +821,9 @@ impl Files {
|
||||
// usvg's parser would overflow on it, as on the SVG holding it (`import`).
|
||||
super::convolve_matrices_ok(&xml).ok()?;
|
||||
self.set_spent(spent.add(cost));
|
||||
let mut edits = Edits::default();
|
||||
self.take_data_urls(&xml, &mut edits);
|
||||
let keyed = edits.apply(text);
|
||||
self.depth.store(used + height, Ordering::Relaxed);
|
||||
let within = self.within.lock().ok().map(|mut w| w.push(file)).is_some();
|
||||
// usvg's `Tree::from_data_nested`, except that hrefs to files go to the resolver.
|
||||
@@ -659,7 +842,7 @@ impl Files {
|
||||
},
|
||||
..usvg::Options::default()
|
||||
};
|
||||
let tree = usvg::Tree::from_str(text, &nested);
|
||||
let tree = usvg::Tree::from_str(&keyed, &nested);
|
||||
if within && let Ok(mut w) = self.within.lock() {
|
||||
w.pop();
|
||||
}
|
||||
@@ -1096,6 +1279,178 @@ mod tests {
|
||||
assert_eq!(files.left_out().len(), 2, "{:?}", files.left_out());
|
||||
}
|
||||
|
||||
/// A base64 data URL of `bytes` of type `mime`.
|
||||
fn data(mime: &str, bytes: &[u8]) -> String {
|
||||
format!("data:{mime};base64,{}", crate::base64_encode(bytes))
|
||||
}
|
||||
|
||||
/// A PNG of `w` × 1.
|
||||
fn png_of(w: u32) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
image::RgbaImage::new(w, 1).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// SVG text of 2 × 2 holding `body`.
|
||||
fn doc(body: &str) -> String {
|
||||
format!(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="2" height="2">{body}</svg>"#)
|
||||
}
|
||||
|
||||
/// `svg` read as the import reads it, its data URLs changed to keys first, `spent` bytes of
|
||||
/// [`MAX_DATA_URL_BYTES`] already decoded: the files, and the PNG bytes of the images usvg
|
||||
/// made, filters' included, in order.
|
||||
fn read_keyed(svg: &str, spent: u64) -> (Files, Vec<Arc<Vec<u8>>>) {
|
||||
let xml = super::super::parse(svg).unwrap();
|
||||
let mut edits = Edits::default();
|
||||
let files = Files::read(svg, &xml, &ImportOptions::default(), &mut edits, &mut vec![]);
|
||||
files.data_bytes.store(spent, Ordering::Relaxed);
|
||||
let text = edits.apply(svg).into_owned();
|
||||
let tree = {
|
||||
let height = depth::height(&xml, MAX_ELEMENT_DEPTH).unwrap();
|
||||
let opts = usvg::Options { image_href_resolver: files.resolver(height), ..usvg::Options::default() };
|
||||
usvg::Tree::from_str(&text, &opts).unwrap()
|
||||
};
|
||||
// Filters' images and SVG images' trees are subroots.
|
||||
fn pngs(g: &usvg::Group, out: &mut Vec<Arc<Vec<u8>>>) {
|
||||
for n in g.children() {
|
||||
match n {
|
||||
usvg::Node::Group(g) => pngs(g, out),
|
||||
usvg::Node::Image(im) => {
|
||||
if let ImageKind::PNG(b) = im.kind() {
|
||||
out.push(b.clone());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
n.subroots(|g| pngs(g, out));
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
pngs(tree.root(), &mut out);
|
||||
(files, out)
|
||||
}
|
||||
|
||||
/// A data URL shown by many `<use>` elements is decoded once, and every use gets the same
|
||||
/// image, where usvg decoded it again for each.
|
||||
#[test]
|
||||
fn a_data_url_is_decoded_once_however_often_it_is_used() {
|
||||
let png = png();
|
||||
let uses = r##"<use href="#p"/>"##.repeat(64);
|
||||
let svg = doc(&format!(r#"<defs><image id="p" href="{}" width="1" height="1"/></defs>{uses}"#, data("image/png", &png)));
|
||||
let (files, shown) = read_keyed(&svg, 0);
|
||||
assert_eq!(shown.len(), 64);
|
||||
assert!(shown.iter().all(|b| Arc::ptr_eq(b, &shown[0]) && **b == png));
|
||||
assert_eq!(files.data_bytes.load(Ordering::Relaxed), png.len() as u64);
|
||||
assert!(files.left_out().is_empty(), "{:?}", files.left_out());
|
||||
}
|
||||
|
||||
/// The data URLs inside an SVG image get keys too: each is decoded once, together with the
|
||||
/// SVG image's own URL.
|
||||
#[test]
|
||||
fn data_urls_in_svg_images_are_decoded_once() {
|
||||
let png = png();
|
||||
let uses = r##"<use href="#p"/>"##.repeat(16);
|
||||
let inner = doc(&format!(r#"<defs><image id="p" href="{}" width="1" height="1"/></defs>{uses}"#, data("image/png", &png)));
|
||||
let svg = doc(&format!(r#"<image href="{}" width="2" height="2"/>"#, data("image/svg+xml", inner.as_bytes())));
|
||||
let (files, shown) = read_keyed(&svg, 0);
|
||||
assert_eq!(shown.len(), 16);
|
||||
assert_eq!(files.data_bytes.load(Ordering::Relaxed), (inner.len() + png.len()) as u64);
|
||||
}
|
||||
|
||||
/// An `<feImage>`'s data URL gets a key too.
|
||||
#[test]
|
||||
fn fe_image_data_urls_are_decoded_once() {
|
||||
let png = png();
|
||||
let rects: String = (1..=8).map(|i| format!(r#"<rect width="{i}" height="1" filter="url(#f)"/>"#)).collect();
|
||||
let svg = doc(&format!(r#"<filter id="f"><feImage href="{}"/></filter>{rects}"#, data("image/png", &png)));
|
||||
let (files, shown) = read_keyed(&svg, 0);
|
||||
assert_eq!(shown.len(), 8);
|
||||
assert_eq!(files.data_bytes.load(Ordering::Relaxed), png.len() as u64);
|
||||
}
|
||||
|
||||
/// Both hrefs get keys, and usvg still takes the plain `href` over `xlink:href`, in either
|
||||
/// order: only its URL is decoded.
|
||||
#[test]
|
||||
fn the_plain_href_still_wins_over_xlink_href() {
|
||||
let (one, two) = (png_of(1), png_of(2));
|
||||
let (one_url, two_url) = (data("image/png", &one), data("image/png", &two));
|
||||
for image in [
|
||||
format!(r#"<image href="{one_url}" xlink:href="{two_url}" width="1" height="1"/>"#),
|
||||
format!(r#"<image xlink:href="{two_url}" href="{one_url}" width="1" height="1"/>"#),
|
||||
] {
|
||||
let (files, shown) = read_keyed(&doc(&image), 0);
|
||||
assert_eq!(shown.len(), 1);
|
||||
assert_eq!(*shown[0], one);
|
||||
assert_eq!(files.data_bytes.load(Ordering::Relaxed), one.len() as u64);
|
||||
}
|
||||
}
|
||||
|
||||
/// An image whose data URL is written in an entity, and so in every element the entity
|
||||
/// makes, gets a key too.
|
||||
#[test]
|
||||
fn data_urls_written_in_entities_are_decoded_once() {
|
||||
let png = png();
|
||||
let uses = r##"<use href="#p"/>"##.repeat(16);
|
||||
let svg = format!(
|
||||
r#"<!DOCTYPE svg [<!ENTITY img "<image id='p' href='{}' width='1' height='1'/>">]>{}"#,
|
||||
data("image/png", &png),
|
||||
doc(&format!("<defs>&img;</defs>{uses}"))
|
||||
);
|
||||
let (files, shown) = read_keyed(&svg, 0);
|
||||
assert_eq!(shown.len(), 16);
|
||||
assert_eq!(files.data_bytes.load(Ordering::Relaxed), png.len() as u64);
|
||||
}
|
||||
|
||||
/// The data URLs decode to at most [`MAX_DATA_URL_BYTES`] together: a URL that fits what is
|
||||
/// left is decoded, and decoding stops where a URL would go past it, that image left out and
|
||||
/// noted.
|
||||
#[test]
|
||||
fn data_urls_past_the_limit_are_left_out() {
|
||||
let (small, big) = (png(), png_of(64));
|
||||
assert!(small.len() < big.len());
|
||||
let svg = doc(&format!(
|
||||
r#"<image href="{}" width="1" height="1"/><image href="{}" width="1" height="1"/>"#,
|
||||
data("image/png", &small),
|
||||
data("image/png", &big)
|
||||
));
|
||||
let spent = MAX_DATA_URL_BYTES - (small.len() + big.len()) as u64 + 1;
|
||||
let (files, shown) = read_keyed(&svg, spent);
|
||||
assert_eq!(shown.len(), 1);
|
||||
assert_eq!(*shown[0], small);
|
||||
assert!(files.data_bytes.load(Ordering::Relaxed) <= MAX_DATA_URL_BYTES);
|
||||
assert_eq!(files.left_out(), [format!("images were left out: together their data URLs decode to more than {} MB", MAX_DATA_URL_BYTES >> 20)]);
|
||||
// A data URL usvg decodes itself counts too.
|
||||
let files = Files::default();
|
||||
files.data_bytes.store(MAX_DATA_URL_BYTES, Ordering::Relaxed);
|
||||
let resolver = files.resolver(1);
|
||||
assert!((resolver.resolve_data)("image/png", Arc::new(small.clone()), &usvg::Options::default()).is_none());
|
||||
drop(resolver);
|
||||
assert_eq!(files.left_out().len(), 1);
|
||||
}
|
||||
|
||||
/// A link that looks like a key, spelled plainly or with character references, in the
|
||||
/// imported SVG or in an SVG image, stays that link: it never shows a data URL's image.
|
||||
#[test]
|
||||
fn links_that_look_like_keys_stay_links() {
|
||||
let png = png();
|
||||
let url = data("image/png", &png);
|
||||
let inner = doc(&format!(r#"<image href="{DATA_URL_KEY}0" width="1" height="1"/>"#));
|
||||
let svg = doc(&format!(
|
||||
r#"<image href="{url}" width="1" height="1"/><image href="{DATA_URL_KEY}0" width="1" height="1"/><image href="v{}0" width="1" height="1"/><image href="{}" width="2" height="2"/>"#,
|
||||
&DATA_URL_KEY[1..],
|
||||
data("image/svg+xml", inner.as_bytes())
|
||||
));
|
||||
let (files, shown) = read_keyed(&svg, 0);
|
||||
// The data URL's image, then the placeholder of the missing file, twice; the SVG image's
|
||||
// link names no file there, so it shows nothing.
|
||||
assert_eq!(shown.len(), 3);
|
||||
assert_eq!(*shown[0], png);
|
||||
assert!(shown[1..].iter().all(|b| **b != png && files.links.get(&key(b)).is_some_and(|l| l.missing)));
|
||||
assert_eq!(files.data_number(&format!("{DATA_URL_KEY}00")), None);
|
||||
assert_eq!(files.data_number(&format!("{DATA_URL_KEY}+0")), None);
|
||||
assert_eq!(files.data_number(&format!("{DATA_URL_KEY}9")), None);
|
||||
}
|
||||
|
||||
/// The nested SVG images read, decoded or not, take at most [`MAX_NESTED_SVG_TEXT`] bytes of
|
||||
/// text together: an image whose text goes past it is left out and noted. A broken image's
|
||||
/// text counts too, and its decoded place is given back.
|
||||
|
||||
@@ -61,8 +61,10 @@ impl Source {
|
||||
|
||||
/// Each `<filter>` element with an id, as written, by id, with the document's style sheets read
|
||||
/// once for all of them. A source is checked and read by usvg only when art uses it, once.
|
||||
/// `markers` is the text with its data URLs left out ([`super::depth::prescan`]).
|
||||
pub(super) fn sources(xml: &roxmltree::Document, markers: &str) -> HashMap<String, Source> {
|
||||
/// `markers` is the text with its data URLs left out ([`super::depth::prescan`]). `href` gives the
|
||||
/// href, as written, of each key the prepass wrote in place of an `<feImage>` href
|
||||
/// ([`super::files::Files::data_href`]): the source holds that href.
|
||||
pub(super) fn sources(xml: &roxmltree::Document, markers: &str, href: impl Fn(&str) -> Option<Arc<str>>) -> HashMap<String, Source> {
|
||||
if !markers.contains("<filter") && !markers.contains(":filter") {
|
||||
return HashMap::new();
|
||||
}
|
||||
@@ -74,13 +76,40 @@ pub(super) fn sources(xml: &roxmltree::Document, markers: &str) -> HashMap<Strin
|
||||
.filter_map(|(order, n)| {
|
||||
let id = n.attribute("id")?.to_string();
|
||||
let primitives = n.children().filter(roxmltree::Node::is_element).map(|p| p.tag_name().name().to_string()).collect();
|
||||
let xml = vectorcraft_effects::svg_filter::element_xml(n, text)?;
|
||||
let xml = hrefs_as_written(n, vectorcraft_effects::svg_filter::element_xml(n, text)?, &href);
|
||||
let styled = vectorcraft_effects::svg_filter::depends_on_styles(n, &styles);
|
||||
Some((id, Source { xml, primitives, order, styled, ..Default::default() }))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `xml`, the text of filter `n` ([`vectorcraft_effects::svg_filter::element_xml`]), with each
|
||||
/// `<feImage>` href that `href` gives a written href for put back as written, XML-escaped.
|
||||
fn hrefs_as_written(n: roxmltree::Node, mut xml: String, href: &impl Fn(&str) -> Option<Arc<str>>) -> String {
|
||||
// `element_xml` adds namespace declarations to the start tag only, ahead of every child.
|
||||
let (start, end) = (n.range().start, n.range().end);
|
||||
let Some(shift) = xml.len().checked_sub(end - start) else { return xml };
|
||||
let mut written: Vec<_> = n
|
||||
.descendants()
|
||||
.filter(|p| p.is_element() && p.tag_name().name() == "feImage")
|
||||
.flat_map(|p| p.attributes())
|
||||
.filter(|a| a.name() == "href" && matches!(a.namespace(), None | Some("http://www.w3.org/1999/xlink")))
|
||||
.filter_map(|a| {
|
||||
let r = a.range_value();
|
||||
// A value written through an entity lies outside the element's text: it stays.
|
||||
(r.start > start && r.end < end).then_some(())?;
|
||||
Some((r.start - start + shift..r.end - start + shift, a.value(), href(a.value())?))
|
||||
})
|
||||
.collect();
|
||||
written.sort_by_key(|(r, ..)| std::cmp::Reverse(r.start));
|
||||
for (r, key, h) in written {
|
||||
if xml.get(r.clone()) == Some(key) {
|
||||
xml.replace_range(r, &crate::xml_escape(&h));
|
||||
}
|
||||
}
|
||||
xml
|
||||
}
|
||||
|
||||
/// The element name of primitive `k` (`feGaussianBlur`).
|
||||
fn element_name(k: &Kind) -> String {
|
||||
let debug = format!("{k:?}");
|
||||
|
||||
@@ -95,6 +95,11 @@ impl Edits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the value of attribute `a` to `value` (XML-escaped already).
|
||||
pub(crate) fn set_value(&mut self, a: roxmltree::Attribute, value: &str) {
|
||||
self.list.push((a.range_value(), value.to_string()));
|
||||
}
|
||||
|
||||
/// Add the declaration `decl` (XML-escaped already) to the `style` of element `n` (in `svg`),
|
||||
/// after the ones already there (so it wins over them and over style sheet rules).
|
||||
fn style(&mut self, svg: &str, n: XNode, decl: &str) {
|
||||
@@ -163,7 +168,8 @@ fn named_made_up_ids(xml: &roxmltree::Document) -> HashSet<usize> {
|
||||
/// * so do `<circle>` and `<ellipse>` elements, recorded: usvg makes their arcs into a varying
|
||||
/// number of curves, and they come back as the ellipse VectorCraft draws (not in a file whose
|
||||
/// style sheet has an attribute selector);
|
||||
/// * linked files are read ([`files`]);
|
||||
/// * linked files are read, and the data URLs of `<image>` and `<feImage>` elements are each
|
||||
/// changed to a key that the resolver decodes once ([`files`]);
|
||||
/// * percentage lengths in a `<symbol>` with a `viewBox` become numbers ([`symbol_units`]);
|
||||
/// * what style sheet rules with a `:not()` set goes in `style` attributes ([`not_rules`]).
|
||||
///
|
||||
@@ -190,7 +196,7 @@ pub(super) fn prepass<'s>(
|
||||
&& !events
|
||||
&& !foreign_attrs
|
||||
&& !ellipses
|
||||
&& !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING, "data-", "class", "groupmode", "script"]
|
||||
&& !["<a", "display", "<use", ":use", "<image", ":image", "feImage", vector_effect::NON_SCALING, "data-", "class", "groupmode", "script"]
|
||||
.iter()
|
||||
.any(|t| markers.contains(t))
|
||||
{
|
||||
|
||||
@@ -533,7 +533,10 @@ pub fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) -> Resu
|
||||
}
|
||||
|
||||
pub use glyph::glyph_art;
|
||||
pub use import::{MAX_ELEMENT_DEPTH, MAX_FOREIGN, MAX_FOREIGN_VALUE, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT, MAX_NODES};
|
||||
pub use import::{
|
||||
MAX_DATA_URL_BYTES, MAX_ELEMENT_DEPTH, MAX_FOREIGN, MAX_FOREIGN_VALUE, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT,
|
||||
MAX_NODES,
|
||||
};
|
||||
|
||||
/// Import an SVG document reading the files it links to as `opts` says, also returning warnings.
|
||||
pub fn import_with(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<String>), SvgError> {
|
||||
|
||||
@@ -949,6 +949,21 @@ fn nested_svg_images_past_count_cap_are_left_out() {
|
||||
assert!(warnings.iter().any(|w| w.contains(&format!("more than {MAX_NESTED_SVG_IMAGES} nested SVG images"))));
|
||||
}
|
||||
|
||||
/// A data URL shown by `<use>` elements, in the SVG and in an SVG image of it, imports as one
|
||||
/// image shown at each use.
|
||||
#[test]
|
||||
fn data_url_images_shown_by_uses_import_at_each_use() {
|
||||
let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAwS2OUAAAAABJRU5ErkJggg==";
|
||||
let image = format!(r#"<image id="p" href="data:image/png;base64,{png}" width="4" height="4"/>"#);
|
||||
let uses = r##"<use href="#p" x="5"/>"##.repeat(3);
|
||||
let inner = format!(r#"<svg {SVG_NS} width="20" height="10"><defs>{image}</defs>{uses}</svg>"#);
|
||||
let (d, w) = import_with_report(&svg(&format!("<defs>{image}</defs>{uses}{}", image_of("image/svg+xml", &inner)))).unwrap();
|
||||
assert!(w.is_empty(), "{w:?}");
|
||||
let found = images(&d);
|
||||
assert_eq!(found.len(), 6);
|
||||
assert!(found.iter().all(|(_, im)| im.key == found[0].1.key && (im.width, im.height) == (1, 1)));
|
||||
}
|
||||
|
||||
/// Nested SVG images that can't be read: text that isn't XML, and an SVG without a size.
|
||||
const BROKEN_SVG_IMAGES: [&str; 2] =
|
||||
[r#"<svg xmlns="http://www.w3.org/2000/svg" width="10"#, r#"<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"/>"#];
|
||||
|
||||
@@ -295,7 +295,8 @@ impl OtFeatures {
|
||||
let own = self.with_tags(listed.iter().map(String::as_str));
|
||||
let s = &own;
|
||||
let mut v = Vec::with_capacity(8);
|
||||
if st.kerning.is_some() {
|
||||
// A monospaced width form turns the font's pair kerning off as well.
|
||||
if st.kerning.is_some() || st.glyph_form.is_width() {
|
||||
v.push(f(b"kern", false));
|
||||
}
|
||||
let liga = s.ligatures && (!ligatures_suppressed_by(st.tracking) || explicit_ligatures(listed));
|
||||
@@ -342,15 +343,20 @@ impl OtFeatures {
|
||||
// Kerning for the glyphs `palt` makes proportional (OpenType `apkn`), with automatic
|
||||
// kerning only.
|
||||
v.push(f(b"apkn", st.kerning.is_none()));
|
||||
} else if st.glyph_form.is_width() {
|
||||
// Listed as off, not left out: in runs shaped together with proportional text, a
|
||||
// feature left out is set back to the shaper's default, which for `apkn` is on.
|
||||
v.push(f(b"apkn", false));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Does text in style `st` take proportional widths (`palt`)? Proportional Metrics in
|
||||
/// horizontal type; vertical type takes proportional heights instead
|
||||
/// horizontal type, except with a monospaced width form ([`vectorcraft_doc::GlyphForm::is_width`]),
|
||||
/// which sets the characters on a fixed width; vertical type takes proportional heights instead
|
||||
/// ([`Self::proportional_vertical`]).
|
||||
pub(crate) fn proportional(&self, st: &CharStyle) -> bool {
|
||||
st.proportional_metrics && !self.vertical
|
||||
st.proportional_metrics && !self.vertical && !st.glyph_form.is_width()
|
||||
}
|
||||
|
||||
/// Does text in style `st` take proportional heights (`vpal`)? Proportional Metrics in
|
||||
@@ -630,4 +636,44 @@ mod tests {
|
||||
assert!(serbian.iter().zip(&russian).all(|(s, r)| s != r), "every letter in its Serbian form");
|
||||
assert_eq!(outlines("sr-Latn"), serbian);
|
||||
}
|
||||
|
||||
/// A monospaced width form (`fwid`, `hwid`, `twid`, `qwid`) and Proportional Metrics' `palt`
|
||||
/// are mutually exclusive: with a width form `palt` is left out and the font's pair kerning
|
||||
/// (`kern`, and `apkn` for `palt`'s glyphs) is turned off, with automatic or manual kerning,
|
||||
/// and with the other forms they stay.
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/features_fj#tag-fwid>
|
||||
#[test]
|
||||
fn width_forms_turn_off_proportional_metrics() {
|
||||
use vectorcraft_doc::GlyphForm;
|
||||
let tags = |form, kerning, value| {
|
||||
let st = CharStyle { proportional_metrics: true, glyph_form: form, kerning, ..CharStyle::default() };
|
||||
OtFeatures::default().resolve(&st).iter().filter(|f| f.value == value).map(|f| f.tag.to_string()).collect::<Vec<_>>()
|
||||
};
|
||||
for form in [GlyphForm::Default, GlyphForm::Traditional, GlyphForm::Jis78] {
|
||||
assert!(tags(form, None, 1).contains(&"palt".to_string()), "{form:?}: {:?}", tags(form, None, 1));
|
||||
assert!(!tags(form, None, 0).contains(&"kern".to_string()), "{form:?}: {:?}", tags(form, None, 0));
|
||||
}
|
||||
for form in [GlyphForm::FullWidth, GlyphForm::HalfWidth, GlyphForm::ThirdWidth, GlyphForm::QuarterWidth] {
|
||||
for kerning in [None, Some(0.0)] {
|
||||
let on = tags(form, kerning, 1);
|
||||
assert!(!on.contains(&"palt".to_string()) && !on.contains(&"apkn".to_string()), "{form:?}: {on:?}");
|
||||
assert!(on.iter().any(|t| t.as_bytes() == form.feature().unwrap()), "{form:?}: {on:?}");
|
||||
// Listed as off, so that runs shaped together with proportional text keep them off.
|
||||
let off = tags(form, kerning, 0);
|
||||
assert!(off.contains(&"kern".to_string()) && off.contains(&"apkn".to_string()), "{form:?} {kerning:?}: {off:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A face's `GPOS` features are found apart from its `GSUB` ones: Source Sans 3 kerns with
|
||||
/// `GPOS` and makes ligatures with `GSUB`.
|
||||
#[test]
|
||||
fn positioning_and_substitution_features_are_found_in_their_own_tables() {
|
||||
let face = FontDb::global().face("Source Sans 3", "Regular").unwrap();
|
||||
assert!(face.has_positioning_feature(*b"kern"));
|
||||
assert!(!face.has_substitution_feature(*b"kern"));
|
||||
assert!(face.has_substitution_feature(*b"liga"));
|
||||
assert!(!face.has_positioning_feature(*b"liga"));
|
||||
assert!(!face.has_positioning_feature(*b"fwid"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,6 +158,17 @@ fn ligature_glyphs(t: &LigatureSubstFormat1<'_>, room: usize) -> Vec<u32> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Does `features` (a `GSUB` or `GPOS` feature list) have feature `tag` with at least one lookup?
|
||||
/// At most [`MAX_FEATURES`] feature records are read.
|
||||
fn has_feature(features: &skrifa::raw::tables::layout::FeatureList<'_>, tag: [u8; 4]) -> bool {
|
||||
features
|
||||
.feature_records()
|
||||
.iter()
|
||||
.take(MAX_FEATURES)
|
||||
.filter(|r| r.feature_tag().to_be_bytes() == tag)
|
||||
.any(|r| r.feature(features.offset_data()).is_ok_and(|f| !f.lookup_list_indices().is_empty()))
|
||||
}
|
||||
|
||||
impl GsubIndex {
|
||||
/// Read `face`'s `GSUB` table. Empty when the face has none or it cannot be read; glyph ids past
|
||||
/// the face's glyph count are left out; the caps above bound what a damaged table makes it read.
|
||||
@@ -309,13 +320,15 @@ impl FontFace {
|
||||
/// cannot be read.
|
||||
pub fn has_substitution_feature(&self, tag: [u8; 4]) -> bool {
|
||||
let Some(font) = self.skrifa() else { return false };
|
||||
let Some(features) = font.gsub().ok().and_then(|g| g.feature_list().ok()) else { return false };
|
||||
features
|
||||
.feature_records()
|
||||
.iter()
|
||||
.take(MAX_FEATURES)
|
||||
.filter(|r| r.feature_tag().to_be_bytes() == tag)
|
||||
.any(|r| r.feature(features.offset_data()).is_ok_and(|f| !f.lookup_list_indices().is_empty()))
|
||||
font.gsub().ok().and_then(|g| g.feature_list().ok()).is_some_and(|features| has_feature(&features, tag))
|
||||
}
|
||||
|
||||
/// Does the face's `GPOS` table have feature `tag` with at least one lookup? At most
|
||||
/// [`MAX_FEATURES`] feature records are read; false when the face has no `GPOS` table or it
|
||||
/// cannot be read.
|
||||
pub fn has_positioning_feature(&self, tag: [u8; 4]) -> bool {
|
||||
let Some(font) = self.skrifa() else { return false };
|
||||
font.gpos().ok().and_then(|g| g.feature_list().ok()).is_some_and(|features| has_feature(&features, tag))
|
||||
}
|
||||
|
||||
/// What the features `aalt`, `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99`, `hist`,
|
||||
|
||||
@@ -1545,7 +1545,8 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
char_level.set(false);
|
||||
*chars = crate::harakat::own_chars(raw, &by_char, range.end, text, |gid| classes.get(skrifa::GlyphId::new(gid)) == 3);
|
||||
}
|
||||
if feats.proportional(st) {
|
||||
// Runs shaped together may differ in their glyph form, and a width form turns `palt` off.
|
||||
if feats.proportional(st) || runs.get(source_runs.clone()).unwrap_or_default().iter().any(|(_, s)| feats.proportional(s)) {
|
||||
// `palt` is positioning only: the same glyphs set on their full widths tell which
|
||||
// advances it changed (kerning and the rest change both alike).
|
||||
let full = shape(&with_more(&|s| feats.resolve_fixed_width(s)), along);
|
||||
|
||||
@@ -14,7 +14,7 @@ use vectorcraft_geom::{Affine, Anchor, AnchorKind, BezPath, PathData, Point, Sub
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_pathops::{Cap, Join};
|
||||
|
||||
use crate::{Action, Tool, ToolContext};
|
||||
use crate::{Action, PenPose, Tool, ToolContext};
|
||||
|
||||
pub use anchor::AnchorTool;
|
||||
pub use curvature::{
|
||||
@@ -87,6 +87,34 @@ pub fn pressure_size(size: f64, variation: f64, pressure: f64) -> f64 {
|
||||
/// The narrowest a Blob Brush or Eraser stroke gets, in points (their Size field's minimum).
|
||||
pub const MIN_BRUSH_SIZE: f64 = 0.1;
|
||||
|
||||
/// A pen's tilt as a lean on the page (each tilt's tangent) and its angle from upright in degrees,
|
||||
/// as Pointer Events' tiltX and tiltY convert to an altitude and an azimuth.
|
||||
fn pen_lean(tilt: [f32; 2]) -> ([f64; 2], f64) {
|
||||
let [x, y] = tilt.map(|d| f64::from(d).to_radians().tan());
|
||||
([x, y], x.hypot(y).atan().to_degrees())
|
||||
}
|
||||
|
||||
/// Which way pose `q` leans, in degrees counter-clockwise on the page from leaning to the right,
|
||||
/// when it leans 1° or more from upright (`path.eraseRegion` keeps the bearing before a pen
|
||||
/// nearer upright than that).
|
||||
pub(crate) fn pen_bearing(q: PenPose) -> Option<f64> {
|
||||
let ([x, y], from_upright) = pen_lean(q.tilt?);
|
||||
(from_upright >= 1.0).then(|| (-y).atan2(x).to_degrees())
|
||||
}
|
||||
|
||||
/// The 0..1 that each of the Eraser's variation modes Pressure, Tilt, Bearing and Rotation reads
|
||||
/// from a pen at `pressure` (0..1) held as `pose`, leaning toward `bearing` (degrees, from
|
||||
/// [`pen_bearing`]): 0 gives the value less its variation and 1 the value plus it, as
|
||||
/// `path.eraseRegion` reads a stroke's points. Tilt reads 1 upright and 0 lying flat; Bearing and
|
||||
/// Rotation read ½ plus the angle over 360°, the rotation turned counter-clockwise. What the pen
|
||||
/// does not give reads ½, the value itself.
|
||||
pub(crate) fn pen_controls(pressure: f64, pose: Option<PenPose>, bearing: Option<f64>) -> [f64; 4] {
|
||||
let tilt = pose.and_then(|q| q.tilt).map_or(0.5, |t| 1.0 - pen_lean(t).1 / 90.0);
|
||||
let rotation = pose.and_then(|q| q.rotation).map_or(0.5, |r| 0.5 + vectorcraft_geom::normalize_deg(-f64::from(r)) / 360.0);
|
||||
let bearing = bearing.map_or(0.5, |b| 0.5 + b / 360.0);
|
||||
[pressure, tilt, bearing, rotation].map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 })
|
||||
}
|
||||
|
||||
/// Create a drawing tool by id (None = not one of ours).
|
||||
pub fn create(id: &str) -> Option<Box<dyn Tool>> {
|
||||
Some(match id {
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
//! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and
|
||||
//! the pen's tilt and barrel rotation where the pen reads them (`[x, y, pressure, tiltX, tiltY,
|
||||
//! rotation]` points, `null` for what a point lacks) for brushes that vary with them. The Blob
|
||||
//! Brush and Eraser also record pressure when their Size varies with Pressure. The other tools
|
||||
//! Brush and Eraser also record pressure when their Size varies with Pressure, and the Eraser
|
||||
//! records the pressure, tilt and rotation that its Angle, Roundness and Size variations follow;
|
||||
//! while it erases, its tip outline at the pointer takes the angle, roundness and size the pen
|
||||
//! gives there. The other tools
|
||||
//! collect the drag polyline (shown as an overlay) and run one command on release. With Shift
|
||||
//! held, the Blob Brush's points stay on the horizontal or
|
||||
//! vertical line through the press point. Alt held at the press, or before the Blob Brush's drag
|
||||
@@ -29,6 +32,7 @@ use std::cell::Cell;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{Calligraphic, Variation};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, ParamCurve, PathData, PathSeg, Point, Rect, Vec2, shapes};
|
||||
use vectorcraft_pathops as po;
|
||||
@@ -88,10 +92,11 @@ pub struct GestureTool {
|
||||
previewed: usize,
|
||||
id: &'static str,
|
||||
points: Vec<Point>,
|
||||
/// The pen pressure of each of `points` (the Paintbrush, and the Blob Brush and the Eraser
|
||||
/// with `size_pressure`).
|
||||
/// The pen pressure of each of `points` (the Paintbrush, the Blob Brush with Size on Pressure,
|
||||
/// and the Eraser with any of its variations on Pressure).
|
||||
pressures: Vec<f32>,
|
||||
/// The pen's tilt and rotation at each of `points` (the Paintbrush only).
|
||||
/// The pen's tilt and rotation at each of `points` (the Paintbrush, and the Eraser with any of
|
||||
/// its variations on Tilt, Bearing or Rotation).
|
||||
poses: Vec<Option<PenPose>>,
|
||||
active: bool,
|
||||
began: bool,
|
||||
@@ -117,16 +122,22 @@ pub struct GestureTool {
|
||||
pub fidelity: f64,
|
||||
/// Brush / eraser diameter in points (the Eraser's across its tip's long axis).
|
||||
pub size: f64,
|
||||
/// Blob Brush and Eraser Tool Options' Size set to Pressure (else Fixed): the tip is `size` −
|
||||
/// `size_variation` wide at the lightest pen pressure and `size` + `size_variation` at the
|
||||
/// heaviest.
|
||||
pub size_pressure: bool,
|
||||
/// Blob Brush and Eraser Tool Options' Size mode: Fixed or Pressure for the Blob Brush (with
|
||||
/// Pressure the tip is `size` − `size_variation` wide at the lightest pen pressure and `size` +
|
||||
/// `size_variation` at the heaviest), and any [`Variation`] for the Eraser.
|
||||
pub size_mode: Variation,
|
||||
/// Blob Brush and Eraser Tool Options' Size Variation, in points.
|
||||
pub size_variation: f64,
|
||||
/// The angle of the Blob Brush or Eraser tip's long axis, in degrees counter-clockwise from horizontal.
|
||||
pub angle: f64,
|
||||
/// The Blob Brush or Eraser tip's short axis in percent of its long one (100: round).
|
||||
pub roundness: f64,
|
||||
/// Eraser Tool Options' Angle mode and its Variation in degrees (0 to 180).
|
||||
pub angle_mode: Variation,
|
||||
pub angle_variation: f64,
|
||||
/// Eraser Tool Options' Roundness mode and its Variation in percent (0 to 100).
|
||||
pub roundness_mode: Variation,
|
||||
pub roundness_variation: f64,
|
||||
/// Fill new pencil/brush strokes.
|
||||
pub fill: bool,
|
||||
/// "Keep selected": select the path a Pencil, Paintbrush or Blob Brush stroke draws, continues
|
||||
@@ -176,6 +187,9 @@ pub struct GestureTool {
|
||||
tip_at: Option<Point>,
|
||||
/// A pen pressed less than fully at a point of the stroke whose pressure is kept.
|
||||
light: bool,
|
||||
/// Which way the pen leaned at the last point of the stroke where it leaned 1° or more from
|
||||
/// upright ([`super::pen_bearing`]), for the Eraser's tip outline.
|
||||
bearing: Option<f64>,
|
||||
/// The length of the stroke, in points.
|
||||
length: f64,
|
||||
/// The outline of the area a Blob Brush or Eraser drag covers, as far as it is built
|
||||
@@ -829,10 +843,14 @@ impl GestureTool {
|
||||
redraw: None,
|
||||
fidelity,
|
||||
size: 10.0,
|
||||
size_pressure: false,
|
||||
size_mode: Variation::Fixed,
|
||||
size_variation: 0.0,
|
||||
angle: 0.0,
|
||||
roundness: 100.0,
|
||||
angle_mode: Variation::Fixed,
|
||||
angle_variation: 0.0,
|
||||
roundness_mode: Variation::Fixed,
|
||||
roundness_variation: 0.0,
|
||||
fill: false,
|
||||
keep_selected: id != "blobBrush",
|
||||
// Off, as Pencil Tool Options ships it: Alt keeps drawing a closed path until it is on.
|
||||
@@ -852,6 +870,7 @@ impl GestureTool {
|
||||
pressed: Point::ZERO,
|
||||
tip_at: None,
|
||||
light: false,
|
||||
bearing: None,
|
||||
length: 0.0,
|
||||
area: Cell::new(None),
|
||||
area_pending: Cell::new(false),
|
||||
@@ -908,15 +927,40 @@ impl GestureTool {
|
||||
self.length += last.distance(p);
|
||||
}
|
||||
self.points.push(p);
|
||||
if self.id == "paintbrush" || (self.varies_size() && self.size_pressure) {
|
||||
let modes = self.tip_modes();
|
||||
// The poses go out beside the pressures (`stroke_json`), so a stroke that keeps one keeps both.
|
||||
let posed = self.id == "paintbrush" || modes.iter().any(|m| matches!(m, Variation::Tilt | Variation::Bearing | Variation::Rotation));
|
||||
if posed || modes.contains(&Variation::Pressure) {
|
||||
self.pressures.push(ev.pressure);
|
||||
self.light |= ev.pressure < 1.0;
|
||||
}
|
||||
if self.id == "paintbrush" {
|
||||
self.poses.push(ev.pen.map(PenPose::sanitized));
|
||||
if posed {
|
||||
let pose = ev.pen.map(PenPose::sanitized);
|
||||
self.bearing = pose.and_then(super::pen_bearing).or(self.bearing);
|
||||
self.poses.push(pose);
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the Eraser's last stroke sample the pen's tilt and rotation of the event `ev`, a drag
|
||||
/// within a pixel of that sample that adds none: a pen turned or tilted in place turns its tip
|
||||
/// there, in the outline and in what the release erases. The sample keeps its pressure, which
|
||||
/// the area outline of the drag was built with, and its pose when `ev` reads none.
|
||||
fn refresh_last_pose(&mut self, ev: &PointerEvent) {
|
||||
if self.id != "eraser" || self.poses.len() != self.points.len() || ev.pen.is_none() {
|
||||
return;
|
||||
}
|
||||
let pose = ev.pen.map(PenPose::sanitized);
|
||||
let Some(last) = self.poses.last_mut() else { return };
|
||||
let had_bearing = last.and_then(super::pen_bearing).is_some();
|
||||
*last = pose;
|
||||
// The bearing is that of the last sample the pen leaned at, as `push` keeps it.
|
||||
self.bearing = match pose.and_then(super::pen_bearing) {
|
||||
Some(b) => Some(b),
|
||||
None if had_bearing => self.poses.iter().rev().find_map(|q| q.and_then(super::pen_bearing)),
|
||||
None => self.bearing,
|
||||
};
|
||||
}
|
||||
|
||||
/// Would a press with `m` held draw a straight Pencil line? Shift or Alt held, unless Alt lends
|
||||
/// the Smooth tool: the rule `PointerKind::Down` sets `straight` by.
|
||||
fn straight_at_press(&self, m: Mods) -> bool {
|
||||
@@ -975,12 +1019,14 @@ impl GestureTool {
|
||||
}
|
||||
|
||||
/// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline
|
||||
/// `size` across at its angle and roundness, at the zoom, black on a white halo so it reads on
|
||||
/// `size` across at its angle and roundness (the Eraser's as the pen varies them while it
|
||||
/// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on
|
||||
/// any art. Precise cursors show only the crosshair, and smoothing shows no tip.
|
||||
fn tip_outline(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
let Some(at) = self.tip_at.filter(|_| !self.smoothing && !cx.precise_cursors) else { return vec![] };
|
||||
let tip = if self.id == "blobBrush" { blob_tip(self.angle, self.roundness) } else { eraser_tip(self.angle, self.roundness) };
|
||||
let r = self.size / 2.0;
|
||||
let [angle, roundness, size] = self.tip_now();
|
||||
let tip = if self.id == "blobBrush" { blob_tip(angle, roundness) } else { eraser_tip(angle, roundness) };
|
||||
let r = size / 2.0;
|
||||
// A tolerance relative to the radius: four arcs at any size or zoom.
|
||||
let circle = kurbo::Shape::to_path(&kurbo::Circle::new(Point::ORIGIN, r), 0.1 * r.max(1e-6));
|
||||
let path = Affine::translate(at.to_vec2()) * tip * circle;
|
||||
@@ -999,6 +1045,7 @@ impl GestureTool {
|
||||
self.previewed = 0;
|
||||
self.shift_line = None;
|
||||
self.light = false;
|
||||
self.bearing = None;
|
||||
self.length = 0.0;
|
||||
self.area.set(None);
|
||||
self.area_pending.set(false);
|
||||
@@ -1064,7 +1111,53 @@ impl GestureTool {
|
||||
/// keeps its Size).
|
||||
fn size_pressures(&self) -> Option<&[f32]> {
|
||||
let pressed = self.pressures.len() == self.points.len() && self.light;
|
||||
(self.varies_size() && self.size_pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice())
|
||||
(self.tip_modes()[2] == Variation::Pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice())
|
||||
}
|
||||
|
||||
/// How the tip's angle, roundness and size vary: the Eraser's three modes, the Blob Brush's
|
||||
/// Size mode (its angle and roundness stay fixed), and Fixed for the other tools. A mode whose
|
||||
/// Variation is 0 is Fixed.
|
||||
fn tip_modes(&self) -> [Variation; 3] {
|
||||
let fixed_at_zero = |mode: Variation, v: f64| if v > 0.0 { mode } else { Variation::Fixed };
|
||||
match self.id {
|
||||
"eraser" => [
|
||||
fixed_at_zero(self.angle_mode, self.angle_variation),
|
||||
fixed_at_zero(self.roundness_mode, self.roundness_variation),
|
||||
fixed_at_zero(self.size_mode, self.size_variation),
|
||||
],
|
||||
"blobBrush" => [Variation::Fixed, Variation::Fixed, fixed_at_zero(self.size_mode, self.size_variation)],
|
||||
_ => [Variation::Fixed; 3],
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eraser's angle, roundness and size where its tip outline shows: while it erases, each
|
||||
/// value on a mode that follows the pen goes from the value less its Variation to the value
|
||||
/// plus it as the pen reads now (the pressure once the pen has pressed less than fully, the
|
||||
/// tilt and rotation of the last point, and the bearing of the last point the pen leaned 1° or
|
||||
/// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a
|
||||
/// pen that gives no reading, the values themselves. The Blob Brush's are its own values.
|
||||
fn tip_now(&self) -> [f64; 3] {
|
||||
let base = [self.angle, self.roundness, self.size];
|
||||
if self.id != "eraser" || !self.active {
|
||||
return base;
|
||||
}
|
||||
let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 };
|
||||
let controls = super::pen_controls(pressure, self.poses.last().copied().flatten(), self.bearing);
|
||||
let variations = [self.angle_variation, self.roundness_variation, self.size_variation];
|
||||
let mut out = base;
|
||||
for (i, (v, mode)) in out.iter_mut().zip(self.tip_modes()).enumerate() {
|
||||
let c = match mode {
|
||||
Variation::Pressure => controls[0],
|
||||
Variation::Tilt => controls[1],
|
||||
Variation::Bearing => controls[2],
|
||||
Variation::Rotation => controls[3],
|
||||
Variation::Fixed | Variation::Random => continue,
|
||||
};
|
||||
// The size goes past a nib's 1296 pt, as `path.eraseRegion` sweeps it.
|
||||
*v = if i == 2 { super::pressure_size(*v, variations[i], c) } else { Calligraphic::moved(i, *v, variations[i] * (2.0 * c - 1.0)) };
|
||||
}
|
||||
let [angle, roundness, size] = out;
|
||||
[angle, roundness.clamp(1.0, 100.0), size.max(super::MIN_BRUSH_SIZE)]
|
||||
}
|
||||
|
||||
/// The stroke's points: `[x, y, pressure, tiltX, tiltY, rotation]` when a pen read its tilt or
|
||||
@@ -1254,7 +1347,7 @@ impl GestureTool {
|
||||
json!({
|
||||
"points": self.stroke_json(),
|
||||
"size": self.size,
|
||||
"sizeMode": if self.size_pressure { "pressure" } else { "fixed" },
|
||||
"sizeMode": self.size_mode.id(),
|
||||
"sizeVariation": self.size_variation,
|
||||
"fidelity": self.fidelity,
|
||||
"angle": self.angle,
|
||||
@@ -1268,10 +1361,14 @@ impl GestureTool {
|
||||
json!({
|
||||
"points": self.stroke_json(),
|
||||
"size": self.size,
|
||||
"sizeMode": if self.size_pressure { "pressure" } else { "fixed" },
|
||||
"sizeMode": self.size_mode.id(),
|
||||
"sizeVariation": self.size_variation,
|
||||
"angle": self.angle,
|
||||
"roundness": self.roundness
|
||||
"angleMode": self.angle_mode.id(),
|
||||
"angleVariation": self.angle_variation,
|
||||
"roundness": self.roundness,
|
||||
"roundnessMode": self.roundness_mode.id(),
|
||||
"roundnessVariation": self.roundness_variation
|
||||
}),
|
||||
)],
|
||||
"knife" if pts.len() >= 2 => vec![Action::Exec("path.knife".into(), json!({"points": points_json(pts)}))],
|
||||
@@ -1385,6 +1482,9 @@ impl Tool for GestureTool {
|
||||
let release_end = kept.unwrap_or(end);
|
||||
self.near_start = self.release_closes_near_start(cx, release_end);
|
||||
self.connects = self.connects_at(cx, release_end).is_some();
|
||||
if self.points.last().is_some_and(|l| l.distance(p) < cx.tol(1.0)) {
|
||||
self.refresh_last_pose(ev);
|
||||
}
|
||||
return vec![];
|
||||
}
|
||||
self.push(p, ev);
|
||||
@@ -1438,13 +1538,17 @@ impl Tool for GestureTool {
|
||||
}
|
||||
} else if self.points.last().is_some_and(|l| l.distance(p) >= cx.tol(1.0)) {
|
||||
self.push(end, ev);
|
||||
} else if self.grid_snaps(cx)
|
||||
&& !self.smoothing
|
||||
&& self.points.len() > 1
|
||||
&& let Some(last) = self.points.last_mut()
|
||||
{
|
||||
// The last step was where the button went up: it moves where that snaps.
|
||||
*last = end;
|
||||
} else {
|
||||
// A release within a pixel of the last step gives it the pen's pose there.
|
||||
self.refresh_last_pose(ev);
|
||||
if self.grid_snaps(cx)
|
||||
&& !self.smoothing
|
||||
&& self.points.len() > 1
|
||||
&& let Some(last) = self.points.last_mut()
|
||||
{
|
||||
// The last step was where the button went up: it moves where that snaps.
|
||||
*last = end;
|
||||
}
|
||||
}
|
||||
let out = if cancel { vec![Action::Cancel] } else { self.finish(cx, ev.mods) };
|
||||
self.active = false;
|
||||
@@ -1666,7 +1770,7 @@ impl Tool for GestureTool {
|
||||
json!({
|
||||
"fidelity": self.fidelity,
|
||||
"size": self.size,
|
||||
"sizeMode": if self.size_pressure { "pressure" } else { "fixed" },
|
||||
"sizeMode": self.size_mode.id(),
|
||||
"sizeVariation": self.size_variation,
|
||||
"angle": self.angle,
|
||||
"roundness": self.roundness,
|
||||
@@ -1676,10 +1780,14 @@ impl Tool for GestureTool {
|
||||
}
|
||||
"eraser" => json!({
|
||||
"size": self.size,
|
||||
"sizeMode": if self.size_pressure { "pressure" } else { "fixed" },
|
||||
"sizeMode": self.size_mode.id(),
|
||||
"sizeVariation": self.size_variation,
|
||||
"angle": self.angle,
|
||||
"roundness": self.roundness
|
||||
"angleMode": self.angle_mode.id(),
|
||||
"angleVariation": self.angle_variation,
|
||||
"roundness": self.roundness,
|
||||
"roundnessMode": self.roundness_mode.id(),
|
||||
"roundnessVariation": self.roundness_variation
|
||||
}),
|
||||
_ => Value::Null,
|
||||
}
|
||||
@@ -1688,12 +1796,19 @@ impl Tool for GestureTool {
|
||||
match key {
|
||||
"fidelity" => self.fidelity = v.as_f64().unwrap_or(self.fidelity).clamp(super::min_fidelity(self.id), 100.0),
|
||||
"size" => self.size = v.as_f64().unwrap_or(self.size).clamp(0.1, 1000.0),
|
||||
"sizeMode" if self.varies_size() => match v.as_str() {
|
||||
Some("pressure") => self.size_pressure = true,
|
||||
Some("fixed") => self.size_pressure = false,
|
||||
// The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size
|
||||
// take any mode.
|
||||
"sizeMode" if self.varies_size() => match v.as_str().and_then(Variation::parse) {
|
||||
Some(m) if self.id == "eraser" || matches!(m, Variation::Fixed | Variation::Pressure) => self.size_mode = m,
|
||||
_ => {}
|
||||
},
|
||||
"angleMode" if self.id == "eraser" => self.angle_mode = v.as_str().and_then(Variation::parse).unwrap_or(self.angle_mode),
|
||||
"roundnessMode" if self.id == "eraser" => self.roundness_mode = v.as_str().and_then(Variation::parse).unwrap_or(self.roundness_mode),
|
||||
"sizeVariation" if self.varies_size() => self.size_variation = v.as_f64().unwrap_or(self.size_variation).clamp(0.0, 1000.0),
|
||||
"angleVariation" if self.id == "eraser" => self.angle_variation = v.as_f64().unwrap_or(self.angle_variation).clamp(0.0, 180.0),
|
||||
"roundnessVariation" if self.id == "eraser" => {
|
||||
self.roundness_variation = v.as_f64().unwrap_or(self.roundness_variation).clamp(0.0, 100.0)
|
||||
}
|
||||
"angle" => self.angle = v.as_f64().unwrap_or(self.angle).clamp(-180.0, 180.0),
|
||||
"roundness" => self.roundness = v.as_f64().unwrap_or(self.roundness).clamp(if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0),
|
||||
"fill" => self.fill = v.as_bool().unwrap_or(self.fill),
|
||||
|
||||
@@ -527,10 +527,20 @@ fn blob_brush_sends_keep_selected_and_merge_only_with_selection() {
|
||||
"{acts:?}"
|
||||
);
|
||||
}
|
||||
// The Eraser keeps Size (Fixed by default), Angle and Roundness: a round tip by default.
|
||||
// The Eraser keeps Size, Angle and Roundness, each Fixed by default: a round tip by default.
|
||||
assert_eq!(
|
||||
GestureTool::new("eraser").options(),
|
||||
json!({"size": 10.0, "sizeMode": "fixed", "sizeVariation": 0.0, "angle": 0.0, "roundness": 100.0})
|
||||
json!({
|
||||
"size": 10.0,
|
||||
"sizeMode": "fixed",
|
||||
"sizeVariation": 0.0,
|
||||
"angle": 0.0,
|
||||
"angleMode": "fixed",
|
||||
"angleVariation": 0.0,
|
||||
"roundness": 100.0,
|
||||
"roundnessMode": "fixed",
|
||||
"roundnessVariation": 0.0
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2768,6 +2778,161 @@ fn the_blob_brush_and_the_eraser_show_their_tip_at_the_pointer() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variation menus: the Eraser keeps each mode and
|
||||
/// Variation, the release sends them with the pen's readings along the drag, and while it erases
|
||||
/// its tip outline at the pointer takes the angle, roundness and size the pen gives there. The Blob
|
||||
/// Brush's Size takes Fixed and Pressure only, and it has no Angle or Roundness menus.
|
||||
#[test]
|
||||
fn the_eraser_tip_follows_its_variation_modes() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
// The bounds of the tip outline, the last two overlays (its halo and its line).
|
||||
let tip = |t: &GestureTool| match &t.overlays(&cx)[..] {
|
||||
[.., Overlay::Path { path: halo, width: 3.0, .. }, Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => {
|
||||
assert_eq!(halo, path);
|
||||
vectorcraft_geom::Shape::bounding_box(path)
|
||||
}
|
||||
o => panic!("{o:?}"),
|
||||
};
|
||||
let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| {
|
||||
assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}");
|
||||
};
|
||||
let mut t = GestureTool::new("eraser");
|
||||
assert_eq!(
|
||||
(t.options()["angleMode"].clone(), t.options()["roundnessMode"].clone(), t.options()["sizeMode"].clone()),
|
||||
(json!("fixed"), json!("fixed"), json!("fixed")),
|
||||
"Fixed by default"
|
||||
);
|
||||
for (k, v) in [
|
||||
("size", json!(20)),
|
||||
("roundness", json!(25)),
|
||||
("angleMode", json!("rotation")),
|
||||
("angleVariation", json!(90)),
|
||||
("roundnessMode", json!("random")),
|
||||
("roundnessVariation", json!(10)),
|
||||
("sizeMode", json!("tilt")),
|
||||
("sizeVariation", json!(8)),
|
||||
] {
|
||||
t.set_option(k, &v);
|
||||
}
|
||||
let o = t.options();
|
||||
assert_eq!(
|
||||
[&o["angleMode"], &o["angleVariation"], &o["roundnessMode"], &o["roundnessVariation"], &o["sizeMode"], &o["sizeVariation"]],
|
||||
[&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)]
|
||||
);
|
||||
// A mode it does not have leaves the mode as it was; a Variation is kept within its range.
|
||||
t.set_option("angleMode", &json!("wheel"));
|
||||
t.set_option("roundnessVariation", &json!(500));
|
||||
assert_eq!((t.options()["angleMode"].clone(), t.options()["roundnessVariation"].clone()), (json!("rotation"), json!(100.0)));
|
||||
t.set_option("roundnessVariation", &json!(10));
|
||||
// Before a press the outline is the set tip: 20 by 5 pt, lying level.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 100.0, 50.0));
|
||||
near(tip(&t), (90.0, 47.5, 110.0, 52.5));
|
||||
// Erasing with the barrel turned half way round and the pen upright, the tip stands upright and
|
||||
// is 28 by 7 pt; Random leaves the roundness as set.
|
||||
let pen = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(180.0) });
|
||||
t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
|
||||
t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
near(tip(&t), (196.5, 36.0, 203.5, 64.0));
|
||||
let acts = t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
|
||||
let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") };
|
||||
assert_eq!(c, "path.eraseRegion");
|
||||
assert_eq!(
|
||||
[&v["angleMode"], &v["angleVariation"], &v["roundnessMode"], &v["roundnessVariation"], &v["sizeMode"], &v["sizeVariation"]],
|
||||
[&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)]
|
||||
);
|
||||
assert_eq!(
|
||||
v["points"],
|
||||
json!([[100.0, 50.0, 0.5, 0.0, 0.0, 180.0], [200.0, 50.0, 0.5, 0.0, 0.0, 180.0]]),
|
||||
"the pen's readings go with the points"
|
||||
);
|
||||
// A mouse drag, which reads no tilt or rotation, keeps the set tip.
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 50.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 50.0));
|
||||
near(tip(&t), (190.0, 47.5, 210.0, 52.5));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 50.0));
|
||||
// A point without a reading after one with it goes back to the set tip there, as the release
|
||||
// erases it.
|
||||
t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
|
||||
t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
near(tip(&t), (190.0, 47.5, 210.0, 52.5));
|
||||
t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
|
||||
// The Blob Brush's Size is Fixed or Pressure, and its Angle and Roundness have no menus.
|
||||
let mut b = GestureTool::new("blobBrush");
|
||||
b.set_option("sizeMode", &json!("tilt"));
|
||||
b.set_option("angleMode", &json!("rotation"));
|
||||
assert_eq!(b.options()["sizeMode"], json!("fixed"));
|
||||
assert!(b.options().get("angleMode").is_none() && b.options().get("roundnessVariation").is_none());
|
||||
b.set_option("sizeMode", &json!("pressure"));
|
||||
assert_eq!(b.options()["sizeMode"], json!("pressure"));
|
||||
}
|
||||
|
||||
/// The Eraser's tip outline follows a pen turned in place, which adds no stroke point, and the
|
||||
/// release erases with that reading; and its size passes 1296 pt as `path.eraseRegion` sweeps it.
|
||||
#[test]
|
||||
fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let tip = |t: &GestureTool| match &t.overlays(&cx)[..] {
|
||||
[.., Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => vectorcraft_geom::Shape::bounding_box(path),
|
||||
o => panic!("{o:?}"),
|
||||
};
|
||||
let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| {
|
||||
assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}");
|
||||
};
|
||||
let mut t = GestureTool::new("eraser");
|
||||
for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("rotation")), ("angleVariation", json!(90))] {
|
||||
t.set_option(k, &v);
|
||||
}
|
||||
let level = Some(PenPose { tilt: None, rotation: Some(0.0) });
|
||||
let turned = Some(PenPose { tilt: None, rotation: Some(180.0) });
|
||||
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
|
||||
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
near(tip(&t), (190.0, 47.5, 210.0, 52.5));
|
||||
// The barrel turns half way round with the pointer still: the tip stands upright.
|
||||
t.pointer(&cx, &PointerEvent { pen: turned, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
near(tip(&t), (197.5, 40.0, 202.5, 60.0));
|
||||
let acts = t.pointer(&cx, &PointerEvent { pen: turned, pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
|
||||
let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") };
|
||||
assert_eq!(v["points"], json!([[100.0, 50.0, 0.5, null, null, 0.0], [200.0, 50.0, 0.5, null, null, 180.0]]));
|
||||
// A release at the last point erases with the pose the pen has as it lifts.
|
||||
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
|
||||
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
let acts = t.pointer(&cx, &PointerEvent { pen: turned, pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
|
||||
let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") };
|
||||
assert_eq!(v["points"], json!([[100.0, 50.0, 0.5, null, null, 0.0], [200.0, 50.0, 0.5, null, null, 180.0]]));
|
||||
// A release there that reads no pose keeps the last one.
|
||||
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
|
||||
t.pointer(&cx, &PointerEvent { pen: turned, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
let acts = t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
|
||||
let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") };
|
||||
assert_eq!(v["points"], json!([[100.0, 50.0, 0.5, null, null, 0.0], [200.0, 50.0, 0.5, null, null, 180.0]]));
|
||||
// With Angle on Bearing, a pen that leaned only at the last point and stands up there again
|
||||
// leaves no bearing: the tip lies level, as set.
|
||||
t.set_option("angleMode", &json!("bearing"));
|
||||
let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None });
|
||||
let leaning = Some(PenPose { tilt: Some([0.0, 45.0]), rotation: None });
|
||||
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
|
||||
t.pointer(&cx, &PointerEvent { pen: leaning, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
assert!(tip(&t).height() > 6.0, "{:?}", tip(&t));
|
||||
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
near(tip(&t), (190.0, 47.5, 210.0, 52.5));
|
||||
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
|
||||
// Size 1000 with a Variation of 1000 on Tilt, the pen upright: a tip 2000 pt across.
|
||||
let mut t = GestureTool::new("eraser");
|
||||
for (k, v) in [("size", json!(1000)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(1000))] {
|
||||
t.set_option(k, &v);
|
||||
}
|
||||
let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None });
|
||||
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
|
||||
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
|
||||
near(tip(&t), (-800.0, -950.0, 1200.0, 1050.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_needs_selection_and_brackets_resize() {
|
||||
let (d, _) = doc_with_rect();
|
||||
|
||||
@@ -43,6 +43,8 @@ const ROWS: &[Row] = &[
|
||||
(&["blobBrush"], None, &["fidelity", "keepSelected", "mergeOnlySelection"]),
|
||||
// Eraser Tool Options' tip shape.
|
||||
(&["blobBrush", "eraser"], None, &["angle", "roundness"]),
|
||||
// Eraser Tool Options' Angle and Roundness variation menus and fields.
|
||||
(&["eraser"], None, &["angleMode", "angleVariation", "roundnessMode", "roundnessVariation"]),
|
||||
// Live Paint Selection Tool Options (`builder::LivePaintSelectionTool`).
|
||||
(&["livePaintSelection"], None, &["selectFills", "selectStrokes", "color", "width"]),
|
||||
// Live Paint Bucket Options (`builder::LivePaintBucketTool`).
|
||||
|
||||
@@ -66,7 +66,7 @@ use overlays::selected_anchor;
|
||||
use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay};
|
||||
pub use panes::Panes;
|
||||
pub(crate) use panes::{consolidate, pane, tile, tiled_area};
|
||||
use raster::{changed_pixels, pixel_region, upload};
|
||||
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
|
||||
pub(crate) use raster::{color_image, color_image_owned, render_job};
|
||||
pub use selection_marks::SelectionMarks;
|
||||
#[cfg(test)]
|
||||
@@ -326,7 +326,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
|
||||
// Artwork raster.
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let device_ppp = ui.ctx().pixels_per_point();
|
||||
let max_side = ui.ctx().input(|i| i.max_texture_side);
|
||||
let ppp = frame_ppp(rect.size(), device_ppp, max_side);
|
||||
// Match Renderer::render_as before recording the cache extent or building its view.
|
||||
let (w, h) = (
|
||||
((rect.width() * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX)),
|
||||
@@ -334,7 +336,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
);
|
||||
// View › Pixel Preview: the art as it rasterizes, one pixel per point, while a document pixel
|
||||
// is bigger than a screen pixel (below that the screen render already shows it).
|
||||
let pixel = (app.ui.view.pixel_preview && xf.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten();
|
||||
let pixel = (app.ui.view.pixel_preview && xf.zoom * device_ppp as f64 > 1.0).then(|| pixel_region(&xf, max_side)).flatten();
|
||||
// File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview: off, images show
|
||||
// their pixels as they rasterize, hard-edged.
|
||||
let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps;
|
||||
|
||||
@@ -5,8 +5,8 @@ use super::drag::{
|
||||
tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id,
|
||||
};
|
||||
use super::view::{
|
||||
HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, pan_pixels, rotate_about, scroll_view, touch_gestures, trackpad_turn,
|
||||
wheel, whole_pixels, zoom_about,
|
||||
HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, pan_pixels, pan_ppp, rotate_about, scroll_view, touch_gestures,
|
||||
trackpad_turn, wheel, whole_pixels, zoom_about,
|
||||
};
|
||||
use super::{Color32, Drag, Mods, Point, PointerEvent, PointerKind, Pos2, Shape, Stroke, Ui, VectorcraftApp, View, Xf, json};
|
||||
|
||||
@@ -367,7 +367,7 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2)
|
||||
let ui_zoom = app.canvas_ui_zoom;
|
||||
match d {
|
||||
Drag::Pan { start, center, .. } => {
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let ppp = pan_ppp(app, ui);
|
||||
if let Some(vm) = app.view_mut() {
|
||||
vm.center = center;
|
||||
pan_pixels(vm, (ppp, ui_zoom), whole_pixels(p - start, ppp));
|
||||
|
||||
@@ -12,7 +12,7 @@ use super::outline::{c32, node_outline, stroke_path, too_many_anchors};
|
||||
use super::view::fit_zoom;
|
||||
use super::{
|
||||
Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key,
|
||||
dim_on_canvas, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers,
|
||||
dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers,
|
||||
shows_artboards, textured_quad, vec2, view_rects,
|
||||
};
|
||||
use crate::doc_windows::Win;
|
||||
@@ -339,10 +339,13 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
|
||||
if let Some(look) = grid_look.filter(|_| grids_in_back) {
|
||||
grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look);
|
||||
}
|
||||
// View › Pixel Preview, as the canvas draws it.
|
||||
let max_side = ui.ctx().input(|i| i.max_texture_side);
|
||||
let pixel = (app.ui.view.pixel_preview && xf.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf, max_side)).flatten();
|
||||
// The pane's frame fits the largest texture side the display supports, as the canvas's does.
|
||||
let ppp = frame_ppp(rect.size(), ppp, max_side);
|
||||
let size = |l: f32| ((l * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX));
|
||||
let (pw, ph) = (size(rect.width()), size(rect.height()));
|
||||
// View › Pixel Preview, as the canvas draws it.
|
||||
let pixel = (app.ui.view.pixel_preview && xf.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten();
|
||||
let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps;
|
||||
let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st);
|
||||
let placed = placed_key(&mut app.canvas.placed_keys, &app.session, st);
|
||||
|
||||
@@ -323,6 +323,40 @@ fn other_panes_show_pixel_preview() {
|
||||
assert!(x1 > x0 && y1 > y0);
|
||||
}
|
||||
|
||||
/// A pane more device pixels across than the largest texture side the display supports renders
|
||||
/// its document within that size, as the canvas does, and the frame covers the pane.
|
||||
#[test]
|
||||
fn other_panes_render_within_the_largest_texture_side() {
|
||||
let mut app = app_with(2);
|
||||
app.canvas.panes.worker_started = true; // every pane renders on this thread
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_pixels_per_point(2.0);
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
// The first frame sets the pixels a point, the second draws at them.
|
||||
for _ in 0..2 {
|
||||
let raw = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))),
|
||||
max_texture_side: Some(1024),
|
||||
..Default::default()
|
||||
};
|
||||
ctx.run_ui(raw, |ui| app.canvas_area(ui)).textures_delta.clear();
|
||||
}
|
||||
let uid = (app.session.documents()[0].uid, 1);
|
||||
let (key, tex) = app.canvas.panes.shown.get(&uid).map(|(k, t)| (k.clone(), t.size())).expect("the other document's pane rendered");
|
||||
assert_eq!(tex[0].max(tex[1]), 1024, "the pane's frame is {tex:?} pixels");
|
||||
let (docs, cells) = panes(&app);
|
||||
let pane = docs.iter().zip(cells).find(|(i, _)| **i == 0).map(|(_, r)| r).unwrap();
|
||||
let rect = view_rects(&app, pane, ctx.pixels_per_point()).1;
|
||||
assert!(rect.width().max(rect.height()) * ctx.pixels_per_point() > 1024.0, "the pane is {rect:?} at {} pixels a point", ctx.pixels_per_point());
|
||||
assert!(
|
||||
(key.w as f32 / key.ppp - rect.width()).abs() < 1.0 && (key.h as f32 / key.ppp - rect.height()).abs() < 1.0,
|
||||
"the frame covers the pane {rect:?}: {} × {} pixels at {} a point",
|
||||
key.w,
|
||||
key.h,
|
||||
key.ppp
|
||||
);
|
||||
}
|
||||
|
||||
/// A pane's render key takes its document's [`CacheKey::placed`] value ([`placed_key`]), which a
|
||||
/// bitmap made for a test running beside this one does not move: the document holds no images.
|
||||
#[test]
|
||||
|
||||
@@ -242,9 +242,20 @@ pub(super) fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: vectorc
|
||||
}
|
||||
}
|
||||
|
||||
/// The device pixels a point that the art's frame of a canvas `size` points across renders at:
|
||||
/// the display's `ppp`, lowered when a side of the frame would be more than `max_side` pixels, the
|
||||
/// largest texture side the display supports (egui's `max_texture_side`). The frame is then drawn
|
||||
/// scaled up over the canvas, at a lower resolution.
|
||||
pub(super) fn frame_ppp(size: egui::Vec2, ppp: f32, max_side: usize) -> f32 {
|
||||
let longest = size.x.max(size.y) * ppp;
|
||||
let max = max_side.clamp(1, usize::from(u16::MAX)) as f32;
|
||||
if longest.round() <= max { ppp } else { ppp * (max / longest) }
|
||||
}
|
||||
|
||||
/// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view
|
||||
/// included. None when the view is degenerate.
|
||||
pub(super) fn pixel_region(xf: &Xf) -> Option<[i64; 4]> {
|
||||
/// included. None when the view is degenerate, or when a side of the region is more than
|
||||
/// `max_side` pixels, the largest texture side the display supports.
|
||||
pub(super) fn pixel_region(xf: &Xf, max_side: usize) -> Option<[i64; 4]> {
|
||||
let r = xf.rect;
|
||||
let corners = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| xf.to_doc(p));
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
@@ -253,6 +264,7 @@ pub(super) fn pixel_region(xf: &Xf) -> Option<[i64; 4]> {
|
||||
}
|
||||
let (x0, y0, x1, y1) = (x0.floor(), y0.floor(), x1.ceil(), y1.ceil());
|
||||
// A document pixel is bigger than a screen pixel here, so the region is about canvas-sized.
|
||||
let ok = [x0, y0, x1, y1].iter().all(|c| c.is_finite() && c.abs() < 1e9) && x1 > x0 && y1 > y0 && x1 - x0 <= 16384.0 && y1 - y0 <= 16384.0;
|
||||
let max = max_side.min(16384) as f64;
|
||||
let ok = [x0, y0, x1, y1].iter().all(|c| c.is_finite() && c.abs() < 1e9) && x1 > x0 && y1 > y0 && x1 - x0 <= max && y1 - y0 <= max;
|
||||
ok.then_some([x0 as i64, y0 as i64, x1 as i64, y1 as i64])
|
||||
}
|
||||
|
||||
@@ -2550,6 +2550,45 @@ 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");
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn the_art_renders_within_the_largest_texture_side() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width":400,"height":300})).unwrap();
|
||||
app.canvas.worker_started = true; // every frame on this thread, however long it takes
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_pixels_per_point(2.0);
|
||||
// The first frame sets the pixels a point, the second draws at them.
|
||||
for _ in 0..2 {
|
||||
let raw = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))),
|
||||
max_texture_side: Some(1024),
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
let rect = app.canvas_rect.unwrap();
|
||||
assert!(rect.width() * ctx.pixels_per_point() > 1024.0, "the canvas is {rect:?} at {} pixels a point", ctx.pixels_per_point());
|
||||
let size = app.canvas.texture.as_ref().map(|t| t.size()).unwrap();
|
||||
assert_eq!(size[0].max(size[1]), 1024, "the frame is {size:?} pixels");
|
||||
let k = app.canvas.key.clone().unwrap();
|
||||
assert!(
|
||||
(k.w as f32 / k.ppp - rect.width()).abs() < 1.0 && (k.h as f32 / k.ppp - rect.height()).abs() < 1.0,
|
||||
"the frame covers the canvas {rect:?}: {} × {} pixels at {} a point",
|
||||
k.w,
|
||||
k.h,
|
||||
k.ppp
|
||||
);
|
||||
|
||||
let xf = Xf { rect: egui::Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 500.0)), zoom: 0.5, center: Point::new(0.0, 0.0), rot: 0.0 };
|
||||
let [x0, _, x1, _] = pixel_region(&xf, 4096).expect("a region 2,000 document pixels wide");
|
||||
assert_eq!(x1 - x0, 2000);
|
||||
assert_eq!(pixel_region(&xf, 1024), None, "more than the display's largest texture");
|
||||
}
|
||||
|
||||
/// A placed document's bitmap made in the background renders the canvas again only where the
|
||||
/// objects showing its file are: both copies of the file are in the part rendered again.
|
||||
#[test]
|
||||
@@ -3425,7 +3464,8 @@ fn a_drag_back_to_its_start_renders_again_after_it() {
|
||||
assert!(!app.canvas.moved);
|
||||
}
|
||||
|
||||
/// Cache metadata, worker requests and view transforms use the renderer's bounded raster size.
|
||||
/// Cache metadata, worker requests and view transforms use the renderer's bounded raster size,
|
||||
/// on a display that reports a larger texture side than that.
|
||||
/// Keep the worker controlled so huge virtual viewports never allocate huge test images.
|
||||
#[test]
|
||||
fn canvas_render_jobs_use_renderer_limited_dimensions() {
|
||||
@@ -3436,7 +3476,11 @@ fn canvas_render_jobs_use_renderer_limited_dimensions() {
|
||||
app.canvas.worker_started = true;
|
||||
app.ui.view.rulers = false;
|
||||
let frame = |app: &mut VectorcraftApp, size, ppp| {
|
||||
let mut input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(pos2(0.0, 0.0), size)), ..Default::default() };
|
||||
let mut input = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(pos2(0.0, 0.0), size)),
|
||||
max_texture_side: Some(1 << 20),
|
||||
..Default::default()
|
||||
};
|
||||
input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().native_pixels_per_point = Some(ppp);
|
||||
let mut output = ctx.run_ui(input, |ui| show(app, ui));
|
||||
output.textures_delta.clear();
|
||||
@@ -5017,6 +5061,67 @@ fn scrolls_and_pans_move_the_view_by_whole_device_pixels() {
|
||||
frame(&mut app, vec![primary(p0 + vec2(-5.55, 22.71), false)]);
|
||||
}
|
||||
|
||||
/// On a canvas whose frame renders at fewer pixels a point than the display's ([`frame_ppp`]),
|
||||
/// the wheel and the Hand tool move the view by whole pixels of that frame.
|
||||
#[test]
|
||||
fn scrolls_and_pans_move_a_lowered_frame_by_whole_pixels() {
|
||||
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; // every frame on this thread
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_pixels_per_point(2.0);
|
||||
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
|
||||
let mut time = 0.0;
|
||||
let mut frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
time += 0.016;
|
||||
let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), max_texture_side: Some(1024), events, ..Default::default() };
|
||||
ctx.run_ui(input, |ui| show(app, ui)).textures_delta.clear();
|
||||
};
|
||||
frame(&mut app, vec![]);
|
||||
app.view_mut().unwrap().center = Point::new(200.3, 150.7);
|
||||
frame(&mut app, vec![]);
|
||||
let ppp = app.canvas.key.as_ref().map(|k| k.ppp).unwrap();
|
||||
assert!(ppp < 2.0, "the frame renders at {ppp} pixels a point");
|
||||
// The pan of the canvas's render view, in pixels of its frame.
|
||||
let pan = |app: &VectorcraftApp| {
|
||||
let v = app.view().unwrap();
|
||||
(Affine::scale(v.zoom * f64::from(ppp)) * Affine::translate(-v.center.to_vec2())).translation()
|
||||
};
|
||||
let whole = |by: vectorcraft_geom::Vec2| (by - vectorcraft_geom::Vec2::new(by.x.round(), by.y.round())).hypot() < 1e-6;
|
||||
let wheel = |d: egui::Vec2| egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: d,
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Default::default(),
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
};
|
||||
let rect = app.canvas_rect.unwrap();
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(rect.center())]);
|
||||
let start = pan(&app);
|
||||
for (k, d) in [vec2(0.37, 11.13), vec2(-12.71, 0.0), vec2(21.9, -3.83)].into_iter().enumerate() {
|
||||
frame(&mut app, vec![wheel(d)]);
|
||||
let by = pan(&app) - start;
|
||||
assert!(whole(by), "scroll {k}: the view moved {by:?} pixels of the frame");
|
||||
}
|
||||
for k in 0..60 {
|
||||
frame(&mut app, vec![]);
|
||||
let by = pan(&app) - start;
|
||||
assert!(whole(by), "frame {k} after the scrolls: the view moved {by:?} pixels of the frame");
|
||||
}
|
||||
assert!((pan(&app) - start).hypot() > 10.0, "the wheel moved the view");
|
||||
app.select_tool("hand");
|
||||
let p0 = rect.center() + vec2(0.3, 0.1);
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(p0)]);
|
||||
let start = pan(&app);
|
||||
frame(&mut app, vec![primary(p0, true)]);
|
||||
for (k, d) in [vec2(13.37, -7.61), vec2(40.19, 3.33)].into_iter().enumerate() {
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(p0 + d)]);
|
||||
let by = pan(&app) - start;
|
||||
assert!(whole(by), "drag {k}: the view moved {by:?} pixels of the frame");
|
||||
}
|
||||
frame(&mut app, vec![primary(p0 + vec2(40.19, 3.33), false)]);
|
||||
}
|
||||
|
||||
/// The part of a device pixel a scroll leaves is added to the next scroll of the same view, and
|
||||
/// dropped when the view was zoomed, turned or moved in between, when the next scroll is in
|
||||
/// another document, or when the device pixels a point changed.
|
||||
|
||||
@@ -10,10 +10,15 @@ use vectorcraft_engine::Session;
|
||||
const WINDOW: egui::Vec2 = vec2(1200.0, 900.0);
|
||||
|
||||
/// One canvas frame in a `WINDOW` window at `native` device pixels a point, with the interface
|
||||
/// zoomed by `ui_zoom`.
|
||||
/// zoomed by `ui_zoom`, on a display whose textures are up to 8,192 pixels a side.
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, (native, ui_zoom): (f32, f32), events: Vec<egui::Event>) {
|
||||
ctx.set_zoom_factor(ui_zoom);
|
||||
let mut input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, WINDOW / ui_zoom)), events, ..Default::default() };
|
||||
let mut input = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, WINDOW / ui_zoom)),
|
||||
max_texture_side: Some(8192),
|
||||
events,
|
||||
..Default::default()
|
||||
};
|
||||
input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(native);
|
||||
let mut out = ctx.run_ui(input, |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
|
||||
@@ -139,10 +139,18 @@ pub(super) fn whole_pixels(d: egui::Vec2, ppp: f32) -> (f64, f64) {
|
||||
((f64::from(d.x) * f64::from(ppp)).round(), (f64::from(d.y) * f64::from(ppp)).round())
|
||||
}
|
||||
|
||||
/// The pixels a point that the canvas's art frame renders at ([`super::frame_ppp`]): the display's,
|
||||
/// or fewer on a canvas wider than the largest texture side. Pans and scrolls move the view by
|
||||
/// whole pixels of that frame.
|
||||
pub(super) fn pan_ppp(app: &VectorcraftApp, ui: &Ui) -> f32 {
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
app.canvas_rect.map_or(ppp, |r| super::frame_ppp(r.size(), ppp, ui.ctx().input(|i| i.max_texture_side)))
|
||||
}
|
||||
|
||||
/// What the scrolls of the view have left to move ([`scroll_view`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(super) struct ScrollRest {
|
||||
/// Device pixels along the screen's axes, at most half a pixel each.
|
||||
/// Pixels of the canvas's frame along the screen's axes, at most half a pixel each.
|
||||
pub(super) x: f64,
|
||||
pub(super) y: f64,
|
||||
/// The document, the view's center, zoom and rotation, and the device pixels a point that the
|
||||
@@ -151,11 +159,11 @@ pub(super) struct ScrollRest {
|
||||
}
|
||||
|
||||
/// Scroll the active view so that its content moves `by` screen points (the wheel, a trackpad, a
|
||||
/// touch screen, a scroll bar), in whole device pixels: the part of a pixel left over is added to
|
||||
/// the next scroll. It is dropped when the view changed in between (a zoom, a turn, Fit, a pan
|
||||
/// of another kind, another document) or the device pixels a point did.
|
||||
/// touch screen, a scroll bar), in whole pixels of the canvas's frame ([`pan_ppp`]): the part of a
|
||||
/// pixel left over is added to the next scroll. It is dropped when the view changed in between (a
|
||||
/// zoom, a turn, Fit, a pan of another kind, another document) or the pixels a point did.
|
||||
pub(super) fn scroll_view(app: &mut VectorcraftApp, ui: &Ui, by: egui::Vec2) {
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let ppp = pan_ppp(app, ui);
|
||||
let ui_zoom = app.canvas_ui_zoom;
|
||||
let Some(doc) = app.session.active().map(|st| st.uid) else { return };
|
||||
let Some(vm) = app.view_mut() else { return };
|
||||
@@ -344,7 +352,7 @@ pub(super) fn scroll_bars(app: &mut VectorcraftApp, ui: &Ui, rect: egui::Rect, o
|
||||
let hot = drag.is_some() || hover.is_some_and(|p| thumb.contains(p));
|
||||
painter.rect_filled(thumb, CornerRadius::same(3), if hot { t.text_dim } else { t.text_disabled });
|
||||
}
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let ppp = pan_ppp(app, ui);
|
||||
if let Some((c, by)) = center
|
||||
&& let Some(vm) = app.view_mut()
|
||||
{
|
||||
|
||||
@@ -18,13 +18,13 @@ mod hints;
|
||||
mod status_bar;
|
||||
mod tabs;
|
||||
|
||||
pub(crate) use control_bar::group_separator;
|
||||
pub use control_bar::{
|
||||
AnchorControls, CONTROL_BAR_EDGES, CONTROL_BAR_GROUPS, anchor_buttons, anchor_controls, control_bar, control_bar_moving, control_bar_placement,
|
||||
read_hidden_groups,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use control_bar::{CONTROL_BAR_FLOAT_AT, ISOLATION_BUTTON};
|
||||
pub(crate) use control_bar::{group_separator, left_out};
|
||||
#[cfg(test)]
|
||||
use hints::hint_segments;
|
||||
pub use hints::{hint_bar, hint_strings};
|
||||
|
||||
@@ -61,6 +61,7 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon
|
||||
for (label, buttons) in groups.into_iter().take(shown) {
|
||||
let text = egui::RichText::new(label).size(12.0).color(t.text);
|
||||
if in_row && ui.available_width() < row_width(ui, &[widgets::text_width(ui, text.clone())]) + buttons_width(ui, buttons.len()) {
|
||||
left_out(ui);
|
||||
break;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
@@ -164,9 +165,13 @@ const GLOBAL_EDIT_OPTIONS_WIDTH: f32 = 24.0;
|
||||
/// It opens the Properties panel's Global Edit Options, which set the same session options, and is
|
||||
/// off and closed while Global Edit is on, as that panel's dropdown is. It sits after Recolor
|
||||
/// Artwork, ahead of the X/Y/W/H fields that the bar leaves out when it runs short of room, and is
|
||||
/// left out when the room left, less `reserve` ([`transform_reserve`]), cannot hold it.
|
||||
/// left out when the room left, less `reserve` ([`transform_reserve`]), cannot hold it ([`left_out`]).
|
||||
fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) {
|
||||
if !crate::menus::enabled(app, "select.globalEdit") || ui.available_width() < row_width(ui, &[GLOBAL_EDIT_OPTIONS_WIDTH]) + reserve {
|
||||
if !crate::menus::enabled(app, "select.globalEdit") {
|
||||
return;
|
||||
}
|
||||
if ui.available_width() < row_width(ui, &[GLOBAL_EDIT_OPTIONS_WIDTH]) + reserve {
|
||||
left_out(ui);
|
||||
return;
|
||||
}
|
||||
let on = app.session.active().is_some_and(|d| d.global_edit.is_some());
|
||||
@@ -287,6 +292,24 @@ fn boundary(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) {
|
||||
ui.data_mut(|d| d.insert_temp(key, b));
|
||||
}
|
||||
|
||||
/// The key of the pass in which a control of the row `ui` was last left out for room.
|
||||
fn left_out_key(ui: &Ui) -> egui::Id {
|
||||
ui.unique_id().with("cb-left-out")
|
||||
}
|
||||
|
||||
/// Notes that a control of the Control bar's row `ui` was left out in this pass for want of room,
|
||||
/// so the controls the bar leaves out first stay out too ([`any_left_out`]).
|
||||
pub(crate) fn left_out(ui: &mut Ui) {
|
||||
let (key, pass) = (left_out_key(ui), ui.ctx().cumulative_pass_nr());
|
||||
ui.data_mut(|d| d.insert_temp(key, pass));
|
||||
}
|
||||
|
||||
/// Whether a control of the row `ui` was left out in this pass for want of room ([`left_out`]).
|
||||
fn any_left_out(ui: &Ui) -> bool {
|
||||
let (key, pass) = (left_out_key(ui), ui.ctx().cumulative_pass_nr());
|
||||
ui.data(|d| d.get_temp::<u64>(key)) == Some(pass)
|
||||
}
|
||||
|
||||
/// The separator that ends a group of the Control bar's controls, drawn as `ui.separator()` draws
|
||||
/// one, and left out when no control follows it ([`boundary`]) or the row has no room left for it.
|
||||
pub(crate) fn group_separator(ui: &mut Ui) {
|
||||
@@ -348,20 +371,26 @@ fn transform_reserve(app: &VectorcraftApp, ui: &Ui, selected: bool) -> f32 {
|
||||
/// Align To menu and, for two or more objects, the Distribute buttons (a single object keeps the bar
|
||||
/// as it was); each shows only while the end of the bar keeps its room. Groups the panel menu has
|
||||
/// off are left out, and take no room. Without `room` (the Character group had none), all of these
|
||||
/// groups are left out, so the bar trims them from its right end before the Character group.
|
||||
/// groups are left out, so the bar trims them from its right end before the Character group. The
|
||||
/// Character group without its room, and a control left out for room here, are noted with
|
||||
/// [`left_out`].
|
||||
fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize, room: bool) -> bool {
|
||||
if !room {
|
||||
left_out(ui);
|
||||
}
|
||||
let nothing = objects == 0;
|
||||
let end = end_width(app, ui, nothing);
|
||||
if room && group_on(app, "paragraph") && crate::panels::paragraph::control_bar(app, ui, BUTTON, |ui| group_end_width(ui) + end) {
|
||||
group_end(ui);
|
||||
}
|
||||
if room
|
||||
&& group_on(app, "verticalAlignment")
|
||||
&& crate::panels::properties::vertical_align::shown(app).is_some()
|
||||
&& ui.available_width() >= buttons_width(ui, 4) + group_end_width(ui) + end
|
||||
&& crate::panels::properties::vertical_align::buttons(app, ui, BUTTON)
|
||||
{
|
||||
group_end(ui);
|
||||
if room && group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some() {
|
||||
if ui.available_width() >= buttons_width(ui, 4) + group_end_width(ui) + end {
|
||||
if crate::panels::properties::vertical_align::buttons(app, ui, BUTTON) {
|
||||
group_end(ui);
|
||||
}
|
||||
} else {
|
||||
left_out(ui);
|
||||
}
|
||||
}
|
||||
if nothing {
|
||||
// Each button shows only while the bar has room left for it, so Preferences can show
|
||||
@@ -378,14 +407,24 @@ fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize
|
||||
}
|
||||
let transform = group_on(app, "transform");
|
||||
let end = if transform { separator_width(ui) + end } else { 0.0 };
|
||||
if room && group_on(app, "alignDistribute") && ui.available_width() >= buttons_width(ui, 7) + end {
|
||||
if room && group_on(app, "alignDistribute") {
|
||||
if ui.available_width() < buttons_width(ui, 7) + end {
|
||||
left_out(ui);
|
||||
return transform;
|
||||
}
|
||||
crate::panels::align::align_buttons(app, ui, BUTTON);
|
||||
if ui.available_width() >= crate::panels::align::align_to_menu_width(BUTTON) + ui.spacing().item_spacing.x + end {
|
||||
crate::panels::align::align_to_menu(app, ui, BUTTON);
|
||||
if objects > 1 && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) + end {
|
||||
ui.add_space(GROUP_GAP);
|
||||
crate::panels::align::distribute_buttons(app, ui, BUTTON);
|
||||
if objects > 1 {
|
||||
if ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) + end {
|
||||
ui.add_space(GROUP_GAP);
|
||||
crate::panels::align::distribute_buttons(app, ui, BUTTON);
|
||||
} else {
|
||||
left_out(ui);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
left_out(ui);
|
||||
}
|
||||
if transform {
|
||||
boundary(ui, separator);
|
||||
@@ -573,7 +612,7 @@ fn dock(app: &mut VectorcraftApp, edge: &str) {
|
||||
fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
let resp = crate::panels::menu_button(ui, "control", rect);
|
||||
egui::Popup::menu(&resp).show(|ui| {
|
||||
ui.set_min_width(160.0);
|
||||
widgets::menu_min_width(ui, 160.0);
|
||||
widgets::menu_scroll(ui, |ui| {
|
||||
for group in CONTROL_BAR_GROUPS {
|
||||
if widgets::menu_item(ui, group_label(group), true, group_on(app, group)) {
|
||||
@@ -594,9 +633,10 @@ fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
|
||||
/// and the width profile, and the separator after them while a control follows ([`group_separator`]).
|
||||
/// Short of room, the bar leaves out the width profile first, then the Stroke link with the weight,
|
||||
/// then the two chips; each shows only while the bar has room for all of it and `reserve` after it
|
||||
/// ([`transform_reserve`]).
|
||||
/// ([`transform_reserve`]), and a control left out is noted with [`left_out`].
|
||||
fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) {
|
||||
if ui.available_width() < row_width(ui, &[CHIP_WIDTH, CHIP_WIDTH]) + reserve {
|
||||
left_out(ui);
|
||||
return;
|
||||
}
|
||||
let shown_stroke = crate::panels::current_stroke(app);
|
||||
@@ -610,11 +650,13 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) {
|
||||
if ui.available_width() >= row_width(ui, &[link, WEIGHT_FIELD_WIDTH]) + reserve {
|
||||
stroke_panel::link(app, ui, tl!("Stroke:"));
|
||||
stroke_panel::weight_field(app, ui, "cb-stroke", weight, WEIGHT_FIELD_WIDTH);
|
||||
if ui.available_width() >= row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve
|
||||
&& let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref()))
|
||||
{
|
||||
if ui.available_width() < row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve {
|
||||
left_out(ui);
|
||||
} else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) {
|
||||
app.run("stroke.set", json!({"profile": id})).ok();
|
||||
}
|
||||
} else {
|
||||
left_out(ui);
|
||||
}
|
||||
group_end(ui);
|
||||
}
|
||||
@@ -625,7 +667,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) {
|
||||
/// the bar leaves out Global Edit Options first, then Recolor Artwork, then the Style link with its
|
||||
/// chip. The Opacity link with its field and the Style link with its chip each show only while the
|
||||
/// bar has room for all of it and `reserve` after it ([`transform_reserve`]), so the narrower Style
|
||||
/// part can show without the Opacity part.
|
||||
/// part can show without the Opacity part. A control left out is noted with [`left_out`].
|
||||
fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity: f32, selected: bool, reserve: f32) {
|
||||
let (opacity_on, style_on) = (group_on(app, "opacity"), group_on(app, "graphicStyle") && selected);
|
||||
let mut drawn = false;
|
||||
@@ -642,10 +684,15 @@ fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity:
|
||||
app.run("transparency.set", json!({"opacity": o.clamp(0.0, 100.0)})).ok();
|
||||
}
|
||||
drawn = true;
|
||||
} else {
|
||||
left_out(ui);
|
||||
}
|
||||
}
|
||||
let text = egui::RichText::new(tl!("Style:")).size(12.0).color(t.text).underline();
|
||||
if style_on && ui.available_width() >= GROUP_GAP + row_width(ui, &[widgets::text_width(ui, text.clone()), CHIP_WIDTH]) + reserve {
|
||||
let style_room = GROUP_GAP + row_width(ui, &[widgets::text_width(ui, text.clone()), CHIP_WIDTH]) + reserve;
|
||||
if style_on && ui.available_width() < style_room {
|
||||
left_out(ui);
|
||||
} else if style_on {
|
||||
// Style picker: the selection's graphic style; its menu applies another.
|
||||
ui.add_space(GROUP_GAP);
|
||||
if ui.link(text).clicked() {
|
||||
@@ -656,10 +703,9 @@ fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity:
|
||||
egui::Popup::menu(&resp).show(|ui| crate::panels::graphic_styles::picker(app, ui));
|
||||
// Recolor Artwork, when the selection has colours to recolour.
|
||||
let colored = app.session.active().is_some_and(|st| crate::canvas::has_colors(&st.doc, &st.selection.objects));
|
||||
if colored
|
||||
&& ui.available_width() >= buttons_width(ui, 1) + reserve
|
||||
&& widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, BUTTON).clicked()
|
||||
{
|
||||
if colored && ui.available_width() < buttons_width(ui, 1) + reserve {
|
||||
left_out(ui);
|
||||
} else if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, BUTTON).clicked() {
|
||||
crate::menus::invoke(app, "ui.recolorDialog", json!({}));
|
||||
}
|
||||
global_edit_options(app, ui, reserve);
|
||||
@@ -670,6 +716,58 @@ fn opacity_and_style(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, opacity:
|
||||
}
|
||||
}
|
||||
|
||||
/// The width of the chevron that opens the Select Similar Options menu.
|
||||
const SELECT_SIMILAR_MENU_WIDTH: f32 = 16.0;
|
||||
|
||||
/// The label of each attribute of [`vectorcraft_engine::cmd::SIMILAR`] in the Select Similar Options
|
||||
/// menu, translated.
|
||||
fn similar_label(by: &str) -> &'static str {
|
||||
match by {
|
||||
"all" => tl!("All"),
|
||||
"fillColor" => tl!("Fill Color"),
|
||||
"fillAndStroke" => tl!("Fill & Stroke"),
|
||||
"strokeColor" => tl!("Stroke Color"),
|
||||
"strokeWeight" => tl!("Stroke Weight"),
|
||||
"opacity" => tl!("Opacity"),
|
||||
"blendingMode" => tl!("Blending Mode"),
|
||||
"appearance" => tl!("Appearance"),
|
||||
"graphicStyle" => tl!("Graphic Style"),
|
||||
"shapeType" => tl!("Shape"),
|
||||
_ => tl!("Symbol Instance"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Control bar's Select Similar Objects button and, beside it, the Select Similar Options menu
|
||||
/// (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=165>). The
|
||||
/// button runs `select.similar`, which selects the objects like the first selected one by the
|
||||
/// attribute kept for the session; a menu item runs it by that item's attribute, which is kept from
|
||||
/// then on, and the kept one is checked. Both are off while `select.similar` cannot run. They show
|
||||
/// together at the right end of the bar, after a separator, while something is selected and the
|
||||
/// panel menu has Object Options on, and only in the room every control ahead of them left
|
||||
/// ([`contents`]): the bar leaves them out before any other control, and while a control ahead of
|
||||
/// them was left out for room ([`any_left_out`]). Groups the panel menu has off take no room.
|
||||
fn trailing_select_similar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let selected = app.session.active().is_some_and(|st| !st.selection.objects.is_empty());
|
||||
let width = separator_width(ui) + row_width(ui, &[BUTTON, SELECT_SIMILAR_MENU_WIDTH]);
|
||||
if any_left_out(ui) || !selected || !group_on(app, "objectOptions") || ui.available_width() < width {
|
||||
return;
|
||||
}
|
||||
boundary(ui, separator);
|
||||
let enabled = crate::menus::enabled(app, "select.similar");
|
||||
if widgets::icon_button_enabled(ui, "copy", tl!("Select Similar Objects"), false, enabled, BUTTON).clicked() {
|
||||
crate::menus::invoke(app, "select.similar", json!({}));
|
||||
}
|
||||
let options = widgets::icon_button_enabled(ui, "chevron-down", tl!("Select Similar Options"), false, enabled, SELECT_SIMILAR_MENU_WIDTH);
|
||||
egui::Popup::menu(&options).show(|ui| {
|
||||
ui.set_min_width(140.0);
|
||||
for (by, _) in vectorcraft_engine::cmd::SIMILAR {
|
||||
if widgets::menu_item(ui, similar_label(by), true, app.session.select_similar == by) {
|
||||
crate::menus::invoke(app, "select.similar", json!({ "by": by }));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The Control bar's gripper, at the left end of the bar `bar`. Dragging it shows where a release
|
||||
/// puts the bar ([`release_at`] in `dock_room`, the window below the menu bar): a band along the
|
||||
/// edge it docks to, or the outline of the bar floating under the pointer. The bar stays where it is
|
||||
@@ -819,6 +917,8 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect,
|
||||
let label = egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text);
|
||||
if ui.available_width() >= widgets::text_width(ui, label.clone()) {
|
||||
ui.label(label);
|
||||
} else {
|
||||
left_out(ui);
|
||||
}
|
||||
// With the Artboard tool in use, the bar shows the active artboard's controls in place
|
||||
// of the object controls.
|
||||
@@ -862,6 +962,8 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect,
|
||||
// all; left out, it leaves out the groups between it and the link too.
|
||||
let room = !group_on(app, "character") || crate::panels::character::control_bar(app, ui, reserve);
|
||||
if !groups_before_transform(app, ui, sel.len(), room) {
|
||||
// With the Transform group off, its link and X/Y/W/H fields take no room.
|
||||
trailing_select_similar(app, ui);
|
||||
erase_trailing(ui);
|
||||
return;
|
||||
}
|
||||
@@ -875,9 +977,10 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect,
|
||||
}
|
||||
crate::panels::transform::link(app, ui);
|
||||
// The bounding box, rotated with rotated objects: its centre and its own sides.
|
||||
if let Some(b) = app.selection_box()
|
||||
&& ui.available_width() >= inline_transform_width(ui, t)
|
||||
{
|
||||
let selection_box = app.selection_box();
|
||||
if selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t) {
|
||||
left_out(ui);
|
||||
} else if let Some(b) = selection_box {
|
||||
let c = b.center();
|
||||
let origin = app.ruler_origin();
|
||||
let link = crate::panels::transform::proportional(app, ui);
|
||||
@@ -906,6 +1009,8 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect,
|
||||
crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click()));
|
||||
}
|
||||
}
|
||||
// Select Similar Objects comes last: it takes only the room every control ahead of it left.
|
||||
trailing_select_similar(app, ui);
|
||||
erase_trailing(ui);
|
||||
});
|
||||
// Controls that keep their size can still run into the button's room in a narrow window;
|
||||
|
||||
@@ -3502,6 +3502,162 @@ fn the_control_bar_shows_the_global_edit_options() {
|
||||
assert!(seen, "a wide bar has room for it");
|
||||
}
|
||||
|
||||
/// The Control bar's Select Similar Objects button selects the objects like the first selected one
|
||||
/// by the attribute kept for the session (All at first), and the Select Similar Options menu beside
|
||||
/// it selects by the item chosen, which is kept and checked from then on. Both show with something
|
||||
/// selected while the Object Options group is on, and fit inside the bar or are left out.
|
||||
#[test]
|
||||
fn the_control_bar_selects_similar_objects() {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let rect = |app: &mut crate::VectorcraftApp, x: f64, color: &str| {
|
||||
let id = app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap();
|
||||
id
|
||||
};
|
||||
let a = rect(&mut app, 20.0, "#ff0000");
|
||||
let b = rect(&mut app, 100.0, "#ff0000");
|
||||
let c = rect(&mut app, 200.0, "#0000ff");
|
||||
let ctx = egui::Context::default();
|
||||
ctx.enable_accesskit();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2400.0, 300.0));
|
||||
let frame = |app: &mut crate::VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui));
|
||||
out.textures_delta.clear();
|
||||
out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default()
|
||||
};
|
||||
type Nodes = Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>;
|
||||
let find = |nodes: &Nodes, name: &str| nodes.iter().find(|(_, n)| n.label() == Some(name) || n.value() == Some(name)).map(|(_, n)| n.clone());
|
||||
// A menu item's label carries its check mark or the room for it.
|
||||
let item = |nodes: &Nodes, name: &str| {
|
||||
nodes.iter().find(|(_, n)| n.label().or(n.value()).is_some_and(|t| t.trim_start_matches(['✓', ' ']) == name)).map(|(_, n)| n.clone())
|
||||
};
|
||||
let center = |n: &egui::accesskit::Node| {
|
||||
let b = n.bounds().unwrap_or_else(|| panic!("{n:?}"));
|
||||
egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)
|
||||
};
|
||||
let click = |app: &mut crate::VectorcraftApp, at: egui::Pos2| {
|
||||
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(app, vec![egui::Event::PointerMoved(at), press(true)]);
|
||||
frame(app, vec![press(false)]);
|
||||
frame(app, vec![]);
|
||||
frame(app, vec![])
|
||||
};
|
||||
let selected = |app: &crate::VectorcraftApp| {
|
||||
let mut ids: Vec<u64> = app.session.active().unwrap().selection.objects.iter().map(|i| i.0).collect();
|
||||
ids.sort();
|
||||
ids
|
||||
};
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
frame(&mut app, vec![]);
|
||||
let nodes = frame(&mut app, vec![]);
|
||||
assert!(find(&nodes, "Select Similar Objects").is_none() && find(&nodes, "Select Similar Options").is_none(), "nothing selected");
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
frame(&mut app, vec![]);
|
||||
let nodes = frame(&mut app, vec![]);
|
||||
let button = find(&nodes, "Select Similar Objects").unwrap_or_else(|| panic!("one rectangle: the button shows"));
|
||||
click(&mut app, center(&button));
|
||||
assert_eq!(selected(&app), vec![a, b], "All: the red rectangles");
|
||||
// The menu selects by the item chosen and keeps it.
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
frame(&mut app, vec![]);
|
||||
let options = find(&frame(&mut app, vec![]), "Select Similar Options").unwrap_or_else(|| panic!("the options menu shows"));
|
||||
let nodes = click(&mut app, center(&options));
|
||||
for label in [
|
||||
"All",
|
||||
"Fill Color",
|
||||
"Fill & Stroke",
|
||||
"Stroke Color",
|
||||
"Stroke Weight",
|
||||
"Opacity",
|
||||
"Blending Mode",
|
||||
"Appearance",
|
||||
"Graphic Style",
|
||||
"Shape",
|
||||
"Symbol Instance",
|
||||
] {
|
||||
assert!(item(&nodes, label).is_some(), "{label} in the menu");
|
||||
}
|
||||
assert!(find(&nodes, "✓ All").is_some(), "All is checked at first");
|
||||
let stroke = item(&nodes, "Stroke Color").unwrap_or_else(|| panic!("Stroke Color"));
|
||||
click(&mut app, center(&stroke));
|
||||
assert_eq!(app.session.select_similar, "strokeColor");
|
||||
assert_eq!(selected(&app), vec![a, b, c], "Stroke Color: all three share the default stroke");
|
||||
app.run("select.set", json!({"ids": [c]})).unwrap();
|
||||
frame(&mut app, vec![]);
|
||||
let nodes = frame(&mut app, vec![]);
|
||||
click(&mut app, center(&find(&nodes, "Select Similar Objects").unwrap_or_else(|| panic!("the button"))));
|
||||
assert_eq!(selected(&app), vec![a, b, c], "the button keeps Stroke Color");
|
||||
let options = find(&frame(&mut app, vec![]), "Select Similar Options").unwrap_or_else(|| panic!("the options menu"));
|
||||
let nodes = click(&mut app, center(&options));
|
||||
assert!(find(&nodes, "✓ Stroke Color").is_some(), "the kept item is checked");
|
||||
// The panel menu's Object Options group turns them off.
|
||||
app.run("window.control.options", json!({"group": "objectOptions"})).unwrap();
|
||||
frame(&mut app, vec![]);
|
||||
assert!(find(&frame(&mut app, vec![]), "Select Similar Objects").is_none(), "Object Options off");
|
||||
app.run("window.control.options", json!({"group": "objectOptions"})).unwrap();
|
||||
// At any width the button and its menu fit inside the bar together or are left out. They take
|
||||
// only the room left at the end of the bar, so they show only while the Align buttons and the
|
||||
// inline X field do too. A control ahead of them that appears in a wider bar (the Distribute
|
||||
// buttons) can take that room again, so the widest bar is the one that must show them.
|
||||
let mut seen = false;
|
||||
for width in (600..=2400).step_by(10) {
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0));
|
||||
let mut nodes = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(&mut app, ui));
|
||||
out.textures_delta.clear();
|
||||
nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
|
||||
}
|
||||
let shown = find(&nodes, "Select Similar Objects").and_then(|n| n.bounds());
|
||||
let menu = find(&nodes, "Select Similar Options").and_then(|n| n.bounds());
|
||||
assert_eq!(shown.is_some(), menu.is_some(), "{width}: the button and its menu show together");
|
||||
if let Some(b) = menu {
|
||||
assert!(b.x1 <= f64::from(width), "{width}: {b:?}");
|
||||
assert!(find(&nodes, "Horizontal Align Left").is_some(), "{width}: shown without the Align buttons");
|
||||
let x = nodes.iter().find(|(_, n)| n.label() == Some("X:") || n.value() == Some("X:")).and_then(|(_, n)| n.bounds());
|
||||
assert!(x.is_some_and(|x| x.x1 <= b.x0), "{width}: shown without the X field ahead of it: {x:?}");
|
||||
}
|
||||
seen = shown.is_some();
|
||||
}
|
||||
assert!(seen, "the widest bar has room for it");
|
||||
// With the Transform group off they still show at the end of a wide bar, after the Align
|
||||
// buttons.
|
||||
app.run("window.control.options", json!({"group": "transform", "visible": false})).unwrap();
|
||||
frame(&mut app, vec![]);
|
||||
let nodes = frame(&mut app, vec![]);
|
||||
let (button, align) = (find(&nodes, "Select Similar Objects"), find(&nodes, "Horizontal Align Left"));
|
||||
let (Some(b), Some(a)) = (button.and_then(|n| n.bounds()), align.and_then(|n| n.bounds())) else {
|
||||
panic!("Transform off: the button and the Align buttons show")
|
||||
};
|
||||
assert!(a.x1 <= b.x0, "after the Align buttons: {a:?} {b:?}");
|
||||
// With the Transform group off, its link and X/Y/W/H fields take no room: the button and its
|
||||
// menu show in the narrowest bar that holds them after every control ahead of them, and never
|
||||
// while a control ahead of them is left out.
|
||||
let mut first = None;
|
||||
for width in (600..=2400).step_by(10) {
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0));
|
||||
let mut nodes = Vec::new();
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(&mut app, ui));
|
||||
out.textures_delta.clear();
|
||||
nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
|
||||
}
|
||||
let Some(b) = find(&nodes, "Select Similar Options").and_then(|n| n.bounds()) else {
|
||||
continue;
|
||||
};
|
||||
for name in ["Stroke:", "Opacity:", "Horizontal Align Left", "Recolor Artwork"] {
|
||||
assert!(find(&nodes, name).is_some(), "{width}: shown without {name} ahead of it");
|
||||
}
|
||||
first.get_or_insert((width, b.x1));
|
||||
}
|
||||
let Some((width, end)) = first else { panic!("Transform off: a wide bar has room for them") };
|
||||
let free = f64::from(width) - end;
|
||||
assert!(free < 120.0, "Transform off: the narrowest bar that shows them, {width} pt wide, leaves {free} pt after them");
|
||||
}
|
||||
|
||||
/// At any width the Control bar shows the inline X, Y, W and H fields whole inside its right margin,
|
||||
/// or leaves all four out and keeps the Transform link; a wider bar never leaves them out once a
|
||||
/// narrower one showed them. The Align buttons, and for two objects the Distribute buttons, are
|
||||
|
||||
@@ -1377,7 +1377,7 @@ pub(crate) fn add_menu_id(name: &str) -> egui::Id {
|
||||
/// bottom bars, as other long menus do ([`widgets::menu_scroll`]).
|
||||
fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: &mut Vec<Action>) {
|
||||
egui::Popup::menu(button).id(add_menu_id(&bar.name)).show(|ui| {
|
||||
ui.set_min_width(200.0);
|
||||
widgets::menu_min_width(ui, 200.0);
|
||||
widgets::menu_scroll(ui, |ui| {
|
||||
let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect();
|
||||
let heading = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).size(12.0).color(t.text_strong));
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user