Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion crates/eps/src/import/ai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ use crate::ps;
pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
#[cfg(test)]
pub(crate) use envelope::MAX_CHECKED;
#[cfg(test)]
pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN;
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
pub(crate) use frames::text_frames;
Expand Down
181 changes: 176 additions & 5 deletions crates/eps/src/import/ai/envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
//! one-patch mesh. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its
//! drawn art.

use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;

use kurbo::{Affine, BezPath, Point, Rect, Vec2};
Expand All @@ -46,6 +46,12 @@ pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live
pub(crate) const TYPE_DRAWN: &str = "type in an envelope comes in as the envelope's drawn art, not as editable type";
/// The note for warped type that keeps its drawn art, before how many.
pub(crate) const WARPED_TYPE_DRAWN: &str = "warped text objects that came in as drawn art, not as editable type";

/// The note for an envelope that keeps its drawn art: [`TYPE_DRAWN`] for an envelope of type
/// (`typed`), else [`DRAWN`].
pub(crate) fn drawn_note(typed: bool) -> &'static str {
if typed { TYPE_DRAWN } else { DRAWN }
}
/// The most envelopes waiting for their drawn art at once.
pub(super) const MAX_PENDING: usize = 64;
/// The most envelopes and warped text objects one import draws to check; more keep their drawn art.
Expand Down Expand Up @@ -371,18 +377,160 @@ pub(super) struct WarpedLook {
pub(super) left_out: Option<Rect>,
}

/// The text objects read with a Warp, and what the import has left of the budget for checks
/// ([`drawn_alike`]). Type is laid out after the layers are read, so these wait for that
/// ([`Self::settle`]).
/// An envelope of type read with its drawn art: its dictionary, the group on `%_` lines before it
/// and the art in its `AIDeformArtKey` block, as [`live`] takes them (their text slots still
/// empty), and the id of its drawn art in the document. Type is laid out after the layers are read,
/// so it waits for that ([`WarpedType::settle_envelopes`]).
#[derive(Debug)]
pub(crate) struct TypedEnvelope {
pub(super) obj: Obj,
pub(super) before: Option<Node>,
pub(super) inner: Vec<Node>,
pub(super) drawn: NodeId,
}

/// Why an envelope of type kept its drawn art.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TypeKept {
/// Its type is set in a font that isn't available: the fallback font doesn't draw as the file.
Font,
/// A text slot of it has no type of its own (none made, or type a look draws, threaded type,
/// type bound to a variable or a wrap object).
Type,
/// Its parts don't make a live envelope, or its drawn art is gone.
Read,
/// The import has no check left.
Budget,
/// Its live envelope doesn't draw as its drawn art.
Differs,
}

/// What [`WarpedType::settle_envelopes`] did.
#[derive(Debug, Default)]
pub(crate) struct TypedSettled {
/// How many envelopes of type opened live.
pub(crate) live: usize,
/// Why each of the others kept its drawn art.
pub(crate) kept: Vec<TypeKept>,
/// Each live envelope's id, with what takes its place again when the layers with it don't draw
/// as the page: its hidden type, then its drawn art.
pub(crate) put_back: Vec<(NodeId, Vec<Node>)>,
}

/// The text objects read with a Warp and the envelopes of type, and what the import has left of the
/// budget for checks ([`drawn_alike`]). Type is laid out after the layers are read, so these wait
/// for that ([`Self::settle`], [`Self::settle_envelopes`]).
#[derive(Debug, Default)]
pub struct WarpedType {
pub(super) looks: Vec<WarpedLook>,
pub(super) envelopes: Vec<TypedEnvelope>,
pub(super) checks: usize,
pub(super) spent: Spent,
pub(super) page: Option<Rect>,
}

