mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 18:18:35 +00:00
Merge pull request #7962 from dotCooCoo/feat/symbol-align-to-pixel-grid
Symbols: Symbol Options › Align to Pixel Grid keeps a symbol's instances on the pixel grid
This commit is contained in:
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbols",
|
||||
[],
|
||||
None,
|
||||
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}",
|
||||
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic, alignToPixelGrid: bool}], current}",
|
||||
has_doc,
|
||||
symbol_list
|
||||
),
|
||||
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Symbol…",
|
||||
[],
|
||||
None,
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_selection,
|
||||
symbol_new
|
||||
),
|
||||
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Options…",
|
||||
[],
|
||||
None,
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_doc,
|
||||
symbol_options
|
||||
),
|
||||
|
||||
@@ -69,6 +69,15 @@ fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> R
|
||||
})
|
||||
}
|
||||
|
||||
/// `alignToPixelGrid` (Symbol Options › Align to Pixel Grid): `None` when it is not given; any
|
||||
/// value other than true or false, null included, is an error.
|
||||
fn pixel_grid_param(p: &Value, cmd: &str) -> Result<Option<bool>> {
|
||||
match p.get("alignToPixelGrid") {
|
||||
None => Ok(None),
|
||||
Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, "alignToPixelGrid must be true or false")),
|
||||
}
|
||||
}
|
||||
|
||||
fn nine_slice_json(d: &Document, name: &str) -> Value {
|
||||
d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value)
|
||||
}
|
||||
@@ -187,6 +196,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"exportType": d.symbol_export_type(&sym.name).id(),
|
||||
"nineSlice": nine_slice_json(d, &sym.name),
|
||||
"type": type_id(sym.dynamic),
|
||||
"alignToPixelGrid": d.symbol_pixel_aligned(&sym.name),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -239,6 +249,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let export = export_type_param(p, C)?.unwrap_or_default();
|
||||
let nine = nine_slice_param(p, C, None)?.flatten();
|
||||
let dynamic = type_param(p, C)?.unwrap_or(false);
|
||||
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
|
||||
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
|
||||
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
|
||||
let id = s.edit("New Symbol", |d, sel| {
|
||||
@@ -249,6 +260,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_registration(&name, reg);
|
||||
d.set_symbol_export_type(&name, export);
|
||||
d.set_symbol_nine_slice(&name, nine);
|
||||
d.set_symbol_pixel_aligned(&name, pixel);
|
||||
let id = instance_in_place(d, &ids, &name, place)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
@@ -260,6 +272,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"exportType": export.id(),
|
||||
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
|
||||
"type": type_id(dynamic),
|
||||
"alignToPixelGrid": pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -270,9 +283,15 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reg = registration_param(p, C)?;
|
||||
let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?;
|
||||
let dynamic = type_param(p, C)?;
|
||||
let pixel = pixel_grid_param(p, C)?;
|
||||
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
|
||||
return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type"));
|
||||
match pixel {
|
||||
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
|
||||
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
|
||||
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
@@ -324,6 +343,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.rename_symbol_registration(&name, n);
|
||||
d.rename_symbol_export_type(&name, n);
|
||||
d.rename_symbol_nine_slice(&name, n);
|
||||
d.rename_symbol_pixel_aligned(&name, n);
|
||||
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
|
||||
d.unknown.insert(CURRENT_SYMBOL.into(), json!(n));
|
||||
}
|
||||
@@ -352,16 +372,26 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sym.dynamic = dynamic;
|
||||
fit_overrides(d, &instances_of(d, Some(&final_name)));
|
||||
}
|
||||
// Turning it on snaps the art and the instances at actual size when the edit ends
|
||||
// (`object::refresh_pixel_aligned`).
|
||||
if let Some(on) = pixel {
|
||||
d.set_symbol_pixel_aligned(&final_name, on);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(json!({
|
||||
"name": final_name,
|
||||
"registration": d.symbol_registration(&final_name).0,
|
||||
"exportType": d.symbol_export_type(&final_name).id(),
|
||||
"nineSlice": nine_slice_json(d, &final_name),
|
||||
"type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)),
|
||||
}))
|
||||
Ok(options_json(&s.doc()?.doc, &final_name))
|
||||
}
|
||||
|
||||
/// What `symbol.options` answers for symbol `name`.
|
||||
fn options_json(d: &Document, name: &str) -> Value {
|
||||
json!({
|
||||
"name": name,
|
||||
"registration": d.symbol_registration(name).0,
|
||||
"exportType": d.symbol_export_type(name).id(),
|
||||
"nineSlice": nine_slice_json(d, name),
|
||||
"type": type_id(d.symbols.iter().any(|x| x.name == name && x.dynamic)),
|
||||
"alignToPixelGrid": d.symbol_pixel_aligned(name),
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
|
||||
@@ -702,6 +732,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_registration(name, SymbolRegistration::CENTER);
|
||||
d.clear_symbol_export_type(name);
|
||||
d.set_symbol_nine_slice(name, None);
|
||||
d.set_symbol_pixel_aligned(name, false);
|
||||
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
|
||||
d.unknown.remove(CURRENT_SYMBOL);
|
||||
}
|
||||
@@ -725,6 +756,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let reg = d.symbol_registration(&name);
|
||||
let export = d.symbol_export_type(&name);
|
||||
let nine = d.symbol_nine_slice(&name);
|
||||
let pixel = d.symbol_pixel_aligned(&name);
|
||||
s.edit("Duplicate Symbol", |d, _| {
|
||||
let art = d.reid(&sym.art);
|
||||
d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) });
|
||||
@@ -732,6 +764,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_registration(&new, reg);
|
||||
d.set_symbol_export_type(&new, export);
|
||||
d.set_symbol_nine_slice(&new, nine);
|
||||
d.set_symbol_pixel_aligned(&new, pixel);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }))
|
||||
|
||||
@@ -766,6 +766,8 @@ pub struct SymbolOptions {
|
||||
pub export_type: SymbolExportType,
|
||||
/// 9-slice guides (`None`: 9-slice scaling off).
|
||||
pub nine_slice: Option<SymbolNineSlice>,
|
||||
/// Align to Pixel Grid.
|
||||
pub pixel_aligned: bool,
|
||||
}
|
||||
|
||||
impl SymbolOptions {
|
||||
@@ -776,6 +778,7 @@ impl SymbolOptions {
|
||||
registration: d.symbol_registration(name),
|
||||
export_type: d.symbol_export_type(name),
|
||||
nine_slice: d.symbol_nine_slice(name),
|
||||
pixel_aligned: d.symbol_pixel_aligned(name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -785,6 +788,7 @@ impl SymbolOptions {
|
||||
d.set_symbol_registration(name, self.registration);
|
||||
d.set_symbol_export_type(name, self.export_type);
|
||||
d.set_symbol_nine_slice(name, self.nine_slice);
|
||||
d.set_symbol_pixel_aligned(name, self.pixel_aligned);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ pub use commands::specs;
|
||||
pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip};
|
||||
pub(crate) use pixelgrid::{
|
||||
align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap,
|
||||
snap_if_aligned,
|
||||
snap_if_aligned, snap_symbol_art,
|
||||
};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that
|
||||
//! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>).
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>),
|
||||
//! and Symbol Options › Align to Pixel Grid, which keeps a symbol's instances on the pixel grid.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
|
||||
|
||||
@@ -150,10 +153,234 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) {
|
||||
keep_pixel_aligned(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
refresh_symbols(before, doc);
|
||||
}
|
||||
|
||||
/// How far the linear part of an instance's transform may be from its symbol's natural size, as a
|
||||
/// fraction of that size, for the instance to count as placed at actual size.
|
||||
const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// After any edit: Symbol Options › Align to Pixel Grid. The art of a pixel-aligned symbol snaps to
|
||||
/// the pixel grid at the symbol's natural size ([`snap_symbol_art`]) when the symbol becomes
|
||||
/// pixel-aligned, when its art or natural size changes, and when symbol editing mode for it ends
|
||||
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
|
||||
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
|
||||
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
|
||||
/// An instance in another symbol's art is placed by that symbol's instances and is left as it is.
|
||||
/// A document without pixel-aligned symbols is not walked.
|
||||
fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let was = before.pixel_aligned_symbols();
|
||||
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let mut every = false;
|
||||
for name in &aligned {
|
||||
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
let art_now = doc.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
let art_changed = match (art_before, art_now) {
|
||||
(Some(b), Some(a)) => !Arc::ptr_eq(b, a),
|
||||
_ => true,
|
||||
};
|
||||
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
|
||||
if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed {
|
||||
snap_symbol_art(doc, name);
|
||||
every = true;
|
||||
}
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
if every {
|
||||
for layer in doc.layers.iter_mut() {
|
||||
if holds_instance(layer, &natural) {
|
||||
snap_instances_in(Arc::make_mut(layer), &natural);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (mut ids, mut masked) = (vec![], vec![]);
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
for id in ids {
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
snap_instance(n, &natural);
|
||||
}
|
||||
}
|
||||
for id in masked {
|
||||
if let Some(m) = doc.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) {
|
||||
snap_instances_in(Arc::make_mut(&mut m.art), &natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Among the objects of `after` that differ from their counterparts in `before` (or are new), in
|
||||
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
|
||||
/// mask art holds such instances (`masked`).
|
||||
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
|
||||
masked.push(a.id);
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &a.kind {
|
||||
if natural.contains_key(symbol) {
|
||||
ids.push(a.id);
|
||||
}
|
||||
} else if let Some(children) = a.children() {
|
||||
changed_instances(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, natural, ids, masked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n`, an object in it or the art of an opacity mask in it is an instance of a symbol in
|
||||
/// `natural`.
|
||||
fn holds_instance(n: &Node, natural: &HashMap<String, Affine>) -> bool {
|
||||
matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if natural.contains_key(symbol))
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_instance(c, natural)))
|
||||
}
|
||||
|
||||
/// [`snap_instance`] on every instance of a symbol in `natural` in `n`, the art of its opacity
|
||||
/// masks included. Only what holds such an instance is copied for editing.
|
||||
fn snap_instances_in(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
snap_instance(n, natural);
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& holds_instance(&m.art, natural)
|
||||
{
|
||||
snap_instances_in(Arc::make_mut(&mut m.art), natural);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if holds_instance(c, natural) {
|
||||
snap_instances_in(Arc::make_mut(c), natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Snap the art of pixel-aligned symbol `name` to the pixel grid as it is drawn at the symbol's
|
||||
/// natural size: each path and compound path in it snaps as a pixel-aligned object does
|
||||
/// ([`snap_object`]), measured from the symbol's origin. The art is stored again only when
|
||||
/// something in it moved, and the answer says whether it did.
|
||||
pub(crate) fn snap_symbol_art(doc: &mut Document, name: &str) -> bool {
|
||||
let natural = doc.symbol_natural_xf(name);
|
||||
let det = natural.determinant();
|
||||
if !det.is_finite() || det.abs() < 1e-18 {
|
||||
return false;
|
||||
}
|
||||
let Some(sym) = doc.symbols.iter_mut().find(|s| s.name == name) else { return false };
|
||||
// Instances draw the art's strokes at their stored width, and the art of unlinked opacity
|
||||
// masks, which `Node::transform` leaves alone, at the natural size too.
|
||||
let mut art = (*sym.art).clone();
|
||||
art.transform(natural, false);
|
||||
transform_unlinked_masks(&mut art, natural);
|
||||
if !snap_art(&mut art) {
|
||||
return false;
|
||||
}
|
||||
let inverse = natural.inverse();
|
||||
art.transform(inverse, false);
|
||||
transform_unlinked_masks(&mut art, inverse);
|
||||
sym.art = Arc::new(art);
|
||||
true
|
||||
}
|
||||
|
||||
/// Transform the art of every unlinked opacity mask in `n` by `xf`, in the art of other masks
|
||||
/// too. Only what holds such a mask is copied for editing.
|
||||
fn transform_unlinked_masks(n: &mut Node, xf: Affine) {
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& holds_unlinked_mask(&m.art, !m.linked)
|
||||
{
|
||||
let linked = m.linked;
|
||||
let art = Arc::make_mut(&mut m.art);
|
||||
if !linked {
|
||||
art.transform(xf, false);
|
||||
}
|
||||
transform_unlinked_masks(art, xf);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if holds_unlinked_mask(c, false) {
|
||||
transform_unlinked_masks(Arc::make_mut(c), xf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` is the art of an unlinked mask (`unlinked`), or it or an object in it, in the art of
|
||||
/// its masks too, has an unlinked opacity mask.
|
||||
fn holds_unlinked_mask(n: &Node, unlinked: bool) -> bool {
|
||||
unlinked
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| holds_unlinked_mask(&m.art, !m.linked))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_unlinked_mask(c, false)))
|
||||
}
|
||||
|
||||
/// Snap every path and compound path in `n` ([`can_align`]) with [`snap_object`], the art of
|
||||
/// opacity masks included (those of a compound path's paths too). Returns whether anything
|
||||
/// changed.
|
||||
fn snap_art(n: &mut Node) -> bool {
|
||||
let mut moved = false;
|
||||
if can_align(n) {
|
||||
let was = n.clone();
|
||||
snap_object(n, Scaling::default());
|
||||
moved = *n != was;
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.extras().mask.is_some() {
|
||||
moved |= snap_mask(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
moved |= snap_art(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
// After the object itself, which a linked mask follows.
|
||||
snap_mask(n) || moved
|
||||
}
|
||||
|
||||
/// [`snap_art`] on the art of `n`'s opacity mask. Returns whether anything changed.
|
||||
fn snap_mask(n: &mut Node) -> bool {
|
||||
let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) else { return false };
|
||||
let mut art = (*m.art).clone();
|
||||
if !snap_art(&mut art) {
|
||||
return false;
|
||||
}
|
||||
m.art = Arc::new(art);
|
||||
true
|
||||
}
|
||||
|
||||
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
|
||||
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
|
||||
/// rotated (a half turn included) or sheared instance stays where it is.
|
||||
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return };
|
||||
let Some(nat) = natural.get(symbol.as_str()) else { return };
|
||||
let [a, b, c, d, e, f] = xf.as_coeffs();
|
||||
let [na, _, _, nd, _, _] = nat.as_coeffs();
|
||||
let near = |v: f64, to: f64| (v.abs() - to.abs()).abs() <= ACTUAL_SIZE_TOLERANCE * to.abs().max(1.0);
|
||||
let actual =
|
||||
near(a, na) && near(d, nd) && b.abs() <= ACTUAL_SIZE_TOLERANCE * na.abs().max(1.0) && c.abs() <= ACTUAL_SIZE_TOLERANCE * nd.abs().max(1.0);
|
||||
// Flipped along both axes is a half turn, which counts as rotated.
|
||||
let half_turn = a * na < 0.0 && d * nd < 0.0;
|
||||
if !actual || half_turn || !e.is_finite() || !f.is_finite() {
|
||||
return;
|
||||
}
|
||||
let (x, y) = (e.round(), f.round());
|
||||
if x != e || y != f {
|
||||
*xf = Affine::new([a, b, c, d, x, y]);
|
||||
}
|
||||
}
|
||||
|
||||
/// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the
|
||||
/// pixel-aligned objects in them to the pixel grid again.
|
||||
/// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid
|
||||
/// again.
|
||||
pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
if doc.node(*id).is_some_and(holds_aligned)
|
||||
@@ -162,6 +389,18 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
keep_pixel_aligned(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
for id in ids {
|
||||
if doc.node(*id).is_some_and(|n| holds_instance(n, &natural))
|
||||
&& let Some(n) = doc.node_mut(*id)
|
||||
{
|
||||
snap_instances_in(n, &natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects of `after` that differ from their counterparts in `before` (or are new) and are
|
||||
|
||||
@@ -529,6 +529,24 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
|
||||
};
|
||||
d.symbols[index].art = Arc::new(new_art);
|
||||
follow_objects(d, &se.symbol, (&old, old_group), (&art, group));
|
||||
// A pixel-aligned symbol stores its art on the pixel grid while it is edited too, and the
|
||||
// editing layer shows the snapped art.
|
||||
if d.symbol_pixel_aligned(&se.symbol) && super::object::snap_symbol_art(d, &se.symbol) {
|
||||
let stored = &d.symbols[index].art;
|
||||
let snapped: Vec<Arc<Node>> = if group { stored.children().map(|c| c.to_vec()).unwrap_or_default() } else { vec![stored.clone()] };
|
||||
let mut snapped = snapped.into_iter().map(|n| {
|
||||
let mut n = (*n).clone();
|
||||
n.transform(se.xf, false);
|
||||
Arc::new(n)
|
||||
});
|
||||
if let Some(ch) = d.node_mut(se.layer).and_then(Node::children_mut) {
|
||||
for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) {
|
||||
if let Some(n) = snapped.next() {
|
||||
*c = n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(e) = d.symbol_edit.as_mut() {
|
||||
e.changed = true;
|
||||
e.group = group;
|
||||
|
||||
@@ -499,12 +499,13 @@ fn instance(name: &str) -> Node {
|
||||
}
|
||||
|
||||
/// Symbol `from`'s Symbol Options in `src` (natural size, registration, export type, 9-slice
|
||||
/// guides) given to symbol `to` of `d`.
|
||||
/// guides, Align to Pixel Grid) given to symbol `to` of `d`.
|
||||
fn copy_options(src: &Document, from: &str, d: &mut Document, to: &str) {
|
||||
set_natural_size(d, to, Some(natural_size(src, from)));
|
||||
d.set_symbol_registration(to, src.symbol_registration(from));
|
||||
d.set_symbol_export_type(to, src.symbol_export_type(from));
|
||||
d.set_symbol_nine_slice(to, src.symbol_nine_slice(from));
|
||||
d.set_symbol_pixel_aligned(to, src.symbol_pixel_aligned(from));
|
||||
}
|
||||
|
||||
fn builtin_info(b: &BuiltinSymbolLibrary) -> LibraryInfo {
|
||||
|
||||
Reference in New Issue
Block a user