mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge pull request #10015 from yoriswind/codex/10008-native-composite-adoption
Keep composite fonts when placing native artwork
This commit is contained in:
8 files changed
+1974
-44
No files matched your search
@@ -903,7 +903,7 @@ pub struct SymbolOptions {
|
||||
|
||||
impl SymbolOptions {
|
||||
/// The options `d` keeps for symbol `name`.
|
||||
fn of(d: &Document, name: &str) -> Self {
|
||||
pub(in crate::cmd) fn of(d: &Document, name: &str) -> Self {
|
||||
Self {
|
||||
size: stored_natural_size(d, name),
|
||||
registration: d.symbol_registration(name),
|
||||
@@ -914,7 +914,7 @@ impl SymbolOptions {
|
||||
}
|
||||
|
||||
/// Make them the options of `d`'s symbol `name`.
|
||||
fn give(&self, d: &mut Document, name: &str) {
|
||||
pub(in crate::cmd) fn give(&self, d: &mut Document, name: &str) {
|
||||
set_natural_size(d, name, self.size);
|
||||
d.set_symbol_registration(name, self.registration);
|
||||
d.set_symbol_export_type(name, self.export_type);
|
||||
|
||||
@@ -10,9 +10,12 @@
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::fileio::{read_file_head, write_file};
|
||||
@@ -77,6 +80,166 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Every stored family name, including regeneration settings and retained style defaults.
|
||||
/// Planning reads a private clone so gathering names never changes the destination.
|
||||
fn family_names(d: &Document) -> Result<BTreeSet<String>> {
|
||||
let mut view = d.clone();
|
||||
let mut names = BTreeSet::new();
|
||||
let mut note = |family: &mut String| {
|
||||
names.insert(family.to_lowercase());
|
||||
};
|
||||
super::textstyles::each_text_mut(&mut view, &mut |text| {
|
||||
for run in &mut text.runs {
|
||||
note(&mut run.style.font_family);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) {
|
||||
if let Some(Value::String(family)) = style.attrs.get_mut("font_family") {
|
||||
note(family);
|
||||
}
|
||||
}
|
||||
let mut graphs = Vec::new();
|
||||
view.visit_stored(|node, _| {
|
||||
if node.extras().graph.is_some() {
|
||||
graphs.push(node.id);
|
||||
}
|
||||
});
|
||||
for id in graphs {
|
||||
if let Some(node) = view.stored_node_mut(id) {
|
||||
graph_families(node, &mut note);
|
||||
}
|
||||
}
|
||||
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
|
||||
graph_families(node, note);
|
||||
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
|
||||
brush_graphs(Arc::make_mut(&mut mask.art), note);
|
||||
}
|
||||
for child in node.children_mut().into_iter().flatten() {
|
||||
brush_graphs(Arc::make_mut(child), note);
|
||||
}
|
||||
}
|
||||
for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) {
|
||||
brush_graphs(art, &mut note);
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
|
||||
if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) {
|
||||
let labels = &mut graph.label_styles;
|
||||
for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() {
|
||||
visit(&mut style.font_family);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Family fields held directly by one node; the adoption walker owns tree/resource traversal.
|
||||
pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
for run in &mut text.runs {
|
||||
visit(&mut run.style.font_family);
|
||||
}
|
||||
}
|
||||
graph_families(node, visit);
|
||||
}
|
||||
|
||||
/// A fully checked incoming-only rename map and the destination's prospective definitions.
|
||||
pub(super) struct CompositeImport {
|
||||
names: BTreeMap<String, String>,
|
||||
pub(super) combined: Vec<CompositeFont>,
|
||||
}
|
||||
|
||||
impl CompositeImport {
|
||||
pub(super) fn rename(&self, family: &mut String) -> bool {
|
||||
if let Some(name) = self.names.get(&family.to_lowercase()) {
|
||||
let changed = family.as_str() != name.as_str();
|
||||
*family = name.clone();
|
||||
changed
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
|
||||
let db = FontDb::global();
|
||||
let mut number = 2_u64;
|
||||
loop {
|
||||
let suffix = format!(" {number}");
|
||||
let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect();
|
||||
let name = format!("{}{suffix}", stem.trim_end());
|
||||
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
|
||||
&& !reserved.contains(&name.to_lowercase())
|
||||
&& !db.has_installed_family(&name)
|
||||
{
|
||||
return Ok(name);
|
||||
}
|
||||
number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Plan used incoming definitions before changing either document or the font database.
|
||||
/// Keep existing meanings even for an uninstalled family that destination art still names.
|
||||
pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
|
||||
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
let mut source_names = BTreeSet::new();
|
||||
for font in &source {
|
||||
font.check().map_err(|why| bad(cmd, why))?;
|
||||
if !source_names.insert(font.name.to_lowercase()) {
|
||||
return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name)));
|
||||
}
|
||||
}
|
||||
let target_families = family_names(target)?;
|
||||
let mut target_taken = target_families.clone();
|
||||
for font in target.composite_fonts.iter() {
|
||||
target_taken.insert(font.name.to_lowercase());
|
||||
target_taken.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let mut reserved = source_families;
|
||||
reserved.extend(target_families);
|
||||
for font in source.iter().chain(target.composite_fonts.iter()) {
|
||||
reserved.insert(font.name.to_lowercase());
|
||||
reserved.extend(font.part_fonts().map(str::to_lowercase));
|
||||
}
|
||||
let db = FontDb::global();
|
||||
let mut names = BTreeMap::new();
|
||||
let mut combined = target.composite_fonts.to_vec();
|
||||
for font in source {
|
||||
let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
|
||||
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent);
|
||||
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
|
||||
if needs_alias {
|
||||
// A repeated import reuses its already-installed equal alias.
|
||||
reused = target.composite_fonts.iter().find(equivalent);
|
||||
}
|
||||
let name = match reused {
|
||||
Some(other) => other.name.clone(),
|
||||
None if needs_alias => composite_alias(&font.name, &reserved, cmd)?,
|
||||
None => font.name.clone(),
|
||||
};
|
||||
reserved.insert(name.to_lowercase());
|
||||
names.insert(font.name.to_lowercase(), name.clone());
|
||||
if reused.is_none() {
|
||||
combined.push(CompositeFont { name, ..font });
|
||||
}
|
||||
}
|
||||
// A source document may currently lend fonts to the database. Validate the prospective
|
||||
// document, not composite names temporarily registered by a different document.
|
||||
if combined.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) {
|
||||
return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name)));
|
||||
}
|
||||
if CompositeFont::usable(&combined).is_some() {
|
||||
return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together"));
|
||||
}
|
||||
Ok(CompositeImport { names, combined })
|
||||
}
|
||||
|
||||
/// Register the active document's composite fonts in the font database, and remove the ones the
|
||||
/// other open documents (or an earlier active document) defined. Run after each command and when
|
||||
/// another document takes the front, so an undo, a revert, an opened or closed file or a document
|
||||
|
||||
@@ -578,7 +578,7 @@ fn art_of<'a>(nodes: impl Iterator<Item = &'a Arc<Node>>) -> Vec<Node> {
|
||||
}
|
||||
|
||||
/// The art as one object of `d` (its resources added), at its natural size and position.
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Result<Node> {
|
||||
let mut node = match l.art {
|
||||
Art::Image(img, clip) => {
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
@@ -613,7 +613,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))),
|
||||
Art::Document(s, link, bounding) => document::node(d, &s, link, bounding),
|
||||
Art::Vector { src, mut nodes, clip } => {
|
||||
adopt::adopt(d, &src, &mut nodes);
|
||||
adopt::adopt(d, &src, &mut nodes, PLACE)?;
|
||||
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
|
||||
if let Some(r) = clip {
|
||||
children.insert(0, Arc::new(clip_path(d.alloc_id(), r)));
|
||||
@@ -622,7 +622,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
|
||||
}
|
||||
};
|
||||
node.name = Some(l.name);
|
||||
node
|
||||
Ok(node)
|
||||
}
|
||||
|
||||
/// `node` moved and scaled by `m` as a whole: strokes, effects and pattern tiles go along.
|
||||
@@ -817,22 +817,86 @@ impl Session {
|
||||
if self.doc()?.uid != read.job.doc {
|
||||
return Err(bad(PLACE, NOT_ACTIVE));
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
// Deleted, changed, or another object with its id: an undo that removes the object frees
|
||||
// its id for the next object made.
|
||||
if st.doc.node(old) != read.job.replaced.as_ref() {
|
||||
// Keep the asynchronous target check against the drawing currently on show.
|
||||
if self.doc()?.doc.node(old) != read.job.replaced.as_ref() {
|
||||
return Err(bad(PLACE, "replace: the object to replace was changed or deleted"));
|
||||
}
|
||||
}
|
||||
let params = read.job.params.clone();
|
||||
// Provisional reselection and placement are one outside command. Deferring their
|
||||
// notifications must not make an asynchronous handoff part of an unrelated tool drag.
|
||||
if self.depth == 0 && !self.previewing && !self.in_tool_actions {
|
||||
self.command_with_settled_warnings(|s| s.outside_interaction(PLACE, ¶ms, |s| s.place_read_handoff(read, ¶ms)))
|
||||
} else {
|
||||
self.place_read_handoff(read, ¶ms)
|
||||
}
|
||||
}
|
||||
|
||||
fn place_read_handoff(&mut self, read: PlaceRead, params: &Value) -> Result<Value> {
|
||||
let mut rollback = None;
|
||||
let mut reselect = None;
|
||||
if let Some(old) = read.job.old {
|
||||
let st = self.doc()?;
|
||||
if st.selection.objects != [old] || st.selection.symbol_part.is_some() {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
// Adoption may now fail. Its provisional selection must not escape that error.
|
||||
rollback = Some((
|
||||
self.active,
|
||||
st.clone(),
|
||||
self.paint.clone(),
|
||||
self.fill_active,
|
||||
self.pending_paint.clone(),
|
||||
self.active_appearance_item.clone(),
|
||||
self.batch_paint_docs.clone(),
|
||||
self.journal.len(),
|
||||
self.journal.held(),
|
||||
));
|
||||
self.journal.hold(Some(self.journal.first_kept()));
|
||||
reselect = Some(old);
|
||||
}
|
||||
}
|
||||
self.place_hand_off = Some(read);
|
||||
let r = self.execute(PLACE, ¶ms);
|
||||
let outer_tool_actions = self.in_tool_actions;
|
||||
if reselect.is_some() {
|
||||
self.in_tool_actions = true;
|
||||
}
|
||||
let result = (|| {
|
||||
if let Some(old) = reselect {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
}
|
||||
self.place_hand_off = Some(read);
|
||||
self.execute(PLACE, params)
|
||||
})();
|
||||
self.place_hand_off = None;
|
||||
r
|
||||
if let Some((active, before, paint, fill_active, pending, appearance, paint_docs, journal, held)) = rollback {
|
||||
if result.is_err() {
|
||||
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == before.uid) {
|
||||
let revision = st.revision.max(before.revision);
|
||||
*st = before;
|
||||
st.revision = revision + 1;
|
||||
}
|
||||
self.active = active;
|
||||
self.paint = paint;
|
||||
self.fill_active = fill_active;
|
||||
self.pending_paint = pending;
|
||||
self.active_appearance_item = appearance;
|
||||
self.batch_paint_docs = paint_docs;
|
||||
self.journal.truncate(journal);
|
||||
for group in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) {
|
||||
group.journal.retain(|&(n, _)| n < journal);
|
||||
group.steps.retain(|&(n, _)| n < journal);
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.decoded_images.empty();
|
||||
self.sync_front_profiles();
|
||||
super::compositefonts::sync(self);
|
||||
}
|
||||
self.journal.hold(held);
|
||||
}
|
||||
if reselect.is_some() {
|
||||
self.in_tool_actions = outer_tool_actions;
|
||||
self.after_command(result.is_ok().then_some(PLACE));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,7 +1062,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
|
||||
}
|
||||
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
|
||||
let mut node = transformed(build(d, loaded, link), m);
|
||||
let mut node = transformed(build(d, loaded, link)?, m);
|
||||
if let Some((old_image, (_, q, _))) = distorted {
|
||||
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
|
||||
}
|
||||
@@ -1266,7 +1330,7 @@ fn thumbnail_png(l: Loaded, px: f64) -> Result<String> {
|
||||
let natural = l.natural;
|
||||
let mut d = Document::new(natural.width().max(1.0), natural.height().max(1.0));
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
let node = build(&mut d, l, None);
|
||||
let node = build(&mut d, l, None)?;
|
||||
d.insert(layer, 0, node)?;
|
||||
let k = px.clamp(1.0, MAX_THUMBNAIL) / natural.width().max(natural.height()).max(1e-9);
|
||||
let png = vectorcraft_render::Renderer::new().render_region(&d, natural, k, false).to_png().map_err(EngineError::Other)?;
|
||||
|
||||
@@ -5,13 +5,16 @@
|
||||
//! defines differently keeps its colour, unlinked. Text styles are left as they are: the art carries
|
||||
//! its own formatting.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_brush::{Brush, BrushKind};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
|
||||
|
||||
use super::super::Result;
|
||||
use super::super::clipboard::SymbolOptions;
|
||||
use super::super::compositefonts::{CompositeImport, node_families, plan_import};
|
||||
use super::unique_name;
|
||||
|
||||
/// Visit `n` and every descendant (children and opacity-mask art) mutably.
|
||||
@@ -52,9 +55,56 @@ fn paint_refs(p: &mut Paint, f: &mut impl FnMut(Ref)) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Visit only the records the shared reader accepted, in their original order. Consuming
|
||||
/// each accepted record once also leaves ignored duplicate surfaces and capped records alone.
|
||||
fn accepted_graphic_refs<T: PartialEq>(
|
||||
list: &mut serde_json::Value,
|
||||
accepted: Vec<T>,
|
||||
parse: impl Fn(&serde_json::Value) -> Option<T>,
|
||||
f: &mut impl FnMut(Ref),
|
||||
) {
|
||||
let Some(list) = list.as_array_mut() else { return };
|
||||
let mut accepted = accepted.into_iter().peekable();
|
||||
for value in list {
|
||||
let Some(next) = accepted.peek() else { break };
|
||||
if parse(value).as_ref() != Some(next) {
|
||||
continue;
|
||||
}
|
||||
let _ = accepted.next();
|
||||
if let Some(serde_json::Value::String(symbol)) = value.get_mut("symbol") {
|
||||
f(Ref::Symbol(symbol));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol references in accepted Graphics and Map Art records, including fill/stroke effects.
|
||||
/// Each stored name is visited once, so a rename cannot feed a second rename in the same map.
|
||||
fn appearance_graphic_refs(appearance: &mut vectorcraft_doc::Appearance, f: &mut impl FnMut(Ref)) {
|
||||
use vectorcraft_render::effects as fx;
|
||||
|
||||
if fx::appearance_graphic_symbols(appearance).is_empty() {
|
||||
return;
|
||||
}
|
||||
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
|
||||
for effect in effects.iter_mut().chain(items.iter_mut().flat_map(|item| item.effects_mut())) {
|
||||
if fx::takes_graphics(&effect.id) {
|
||||
let accepted = fx::mapped_graphics(&effect.params);
|
||||
if let Some(list) = effect.params.get_mut(fx::GRAPHICS) {
|
||||
accepted_graphic_refs(list, accepted, |value| fx::MappedGraphic::from_value(value).ok(), f);
|
||||
}
|
||||
} else if fx::takes_map_art(&effect.id) {
|
||||
let accepted = fx::surface_maps(&effect.params);
|
||||
if let Some(list) = effect.params.get_mut(fx::MAP_ART) {
|
||||
accepted_graphic_refs(list, accepted, |value| fx::SurfaceMap::from_value(value).ok(), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every resource reference in `n` and its descendants.
|
||||
fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
each_mut(n, &mut |n| {
|
||||
appearance_graphic_refs(&mut n.appearance, f);
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(fl) => paint_refs(&mut fl.paint, f),
|
||||
@@ -71,6 +121,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
for r in &mut t.runs {
|
||||
paint_refs(&mut r.style.fill, f);
|
||||
paint_refs(&mut r.style.stroke, f);
|
||||
if let Some(inline) = &mut r.inline {
|
||||
f(Ref::Symbol(&mut inline.symbol));
|
||||
}
|
||||
}
|
||||
if let Some(fonts) = &mut t.file_fonts {
|
||||
fonts.map_keys(|key| f(Ref::Image(key)));
|
||||
@@ -81,6 +134,14 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(extras) = n.extras_if_any() {
|
||||
extras
|
||||
.symbol_overrides
|
||||
.iter_mut()
|
||||
.flat_map(|override_| [&mut override_.fill, &mut override_.stroke])
|
||||
.flatten()
|
||||
.for_each(|paint| paint_refs(paint, f));
|
||||
}
|
||||
// A color-masked image's masked pixels come along, and the key they were made from
|
||||
// follows the image's.
|
||||
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
|
||||
@@ -162,7 +223,16 @@ fn canon(dst: &Document, n: &Node) -> Node {
|
||||
own.images.insert(k.clone(), blob.clone());
|
||||
}
|
||||
}
|
||||
own.reid(n)
|
||||
let mut canonical = own.reid(n);
|
||||
// Derived layout caches do not define the stored art's resource identity.
|
||||
each_mut(&mut canonical, &mut |node| {
|
||||
if let NodeKind::Text(text) = &mut node.kind {
|
||||
text.cached_bounds = None;
|
||||
text.cached_baselines.clear();
|
||||
text.cached_ink = None;
|
||||
}
|
||||
});
|
||||
canonical
|
||||
}
|
||||
|
||||
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
|
||||
@@ -220,12 +290,273 @@ fn brush_art(b: &mut Brush) -> Vec<&mut Node> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
/// Apply the final resource-name plan to one incoming reference.
|
||||
fn rename_ref(r: Ref<'_>, maps: [&Renames; 5]) {
|
||||
let (map, key) = match r {
|
||||
Ref::Image(key) => (maps[0], key),
|
||||
Ref::Symbol(key) => (maps[1], key),
|
||||
Ref::Pattern(key) => (maps[2], key),
|
||||
Ref::Brush(key) => (maps[3], key),
|
||||
Ref::Swatch(link) => {
|
||||
if let Some((new, _)) = link.as_deref().and_then(|key| maps[4].get(key)) {
|
||||
*link = new.clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some((Some(new), _)) = map.get(key.as_str()) {
|
||||
*key = new.clone();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum ResourceKind {
|
||||
Symbol,
|
||||
Pattern,
|
||||
Brush,
|
||||
}
|
||||
|
||||
type ResourceKey = (ResourceKind, String);
|
||||
|
||||
/// A source definition's dependencies whose planned names have not been finalized yet.
|
||||
fn pending_dependencies(key: &ResourceKey, src: &Document, brushes: &[Brush], pending: &BTreeSet<ResourceKey>) -> BTreeSet<ResourceKey> {
|
||||
let mut dependencies = BTreeSet::new();
|
||||
let mut note = |r: Ref<'_>| {
|
||||
let key = match r {
|
||||
Ref::Symbol(name) => (ResourceKind::Symbol, name.clone()),
|
||||
Ref::Pattern(name) => (ResourceKind::Pattern, name.clone()),
|
||||
Ref::Brush(name) => (ResourceKind::Brush, name.clone()),
|
||||
Ref::Image(_) | Ref::Swatch(_) => return,
|
||||
};
|
||||
if pending.contains(&key) {
|
||||
dependencies.insert(key);
|
||||
}
|
||||
};
|
||||
match key.0 {
|
||||
ResourceKind::Symbol => {
|
||||
if let Some(symbol) = src.symbols.iter().find(|symbol| symbol.name == key.1) {
|
||||
refs(&mut (*symbol.art).clone(), &mut note);
|
||||
}
|
||||
}
|
||||
ResourceKind::Pattern => {
|
||||
if let Some(pattern) = src.pattern(&key.1) {
|
||||
for art in &pattern.art {
|
||||
refs(&mut (**art).clone(), &mut note);
|
||||
}
|
||||
}
|
||||
}
|
||||
ResourceKind::Brush => {
|
||||
if let Some(mut brush) = brushes.iter().find(|brush| brush.name == key.1).cloned() {
|
||||
for art in brush_art(&mut brush) {
|
||||
refs(art, &mut note);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dependencies
|
||||
}
|
||||
|
||||
/// Prefer the original name, then only canonical numbered variants from `unique_name`.
|
||||
/// A free original name keeps its planned copy; another incoming name is never stolen.
|
||||
fn matching_name<T>(base: &str, definitions: &[T], used: &[String], name: impl Fn(&T) -> &str, same: impl Fn(&T) -> bool) -> Option<String> {
|
||||
let original = definitions.iter().find(|definition| name(definition) == base)?;
|
||||
if same(original) {
|
||||
return Some(base.to_string());
|
||||
}
|
||||
let prefix = format!("{base} ");
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut aliases: Vec<_> = definitions
|
||||
.iter()
|
||||
.filter_map(|definition| {
|
||||
let candidate = name(definition);
|
||||
// Match the first definition, as the document name lookups do.
|
||||
if !seen.insert(candidate.to_string()) {
|
||||
return None;
|
||||
}
|
||||
let suffix = candidate.strip_prefix(&prefix)?;
|
||||
if suffix.starts_with('0') || !suffix.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let number = suffix.parse::<u64>().ok()?;
|
||||
(number >= 2 && !used.iter().any(|used| used == candidate)).then_some((number, definition))
|
||||
})
|
||||
.collect();
|
||||
aliases.sort_unstable_by_key(|(number, _)| *number);
|
||||
aliases.into_iter().find_map(|(_, definition)| same(definition).then(|| name(definition).to_string()))
|
||||
}
|
||||
|
||||
/// Compare final incoming content, not the original references or destination's resource name.
|
||||
fn reusable_name(
|
||||
key: &ResourceKey,
|
||||
dst: &Document,
|
||||
src: &Document,
|
||||
src_brushes: &[Brush],
|
||||
dst_brushes: &[Brush],
|
||||
used: &Used,
|
||||
maps: [&Renames; 5],
|
||||
) -> Option<String> {
|
||||
match key.0 {
|
||||
ResourceKind::Symbol => {
|
||||
let source = src.symbols.iter().find(|symbol| symbol.name == key.1)?;
|
||||
let mut incoming = source.clone();
|
||||
refs(Arc::make_mut(&mut incoming.art), &mut |r| rename_ref(r, maps));
|
||||
matching_name(
|
||||
&key.1,
|
||||
&dst.symbols,
|
||||
&used.symbols,
|
||||
|symbol| &symbol.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
same_symbol(dst, &normalized, &incoming) && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
ResourceKind::Pattern => {
|
||||
let mut incoming = src.pattern(&key.1)?.clone();
|
||||
for art in &mut incoming.art {
|
||||
refs(Arc::make_mut(art), &mut |r| rename_ref(r, maps));
|
||||
}
|
||||
matching_name(
|
||||
&key.1,
|
||||
&dst.patterns,
|
||||
&used.patterns,
|
||||
|pattern| &pattern.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
same_pattern(dst, &normalized, &incoming)
|
||||
},
|
||||
)
|
||||
}
|
||||
ResourceKind::Brush => {
|
||||
let mut incoming = src_brushes.iter().find(|brush| brush.name == key.1)?.clone();
|
||||
for art in brush_art(&mut incoming) {
|
||||
refs(art, &mut |r| rename_ref(r, maps));
|
||||
*art = canon(dst, art);
|
||||
}
|
||||
matching_name(
|
||||
&key.1,
|
||||
dst_brushes,
|
||||
&used.brushes,
|
||||
|brush| &brush.name,
|
||||
|candidate| {
|
||||
let mut normalized = candidate.clone();
|
||||
normalized.name = incoming.name.clone();
|
||||
for art in brush_art(&mut normalized) {
|
||||
*art = canon(dst, art);
|
||||
}
|
||||
normalized == incoming
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finalize each copied definition only after its copied dependencies. Each key/edge is
|
||||
/// processed once; a cycle (and its unresolved parents) conservatively keeps the planned copies.
|
||||
fn reuse_remapped_resources(
|
||||
dst: &Document,
|
||||
src: &Document,
|
||||
src_brushes: &[Brush],
|
||||
dst_brushes: &[Brush],
|
||||
used: &Used,
|
||||
fixed: [&Renames; 2],
|
||||
changing: [&mut Renames; 3],
|
||||
) {
|
||||
let [symbols, patterns, brushes] = changing;
|
||||
let mut pending = BTreeSet::new();
|
||||
for (kind, map) in [(ResourceKind::Symbol, &*symbols), (ResourceKind::Pattern, &*patterns), (ResourceKind::Brush, &*brushes)] {
|
||||
pending.extend(map.iter().filter(|(_, (_, copy))| *copy).map(|(name, _)| (kind, name.clone())));
|
||||
}
|
||||
let mut waiting = BTreeMap::new();
|
||||
let mut parents: BTreeMap<ResourceKey, Vec<ResourceKey>> = BTreeMap::new();
|
||||
let mut ready = BTreeSet::new();
|
||||
for key in &pending {
|
||||
let dependencies = pending_dependencies(key, src, src_brushes, &pending);
|
||||
if dependencies.is_empty() {
|
||||
ready.insert(key.clone());
|
||||
}
|
||||
waiting.insert(key.clone(), dependencies.len());
|
||||
for dependency in dependencies {
|
||||
parents.entry(dependency).or_default().push(key.clone());
|
||||
}
|
||||
}
|
||||
while let Some(key) = ready.pop_first() {
|
||||
let maps = [fixed[0], &*symbols, &*patterns, &*brushes, fixed[1]];
|
||||
if let Some(name) = reusable_name(&key, dst, src, src_brushes, dst_brushes, used, maps) {
|
||||
let map = match key.0 {
|
||||
ResourceKind::Symbol => &mut *symbols,
|
||||
ResourceKind::Pattern => &mut *patterns,
|
||||
ResourceKind::Brush => &mut *brushes,
|
||||
};
|
||||
map.insert(key.1.clone(), (Some(name), false));
|
||||
}
|
||||
for parent in parents.remove(&key).into_iter().flatten() {
|
||||
if let Some(count) = waiting.get_mut(&parent) {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
ready.insert(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remap only incoming users before resource equality decides whether to share or copy.
|
||||
/// Report actual family renaming for the final copied-resource reuse phase.
|
||||
fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport) -> (Document, bool) {
|
||||
let mut staged = src.clone();
|
||||
let mut aliased = false;
|
||||
for node in nodes.iter_mut() {
|
||||
each_mut(node, &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) {
|
||||
each_mut(Arc::make_mut(&mut symbol.art), &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) {
|
||||
for art in &mut pattern.art {
|
||||
each_mut(Arc::make_mut(art), &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
for brush in brushes.iter_mut().filter(|brush| used.brushes.contains(&brush.name)) {
|
||||
for art in brush_art(brush) {
|
||||
each_mut(art, &mut |node| {
|
||||
node_families(node, &mut |family| {
|
||||
aliased |= plan.rename(family);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
(staged, aliased)
|
||||
}
|
||||
|
||||
/// Discover the incoming resource frontier and its composite-font users before planning
|
||||
/// names or changing either document. Resource order and the no-composite fast path stay shared.
|
||||
fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, BTreeSet<String>) {
|
||||
let mut used = Used::default();
|
||||
let composites = !src.composite_fonts.is_empty();
|
||||
let mut families = BTreeSet::new();
|
||||
let mut note_family = |name: &mut String| {
|
||||
families.insert(name.to_lowercase());
|
||||
};
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(n, &mut |node| node_families(node, &mut note_family));
|
||||
}
|
||||
}
|
||||
let src_brushes = vectorcraft_brush::library(src);
|
||||
// Symbol, pattern and brush art and tint swatches can use more resources (the lists grow while
|
||||
@@ -254,8 +585,29 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
}
|
||||
for mut a in art {
|
||||
refs(&mut a, &mut |r| used.note(r));
|
||||
if composites {
|
||||
each_mut(&mut a, &mut |node| node_families(node, &mut note_family));
|
||||
}
|
||||
}
|
||||
}
|
||||
(used, src_brushes, families)
|
||||
}
|
||||
|
||||
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
|
||||
/// `nodes` at the names they got.
|
||||
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
|
||||
let (used, mut src_brushes, families) = collect_resources(src, nodes);
|
||||
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
|
||||
// All representability/validation errors precede incoming or destination mutation.
|
||||
let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
|
||||
let staged;
|
||||
let mut aliased = false;
|
||||
let src = if let Some(plan) = &plan {
|
||||
(staged, aliased) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan);
|
||||
&staged
|
||||
} else {
|
||||
src
|
||||
};
|
||||
|
||||
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
|
||||
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
|
||||
@@ -264,7 +616,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
&used.symbols,
|
||||
|n| src.symbols.iter().find(|s| s.name == n),
|
||||
|n| dst.symbols.iter().find(|s| s.name == n),
|
||||
|a, b| same_symbol(dst, a, b),
|
||||
|a, b| same_symbol(dst, a, b) && SymbolOptions::of(dst, &a.name) == SymbolOptions::of(src, &b.name),
|
||||
|c| dst.symbols.iter().any(|s| s.name == c),
|
||||
);
|
||||
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
|
||||
@@ -330,23 +682,14 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
|
||||
}
|
||||
|
||||
let mut rename = |r: Ref| {
|
||||
let (map, k) = match r {
|
||||
Ref::Image(k) => (&images, k),
|
||||
Ref::Symbol(k) => (&symbols, k),
|
||||
Ref::Pattern(k) => (&patterns, k),
|
||||
Ref::Brush(k) => (&brushes, k),
|
||||
Ref::Swatch(link) => {
|
||||
if let Some((new, _)) = link.as_deref().and_then(|k| swatches.get(k)) {
|
||||
*link = new.clone();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some((Some(new), _)) = map.get(k.as_str()) {
|
||||
*k = new.clone();
|
||||
}
|
||||
};
|
||||
if aliased || symbols.values().any(|(_, copy)| *copy) {
|
||||
reuse_remapped_resources(dst, src, &src_brushes, &dst_brushes, &used, [&images, &swatches], [&mut symbols, &mut patterns, &mut brushes]);
|
||||
}
|
||||
|
||||
if let Some(plan) = plan {
|
||||
dst.composite_fonts = plan.combined.into();
|
||||
}
|
||||
let mut rename = |r: Ref| rename_ref(r, [&images, &symbols, &patterns, &brushes, &swatches]);
|
||||
for n in nodes.iter_mut() {
|
||||
refs(n, &mut rename);
|
||||
}
|
||||
@@ -375,6 +718,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
|
||||
def.art = Arc::new(dst.reid(&def.art));
|
||||
dst.symbols.push(def);
|
||||
SymbolOptions::of(src, old).give(dst, new);
|
||||
}
|
||||
}
|
||||
for (old, new) in copies(&patterns) {
|
||||
@@ -406,4 +750,5 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
dst.swatches.push(w);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -178,6 +178,10 @@ fn opened_document_art(
|
||||
super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false);
|
||||
}
|
||||
l.doc.drop_edit_modes();
|
||||
// Measure and crop in this source's composite fonts, not those of the front document.
|
||||
// The existing thread-local loan restores its caller's context on every return or unwind.
|
||||
let source_fonts = l.doc.composite_fonts.clone();
|
||||
let _source_fonts = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts);
|
||||
// The native file does not store type's layout bounds. Measure them before cropping or
|
||||
// copying the art, so the placed group keeps the positions of aligned point type.
|
||||
for warning in crate::Session::refresh_text_bounds(&mut l.doc) {
|
||||
@@ -544,7 +548,7 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
|
||||
let a = document_art(p.link.name(), &bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, cmd)?;
|
||||
let m = p.art_xf(a.frame).ok_or_else(|| bad(cmd, format!("object {} has no size", id.0)))?;
|
||||
let mut nodes = a.nodes;
|
||||
super::adopt::adopt(d, &a.doc, &mut nodes);
|
||||
super::adopt::adopt(d, &a.doc, &mut nodes, cmd)?;
|
||||
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
|
||||
if let Some(r) = a.clip {
|
||||
children.insert(0, Arc::new(super::clip_path(d.alloc_id(), r)));
|
||||
|
||||
@@ -661,6 +661,7 @@ impl Session {
|
||||
self.pending_paint = None;
|
||||
// The previous preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
cmd::compositefonts::sync(self);
|
||||
let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params));
|
||||
let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p));
|
||||
// A selected object's converted appearance must not replace the current paints while
|
||||
@@ -877,6 +878,7 @@ impl Session {
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// A canceled preview's Assign Profile is undone with it.
|
||||
self.sync_front_profiles();
|
||||
cmd::compositefonts::sync(self);
|
||||
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
|
||||
// the document has it again, not as a preview left it. An interaction that changed only the
|
||||
// defaults (`defaultsOnly: true`) leaves the defaults it began with.
|
||||
|
||||
@@ -25,6 +25,12 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run a command callback and keep warnings from every preview it settles or restores.
|
||||
pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
let (r, settled) = self.collect_settled_warnings(f);
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
}
|
||||
|
||||
/// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back.
|
||||
fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> {
|
||||
let Some(d) = self.active_mut() else { return (spec.enabled)(self) };
|
||||
@@ -121,10 +127,9 @@ impl Session {
|
||||
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
|
||||
// before Undo) reports its warning in the command's result.
|
||||
let r = if self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| {
|
||||
self.command_with_settled_warnings(|s| {
|
||||
if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) }
|
||||
});
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
})
|
||||
} else {
|
||||
self.execute_spec(spec, id, params)
|
||||
};
|
||||
@@ -253,6 +258,10 @@ impl Session {
|
||||
// after an undone or redone Assign Profile, a failed or panicked command's documents put
|
||||
// back, and a batch step, before the next step converts through them.
|
||||
self.sync_front_profiles();
|
||||
if self.depth != 0 {
|
||||
// The next batch step can measure/outline definitions this step adopted.
|
||||
cmd::compositefonts::sync(self);
|
||||
}
|
||||
if r.is_err() && self.depth == 0 {
|
||||
self.batch_paint_docs.clear();
|
||||
// A failed or panicked command's documents are put back: type is drawn in their
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user