impl WarpedType {
/// Are envelopes of type waiting for their type?
pub(crate) fn has_envelopes(&self) -> bool {
!self.envelopes.is_empty()
}

/// These, for layers `compared` with a page. Layers that aren't leave the envelopes of type
/// their drawn art and their hidden type, with the note ([`TYPE_DRAWN`]) added to `notes`: a
/// live envelope opens only where the page chooses it.
pub(crate) fn compared(mut self, compared: bool, notes: &mut Vec<String>) -> Self {
if !compared && !std::mem::take(&mut self.envelopes).is_empty() && !notes.iter().any(|n| n == TYPE_DRAWN) {
notes.push(TYPE_DRAWN.into());
}
self
}

/// Make each envelope of type live where it draws as its drawn art, its contents' text slots
/// holding their type: `type_of` gives, for a slot's id, the hidden text object it became in
/// `doc` and the type the contents take in its place (the slot's visibility and lock are the
/// type's). The live envelope takes its drawn art's place and the hidden type goes. Each check
/// uses one of the import's checks and, for an envelope that shows, adds to what the page check
/// allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't
/// available, the drawn art and the hidden type stay.
pub(crate) fn settle_envelopes(&mut self, doc: &mut Document, type_of: impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>) -> TypedSettled {
let mut settled = TypedSettled::default();
if self.envelopes.is_empty() {
return settled;
}
let mut shown = BTreeSet::new();
doc.layers.iter().for_each(|l| collect_shown(l, &mut shown));
for envelope in std::mem::take(&mut self.envelopes) {
match self.typed_live(doc, envelope, &type_of, &shown) {
Ok(put_back) => {
settled.live += 1;
settled.put_back.push(put_back);
}
Err(why) => settled.kept.push(why),
}
}
settled
}

/// [`Self::settle_envelopes`] for `envelope`, the shown objects of `doc` being `shown`: the live
/// envelope's id and what takes its place again, or why its drawn art stays.
fn typed_live(
&mut self,
doc: &mut Document,
envelope: TypedEnvelope,
type_of: &impl Fn(&Document, NodeId) -> Option<(NodeId, Node)>,
shown: &BTreeSet<NodeId>,
) -> Result<(NodeId, Vec<Node>), TypeKept> {
let TypedEnvelope { obj, mut before, mut inner, drawn } = envelope;
let art = doc.node(drawn).cloned().ok_or(TypeKept::Read)?;
// The text slots in the contents, in the order the reader put their hidden copies in.
let mut slots = vec![];
before.iter().chain(&inner).for_each(|n| text_slots_in(n, &mut slots));
if slots.is_empty() {
return Err(TypeKept::Type);
}
let db = vectorcraft_text::FontDb::global();
let (mut texts, mut hidden) = (HashMap::new(), vec![]);
for (slot, look) in slots {
let (id, mut text) = type_of(doc, slot).filter(|_| !look).ok_or(TypeKept::Type)?;
let NodeKind::Text(t) = &text.kind else { return Err(TypeKept::Type) };
if t.runs.iter().any(|r| r.style.font_family.is_empty() || !db.has_family(&r.style.font_family)) {
return Err(TypeKept::Font);
}
text.id = doc.alloc_id();
texts.insert(slot, text);
hidden.push(id);
}
for n in before.iter_mut().chain(inner.iter_mut()) {
put_type(n, &texts);
}
let kind = live(&obj, before, inner).ok_or(TypeKept::Read)?;
if self.checks == 0 {
return Err(TypeKept::Budget);
}
self.checks -= 1;
let mut envelope = art.clone();
(envelope.id, envelope.kind) = (doc.alloc_id(), kind);
let layer = doc.alloc_id();
let shared = Shared { patterns: &doc.patterns, images: &doc.images };
let (mut live_one, mut plain) = (envelope.clone(), art.clone());
(live_one.visible, live_one.opacity) = (true, 1.0);
(plain.visible, plain.opacity) = (true, 1.0);
let page = self.page.filter(|_| shown.contains(&drawn));
if !drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) {
return Err(TypeKept::Differs);
}
if doc.node(drawn).is_none() {
return Err(TypeKept::Read);
}
// The type is the envelope's now: its hidden copy goes, kept for when the drawn art comes back.
let mut put_back: Vec<Node> = hidden.into_iter().filter_map(|id| doc.remove(id).ok()).map(Arc::unwrap_or_clone).collect();
let id = envelope.id;
let Some(slot) = doc.node_mut(drawn) else { return Err(TypeKept::Read) };
*slot = envelope;
put_back.push(art);
Ok((id, put_back))
}

/// Replace each warped text object of `doc` that doesn't draw as its saved look (or that the
/// budget has no check left for) with that look: `made` gives the text object a slot became. A
/// frame in `threaded` stays type, since the frames of a thread share one story. A replaced
Expand All @@ -395,7 +543,7 @@ impl WarpedType {
threaded: &BTreeSet<NodeId>,
restyled: &mut Vec<Rect>,
) -> usize {
let Self { looks, mut checks, mut spent, page } = self;
let Self { looks, mut checks, mut spent, page, .. } = self;
let mut shown_ids = BTreeSet::new();
doc.layers.iter().for_each(|l| collect_shown(l, &mut shown_ids));
let mut replaced = 0;
Expand Down Expand Up @@ -439,6 +587,29 @@ impl WarpedType {
}
}

