Skip to content

VectorCraft: An open-source, vector art tool written by scratch in pure Rust

Merge origin/main into #777

bflatastic94f27299d490
diff --cc crates/engine/src/cmd/package.rs
index d71980567,016c7c85e..b649c3eb4
--- a/crates/engine/src/cmd/package.rs
+++ b/crates/engine/src/cmd/package.rs
@@@ -62,214 -70,6 +73,220 @@@ struct Options
report: bool,
}
+/// An asset that has been copied to the package, including rewritten linked documents.
+#[derive(Clone)]
+struct Copied {
+ name: String,
+ size: Option<u64>,
+ hash: Option<String>,
+}
+
+/// The parent of a packaged document and its asset both live inside the package.
+/// Use paths relative to that *document*, not the package's root: a linked document
+/// in Links/ must reference its own sibling image as "image.png".
+fn relative_in_package(document: &str, asset: &str) -> String {
+ let parent = document.rsplit_once('/').map_or("", |(dir, _)| dir);
+ let a: Vec<&str> = parent.split('/').filter(|s| !s.is_empty()).collect();
+ let b: Vec<&str> = asset.split('/').filter(|s| !s.is_empty()).collect();
+ let common = a.iter().zip(&b).take_while(|(a, b)| a == b).count();
+ let mut out = vec![".."; a.len() - common];
+ out.extend_from_slice(&b[common..]);
+ out.join("/")
+}
+
+fn safe_asset_name(name: &str) -> String {
+ let name: String = name
+ .chars()
+ .map(|c| if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c })
+ .collect();
+ let name = name.trim().trim_matches('.');
+ if name.is_empty() { "asset".into() } else { name.into() }
+}
+
+/// Collect dependencies depth-first so nested VectorCraft files are rewritten before
+/// their parents: each parent can record the final hash of the rewritten child.
+/// Cycles, excessive nesting, and unreadable children are reported, not fatal.
+struct Collector<'a> {
+ opts: &'a Options,
+ root: Option<PathBuf>,
+ entries: Vec<Entry>,
+ copies: BTreeMap<String, Copied>,
+ visiting: BTreeMap<String, String>,
+ taken: HashSet<String>,
+ link_names: HashSet<String>,
+ font_files: HashSet<String>,
+ fonts: usize,
+ missing: Vec<String>,
+ skipped: Vec<Value>,
+ warnings: Vec<String>,
+ lines: Vec<String>,
+}
+
+impl<'a> Collector<'a> {
+ fn new(opts: &'a Options, root: Option<PathBuf>, doc_name: &str) -> Self {
+ let mut taken = HashSet::new();
+ taken.insert(doc_name.to_lowercase());
+ Self {
+ opts,
+ root,
+ entries: Vec::new(),
+ copies: BTreeMap::new(),
+ visiting: BTreeMap::new(),
+ taken,
+ link_names: HashSet::new(),
+ font_files: HashSet::new(),
+ fonts: 0,
+ missing: Vec::new(),
+ skipped: Vec::new(),
+ warnings: Vec::new(),
+ lines: Vec::new(),
+ }
+ }
+
+ fn warn(&mut self, message: String) {
+ self.lines.push(format!("WARNING: {message}"));
+ self.warnings.push(message);
+ }
+
+ fn collect(&mut self, doc: &mut Document, source: &str, destination: &str, depth: usize) -> Result<()> {
+ // The caller checks cycles and depth before descending; active documents have
+ // a destination reserved so back-links can point at their single packaged copy.
+ let previous = self.visiting.insert(source.to_string(), destination.to_string());
+ debug_assert!(previous.is_none(), "collector visits each document once");
+ // A file's saved path is only meaningful inside its own document.
+ // Different linked documents can reuse the same stale absolute path yet
+ // resolve it to distinct local assets. Keep a mapping per document.
+ let mut local = BTreeMap::<String, Copied>::new();
+ if self.opts.copy_links {
+ let mut placed = HashSet::new();
+ doc.visit_placed(|_, p| { placed.insert(p.link.path.clone()); });
+ // Keep this exact header for programs parsing Package reports.
+ self.lines.push("LINKED FILES".into());
+ self.lines.push(format!("Document: {source}"));
+ for file in super::links::linked_files(doc, Some(source)) {
+ let found_path = file.found_path.as_deref().unwrap_or(&file.path);
+ if let Some(ancestor) = self.visiting.get(found_path).cloned() {
+ // The ancestor is already included (possibly the root document). A
+ // cyclic reference cannot have a final content hash until both files
+ // have been written, so leave its size/hash unspecified, not stale.
+ self.warn(format!("{}: circular placed-document link to {ancestor}; stopped following the cycle", file.path));
+ local.insert(file.path.clone(), Copied { name: ancestor, size: None, hash: None });
+ continue;
+ }
+ if let Some(existing) = self.copies.get(found_path) {
+ local.insert(file.path.clone(), existing.clone());
+ continue;
+ }
+ let Some(mut bytes) = file.bytes else {
+ self.lines.push(format!("{}: not found ({}), not copied", file.name, file.path));
+ self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({source})", file.name) });
+ continue;
+ };
+ if self.copies.len() >= 10_000 {
+ return Err(bad(C, "more than 10000 linked files: package dependencies in smaller parts"));
+ }
+ let dir = if self.opts.links_folder { "Links/" } else { "" };
+ let name = safe_asset_name(&file.name);
+ let unique = free_name(&name, if self.opts.links_folder { &mut self.link_names } else { &mut self.taken });
+ let destination_file = format!("{dir}{unique}");
+ if placed.contains(&file.path) {
+ if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
+ self.warn(format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path));
+ } else {
+ match vectorcraft_format::load_file(&bytes) {
+ Ok(saved) => {
+ let preview = vectorcraft_format::preview(&bytes);
+ let pdf = vectorcraft_format::pdf_content(&bytes);
+ let compressed = bytes.starts_with(&[0x1f, 0x8b]);
+ let include_linked = saved
+ .doc
+ .linked_only_images()
+ .iter()
+ .any(|key| saved.doc.images.get(key).is_some_and(|blob| !blob.is_proxy()));
+ let mut nested = saved.doc;
+ self.collect(&mut nested, found_path, &destination_file, depth + 1)?;
+ if self.opts.relink {
+ // Preserve auxiliary native-file content when rewriting.
+ let mut options = vectorcraft_format::SaveOptions::for_doc(&nested);
+ options.preview = preview;
+ options.pdf = pdf;
+ options.profiles = saved.profiles;
+ options.compress = compressed;
+ options.include_linked = include_linked;
+ match vectorcraft_format::save_with(&nested, &options) {
+ Ok(rewritten) => bytes = rewritten,
+ Err(e) => self.warn(format!("{}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked", file.path)),
+ }
+ }
+ }
+ Err(e) => self.warn(format!("{}: unreadable linked document ({e}); copied unchanged, its own links were not collected", file.path)),
+ }
+ }
+ }
+ let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
+ self.copies.insert(found_path.to_string(), copy.clone());
+ local.insert(file.path.clone(), copy);
+ self.lines.push(format!("{} → {destination_file}", file.path));
+ self.entries.push((destination_file, bytes));
+ }
+ self.lines.push(String::new());
+ }
+ if self.opts.copy_fonts {
+ let db = vectorcraft_text::FontDb::global();
+ self.lines.push("FONTS".into());
+ self.lines.push(format!("Document: {source}"));
- for (family, style) in super::fonts::used_fonts(doc) {
- let font = format!("{family} {style}");
- let reason = match db.face(&family, &style) {
- Some(f) if f.family.eq_ignore_ascii_case(&family) && f.embeddable() => {
++ for used in super::fonts::used_fonts(doc) {
++ let font = super::fonts::font_label(&used);
++ let (family, style, version) = used;
++ // Found by any of its names, as the canvas draws it (in the version the type names).
++ let resolved = db
++ .resolve(&family, &style)
++ .filter(|(_, m)| *m != vectorcraft_text::FontMatch::Missing)
++ .map(|(f, m)| (db.face_version(&family, &style, version.as_deref()).unwrap_or(f), m));
++ // A style the family lacks is shown in its closest style, whose file is copied.
++ let shown = match &resolved {
++ Some((f, vectorcraft_text::FontMatch::Style)) => format!(" (shown in {} {})", f.family, f.style),
++ _ => String::new(),
++ };
++ let reason = match resolved {
++ Some((f, _)) if f.embeddable() => {
+ let data = f.file_data();
- let file = f.path().and_then(Path::file_name).map_or_else(
- || {
- format!("{}-{}.{}", f.family, f.style, font_ext(data))
- .replace(|c: char| !(c.is_alphanumeric() || "-_.".contains(c)), "")
- },
- |n| n.to_string_lossy().into_owned(),
- );
++ let file = packaged_name(f.path(), &f.family, &f.style, data);
++ // A collection, or a style shown in another face's file, is copied once.
+ if self.font_files.insert(file.to_lowercase()) {
+ self.entries.push((format!("Fonts/{file}"), data.to_vec()));
+ self.fonts += 1;
+ }
- self.lines.push(format!("{font} → Fonts/{file}"));
++ self.lines.push(format!("{font}{shown} → Fonts/{file}"));
+ continue;
+ }
- Some(f) if f.family.eq_ignore_ascii_case(&family) => "its licence doesn't allow embedding",
- _ => "not available on this computer",
++ Some(_) => "its licence doesn't allow embedding",
++ None => "not available on this computer",
+ };
- self.lines.push(format!("{font}: {reason}, not copied"));
++ self.lines.push(format!("{font}{shown}: {reason}, not copied"));
+ self.skipped.push(json!({ "font": font, "reason": reason }));
+ }
+ self.lines.push(String::new());
+ }
+ if self.opts.relink {
+ // The child files have already been rewritten; the hash and size of each
+ // target must reflect the *packaged* bytes rather than the original.
+ doc.update_links(|link: &mut LinkInfo| {
+ if let Some(copy) = local.get(&link.path) {
+ let relative = relative_in_package(destination, &copy.name);
+ link.path = self.root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(&copy.name).to_string_lossy().into_owned());
+ link.relative = Some(relative);
+ link.size = copy.size;
+ link.hash = copy.hash.clone();
+ link.modified = None;
+ }
+ });
+ }
+ let _ = self.visiting.remove(source);
+ Ok(())
+ }
+}
+
fn package(s: &mut Session, p: &Value) -> Result<Value> {
let o = Options {
copy_links: bool_or(p, "copyLinks", true),