/// The ids of the text slots in `n` and its groups, in order, each with whether it is a slot of type
/// that a look draws ([`super::is_look_slot`]).
fn text_slots_in(n: &Node, out: &mut Vec<(NodeId, bool)>) {
let look = super::is_look_slot(n.name.as_deref());
if look || super::slot_of(n.name.as_deref()).is_some() {
out.push((n.id, look));
} else if !matches!(n.kind, NodeKind::Compound { .. }) {
n.children().into_iter().flatten().for_each(|c| text_slots_in(c, out));
}
}

/// `n` with each text slot in it or its groups replaced by its type in `texts`, by the slot's id,
/// shown and locked as the slot is.
fn put_type(n: &mut Node, texts: &HashMap<NodeId, Node>) {
if let Some(text) = texts.get(&n.id) {
let (visible, locked) = (n.visible, n.locked);
*n = text.clone();
(n.visible, n.locked) = (visible, locked);
} else if !matches!(n.kind, NodeKind::Compound { .. }) {
n.children_mut().into_iter().flatten().for_each(|c| put_type(Arc::make_mut(c), texts));
}
}

/// Add to `out` the ids of `n` and what is in it, unless hidden.
fn collect_shown(n: &Node, out: &mut BTreeSet<NodeId>) {
if n.visible {
Expand Down
4 changes: 4 additions & 0 deletions crates/eps/src/import/ai/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,9 @@ struct Reader<'a> {
envelope_spent: super::envelope::Spent,
/// The text objects read with a Warp ([`super::envelope::WarpedType`]).
warped_type: Vec<super::envelope::WarpedLook>,
/// The envelopes of type read with their drawn art, settled once the type is laid out
/// ([`super::envelope::TypedEnvelope`]).
typed_envelopes: Vec<super::envelope::TypedEnvelope>,
/// The live envelopes made so far and the drawn art each took the place of
/// ([`Structure::envelopes_drawn`]).
envelopes_drawn: Vec<(NodeId, Node)>,
Expand Down Expand Up @@ -769,6 +772,7 @@ impl<'a> Reader<'a> {
envelope_checks: super::envelope::MAX_CHECKED,
envelope_spent: super::envelope::Spent::default(),
warped_type: Vec::new(),
typed_envelopes: Vec::new(),
envelopes_drawn: Vec::new(),
clip_fills: HashSet::new(),
looks: HashSet::new(),
Expand Down
55 changes: 42 additions & 13 deletions crates/eps/src/import/ai/read/containers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,17 +516,17 @@ impl<'a> Reader<'a> {
slot.visible = false;
self.add(slot, false)?;
}
// An envelope of type keeps its drawn art and its type, hidden, as above: the
// type is filled in after reading, which the envelope can't wait for.
if typed {
self.warn(crate::import::ai::envelope::TYPE_DRAWN);
return Ok(());
}
if self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING {
self.warn(crate::import::ai::envelope::DRAWN);
// An envelope of type keeps its drawn art and its type, hidden, as above, until
// the type is filled in after reading: then it opens live where it draws as its
// drawn art ([`crate::import::ai::envelope::TypedEnvelope`]). In a symbol's or a
// pattern's art it keeps them.
let waits = !typed || (self.symbol.is_none() && self.pattern.is_none());
if !waits || self.envelopes.len() >= crate::import::ai::envelope::MAX_PENDING {
self.warn(crate::import::ai::envelope::drawn_note(typed));
} else {
let siblings = self.frames.last().map_or(0, |f| f.children.len());
self.envelopes.push(PendingEnvelope { obj: *o, before, inner: children, depth: self.frames.len(), siblings });
let depth = self.frames.len();
self.envelopes.push(PendingEnvelope { obj: *o, before, inner: children, depth, siblings, typed });
}
}
}
Expand Down Expand Up @@ -863,19 +863,22 @@ impl<'a> Reader<'a> {
/// in containers that closed keep their drawn art.
pub(super) fn end_envelope(&mut self) {
let depth = self.frames.len();
while self.envelopes.last().is_some_and(|p| p.depth > depth) {
self.envelopes.pop();
self.warn(crate::import::ai::envelope::DRAWN);
while let Some(p) = self.envelopes.pop_if(|p| p.depth > depth) {
self.warn(crate::import::ai::envelope::drawn_note(p.typed));
}
if self.envelopes.last().is_none_or(|p| p.depth != depth) {
return;
}
let Some(p) = self.envelopes.pop() else { return };
let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last());
let Some(drawn) = drawn else {
self.warn(crate::import::ai::envelope::DRAWN);
self.warn(crate::import::ai::envelope::drawn_note(p.typed));
return;
};
if p.typed {
self.wait_for_type(p);
return;
}
let live = (self.envelope_checks > 0).then(|| crate::import::ai::envelope::live(&p.obj, p.before, p.inner)).flatten();
let Some(kind) = live else {
self.warn(crate::import::ai::envelope::DRAWN);
Expand Down Expand Up @@ -932,6 +935,32 @@ impl<'a> Reader<'a> {
}
}

impl Reader<'_> {
/// An envelope of type `p` whose drawn art was just read (the last object of this container):
/// it waits for its type to be laid out ([`crate::import::ai::envelope::TypedEnvelope`]), unless
/// objects the reader couldn't read are in it, or too many already wait. Then it keeps its
/// drawn art and its type, hidden.
fn wait_for_type(&mut self, p: PendingEnvelope) {
let Some(drawn) = self.frames.last().and_then(|f| f.children.last()) else { return };
let mut ids = HashSet::new();
fn collect(n: &Node, ids: &mut HashSet<NodeId>) {
ids.insert(n.id);
for c in n.children().into_iter().flatten() {
collect(c, ids);
}
}
collect(drawn, &mut ids);
p.before.iter().chain(&p.inner).for_each(|n| collect(n, &mut ids));
let unread = self.unread.iter().any(|(id, _)| ids.contains(id));
if unread || self.typed_envelopes.len() >= crate::import::ai::envelope::MAX_CHECKED {
self.warn(crate::import::ai::envelope::TYPE_DRAWN);
return;
}
let drawn = drawn.id;
self.typed_envelopes.push(crate::import::ai::envelope::TypedEnvelope { obj: p.obj, before: p.before, inner: p.inner, drawn });
}
}

/// Does `node` hold a text slot?
fn has_text_slot(node: &Node) -> bool {
let mut slots = vec![];
Expand Down
11 changes: 8 additions & 3 deletions crates/eps/src/import/ai/read/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1165,9 +1165,8 @@ impl<'a> Reader<'a> {
self.warn(super::types::GRAPH_UNENDED);
}
// Envelopes whose plugin never closed them keep their drawn art.
if !self.envelopes.is_empty() {
self.envelopes.clear();
self.warn(crate::import::ai::envelope::DRAWN);
for p in std::mem::take(&mut self.envelopes) {
self.warn(crate::import::ai::envelope::drawn_note(p.typed));
}
if !self.unknown.is_empty() {
let ops: Vec<String> = self.unknown.iter().map(|o| format!("`{o}`")).collect();
Expand Down Expand Up @@ -1297,6 +1296,11 @@ impl<'a> Reader<'a> {
for w in &mut self.warped_type {
vectorcraft_doc::swatches::map_node_solid_paints(&mut w.look, &mut follow);
}
for e in &mut self.typed_envelopes {
for n in e.before.iter_mut().chain(e.inner.iter_mut()) {
vectorcraft_doc::swatches::map_node_solid_paints(n, &mut follow);
}
}
}
let mut warnings = self.warnings;
if let Some((lib, unread)) = brushes {
Expand Down Expand Up @@ -1341,6 +1345,7 @@ impl<'a> Reader<'a> {
envelopes_drawn: self.envelopes_drawn,
warped_type: super::super::envelope::WarpedType {
looks: self.warped_type,
envelopes: self.typed_envelopes,
checks: self.envelope_checks,
spent: self.envelope_spent,
page,
Expand Down
3 changes: 3 additions & 0 deletions crates/eps/src/import/ai/read/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,9 @@ pub(super) struct PendingEnvelope {
/// had: its drawn art is the one child after them.
pub(super) depth: usize,
pub(super) siblings: usize,
/// Its contents hold type: it is settled once the type is laid out
/// ([`super::super::envelope::TypedEnvelope`]).
pub(super) typed: bool,
}

/// What a reader of a pattern's definition has of its head, `(name) llx lly urx ury`: the operands
Expand Down
2 changes: 1 addition & 1 deletion crates/eps/src/import/ai/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7992,7 +7992,7 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() {
let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None };
let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0));
let settle = |w: &super::envelope::WarpedLook, spent| {
let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page };
let warped = super::envelope::WarpedType { looks: vec![copy(w)], envelopes: vec![], checks: 1, spent, page };
warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![])
};
let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 };
Expand Down
Loading
Loading