Skip to content
Draft
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: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions assets/locales/pending/file-pack.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"en": { "cmd.file_pack": "Pack Design" },
"ar": { "cmd.file_pack": "حزم التصميم" },
"de": { "cmd.file_pack": "Konstruktion packen" },
"es": { "cmd.file_pack": "Empaquetar diseño" },
"fr": { "cmd.file_pack": "Empaqueter la conception" },
"he": { "cmd.file_pack": "אריזת תכן" },
"ja": { "cmd.file_pack": "デザインをパック" },
"ko": { "cmd.file_pack": "설계 묶기" },
"vi": { "cmd.file_pack": "Đóng gói thiết kế" },
"zh": { "cmd.file_pack": "打包设计" },
"zh-TW": { "cmd.file_pack": "打包設計" }
}
2 changes: 2 additions & 0 deletions crates/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ web-time = { workspace = true }
solidcraft-io = { workspace = true, features = ["trust-unknown-source"] }
# Normal CI exercises profiling assertions without enabling the production feature.
solidcraft-sketch = { workspace = true, features = ["solver-profiling"] }
# Packs (file.pack) are read back to check what they hold.
zip = { workspace = true }

[[example]]
name = "render_resource_workflow"
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
)
}

fn default_design_format(path: &str) -> &'static str {
pub(super) fn default_design_format(path: &str) -> &'static str {
if std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("json")) { "json" } else { "container" }
}

Expand Down
111 changes: 111 additions & 0 deletions crates/engine/src/cmd/file_pack.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
//! `file.pack` (#3890 K12): the saved design and the designs its links name, in one `.zip` to hand
//! on. The design goes at the top level with each link pointing at `designs/<name>`, and each
//! linked design under `designs/`, byte for byte. Packs go one level deep: a linked design's own
//! links are listed in the reply, not followed. Only design files are copied.
//!
//! A pack holds the files as saved, so a design with unsaved changes or no file is refused; the
//! design, its file and its links are left as they were. Every linked file is checked before any
//! is read, and the sizes are summed before any is read, within [`solidcraft_io::MAX_PACK_BYTES`].

use std::path::{Path, PathBuf};

use serde_json::Value;
use solidcraft_io::{MAX_PACK_DESIGNS, PACK_DESIGNS, PackWriter};

use super::CommandSpec;
use super::design_link::{absolute, resolve};
use crate::params::bad;
use crate::schema::file_pack::{DeeperLink, PackParams, PackResult, PackedDesign};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};

const CMD: &str = "file.pack";
const CONTRACT: TypedContract<PackParams> = TypedContract::new();
/// The longest path taken, in bytes, as `drawing.export`'s.
const MAX_PATH_BYTES: usize = 4096;

pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Pack Design", crate::checked!("file.pack", pack))
.any_part()
.icon("export")
.noundo()
.doc_only()
.contract(&CONTRACT)
.output(output_schema_for::<PackResult>)
.params("path: .zip file → {path, bytes, design, designs: [{file, entry}], deeper: [{design, path}]}. The saved design at the top level, its links pointing at designs/<name>, and each design its links name under designs/, byte for byte, once each; a linked design's own links are listed in deeper, not followed. Refused when the design has no file or unsaved changes, or a linked file can't be read or isn't a design; at most 1 GiB in all.")];

fn pack(s: &mut Session, p: &Value) -> Result<Value> {
let request: PackParams = crate::schema::read(CMD, p)?;
let path = request.path;
if path.len() > MAX_PATH_BYTES || !solidcraft_io::is_pack_path(&path) {
return Err(bad(CMD, "path must be a .zip file"));
}
let io = |e: std::io::Error| EngineError::Other(e.to_string());
solidcraft_io::vfs::check(&path).map_err(io)?;
let own = s.path.clone().ok_or_else(|| bad(CMD, "the design has no file yet: save it first"))?;
if s.is_dirty() {
return Err(bad(CMD, "the design has unsaved changes: save it first"));
}
let files = linked_files(s, &own)?;
// Every file checked from its text, then measured, before any is read.
for (file, link) in &files {
solidcraft_io::vfs::check_design_path(&file.to_string_lossy(), Some(&own)).map_err(|e| bad(CMD, format!("{link}: {e}")))?;
}
let mut total = 0u64;
for (file, link) in &files {
total = total.saturating_add(solidcraft_io::vfs::len(&file.to_string_lossy()).map_err(|e| bad(CMD, format!("{link}: {e}")))?);
}
solidcraft_io::fits_pack(total).map_err(|e| bad(CMD, e.to_string()))?;

let mut pack = PackWriter::default();
let (mut designs, mut deeper) = (Vec::new(), Vec::new());
let mut doc = s.design_at(None).into_owned();
for (file, link) in &files {
let shown = file.to_string_lossy();
let bytes = solidcraft_io::vfs::read_design_path(&shown, Some(&own), solidcraft_io::limits::max_design_bytes())
.map_err(|e| bad(CMD, format!("{link}: {}", solidcraft_io::limits::explain(solidcraft_io::limits::Kind::Design, e))))?;
// Only a design is copied: anything else is refused by its link alone, never quoted.
let linked = solidcraft_io::read_design(&bytes).map_err(|_| bad(CMD, format!("{link}: not a design file")))?;
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let entry = pack.add(Some(PACK_DESIGNS), &name, &bytes).map_err(|e| bad(CMD, e.to_string()))?;
for l in doc.links.values_mut().filter(|l| absolute(&resolve(Some(&own), &l.path)) == *file) {
l.path.clone_from(&entry);
}
deeper.extend(linked.links.values().map(|l| DeeperLink { design: entry.clone(), path: l.path.clone() }));
designs.push(PackedDesign { file: shown.into_owned(), entry });
}
let top = match super::file::default_design_format(&own) {
"json" => solidcraft_io::write_design(&doc),
_ => solidcraft_io::write_design_container(&doc).map_err(|e| bad(CMD, e.to_string()))?,
};
let name = Path::new(&own).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let design = pack.add(None, &name, &top).map_err(|e| bad(CMD, e.to_string()))?;
let bytes = pack.finish().map_err(|e| bad(CMD, e.to_string()))?;
// Checked again just before writing, as drawing.export does.
solidcraft_io::vfs::check(&path).map_err(io)?;
solidcraft_io::write_atomic(Path::new(&path), &bytes, false).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let reply = PackResult { path, bytes: bytes.len(), design, designs, deeper, param_warnings: Vec::new() };
serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string()))
}

/// Each file the design's links name, once, in link order, with the link that names it first
/// (as the design keeps it, for messages). The design itself is never one of them.
fn linked_files(s: &Session, own: &str) -> Result<Vec<(PathBuf, String)>> {
let mut files: Vec<(PathBuf, String)> = Vec::new();
for link in s.doc.links.values() {
let file = absolute(&resolve(Some(own), &link.path));
if file == absolute(Path::new(own)) {
return Err(bad(CMD, format!("{}: a design can't be packed as its own link", link.path)));
}
if !files.iter().any(|(f, _)| *f == file) {
files.push((file, link.path.clone()));
}
}
if files.len() > MAX_PACK_DESIGNS {
return Err(bad(CMD, format!("the design links {} files; a pack holds at most {MAX_PACK_DESIGNS}", files.len())));
}
Ok(files)
}

#[cfg(test)]
#[path = "file_pack_tests.rs"]
mod tests;
218 changes: 218 additions & 0 deletions crates/engine/src/cmd/file_pack_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
use std::io::Read;
use std::path::Path;

use serde_json::{Value, json};

use super::*;
use crate::schema::tests::conforms;
use crate::tests::Folder;

fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}

fn refused(s: &mut Session, p: Value) -> String {
s.execute(CMD, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("packed: {p}"))
}

/// A box `height` mm high called Plate, saved at `path`.
fn save_box(path: &str, height: f64) {
let mut part = Session::default();
run(&mut part, "solid.box", json!({"length": 10, "width": 20, "height": height, "body_name": "Plate"}));
run(&mut part, "file.save", json!({"path": path}));
}

fn volume(s: &mut Session) -> f64 {
run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap()
}

/// A design saved at `path` linking each of `parts`.
fn assembly(path: &str, parts: &[&str]) -> Session {
let mut s = Session::default();
for part in parts {
run(&mut s, "component.insert_design", json!({"path": part}));
}
run(&mut s, "file.save", json!({"path": path}));
s
}

/// Each entry of the pack at `path`, by name, unpacked into `into`.
fn unpack(path: &str, into: &Path) -> Vec<(String, Vec<u8>)> {
let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap();
let mut entries = Vec::new();
for i in 0..zip.len() {
let mut file = zip.by_index(i).unwrap();
let name = file.name().unwrap().into_owned();
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let to = into.join(&name);
std::fs::create_dir_all(to.parent().unwrap()).unwrap();
std::fs::write(&to, &bytes).unwrap();
entries.push((name, bytes));
}
entries
}

/// A pack holds the design at the top level and each design its links name once under
/// `designs/`, byte for byte; unpacked anywhere it opens with every link found and the same
/// model. The design, its file and its links are left as they were.
#[test]
fn a_pack_opens_anywhere_with_every_link_found() {
let folder = Folder::new("pack-links");
std::fs::create_dir_all(folder.0.join("parts")).unwrap();
std::fs::create_dir_all(folder.0.join("asm")).unwrap();
let plate = folder.path("parts/plate.solidcraft");
save_box(&plate, 30.0);
let case = folder.path("asm/case.solidcraft");
// Two placements of one linked design: one file in the pack.
let mut s = assembly(&case, &[&plate, &plate]);
let (before, saved, doc) = (volume(&mut s), std::fs::read(&case).unwrap(), s.doc.clone());
let zip = folder.path("out.zip");
let reply = run(&mut s, CMD, json!({"path": zip}));
let schema = output_schema_for::<PackResult>();
assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}");
assert_eq!(
(&reply["design"], &reply["designs"][0]["entry"], &reply["deeper"]),
(&json!("case.solidcraft"), &json!("designs/plate.solidcraft"), &json!([]))
);
assert_eq!(reply["designs"].as_array().map(Vec::len), Some(1), "{reply}");
assert_eq!(reply["bytes"].as_u64(), Some(std::fs::metadata(&zip).unwrap().len()));
let elsewhere = Folder::new("pack-links-unpacked");
let entries = unpack(&zip, &elsewhere.0);
let names: Vec<&str> = entries.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["designs/plate.solidcraft", "case.solidcraft"]);
assert_eq!(entries[0].1, std::fs::read(&plate).unwrap(), "byte for byte");
let mut opened = Session::default();
run(&mut opened, "doc.open", json!({"path": elsewhere.path("case.solidcraft")}));
let links = run(&mut opened, "component.links", json!({}));
for link in links["links"].as_array().unwrap() {
assert_eq!(link["found"], true, "{links}");
assert_eq!(super::absolute(Path::new(link["file"].as_str().unwrap())), super::absolute(&elsewhere.0.join("designs/plate.solidcraft")));
}
assert!((volume(&mut opened) - before).abs() < 1e-6);
// Nothing here changed.
assert_eq!(std::fs::read(&case).unwrap(), saved);
assert!(std::sync::Arc::ptr_eq(&doc, &s.doc) && !s.is_dirty() && s.path.as_deref() == Some(case.as_str()));
}

/// Linked files of one name are numbered apart, and a linked design's own links are listed, not
/// followed: the pack goes one level deep.
#[test]
fn names_are_numbered_apart_and_deeper_links_listed() {
let folder = Folder::new("pack-names");
for dir in ["a", "b"] {
std::fs::create_dir_all(folder.0.join(dir)).unwrap();
}
let (first, second, bolt) = (folder.path("a/plate.solidcraft"), folder.path("b/plate.solidcraft"), folder.path("b/bolt.solidcraft"));
save_box(&first, 30.0);
save_box(&bolt, 5.0);
assembly(&second, &[&bolt]);
let mut s = assembly(&folder.path("case.solidcraft"), &[&first, &second]);
let reply = run(&mut s, CMD, json!({"path": folder.path("case.zip")}));
let entries: Vec<&str> = reply["designs"].as_array().unwrap().iter().map(|d| d["entry"].as_str().unwrap()).collect();
assert_eq!(entries, ["designs/plate.solidcraft", "designs/plate-2.solidcraft"]);
assert_eq!(reply["deeper"], json!([{"design": "designs/plate-2.solidcraft", "path": "bolt.solidcraft"}]));
let elsewhere = Folder::new("pack-names-unpacked");
unpack(&folder.path("case.zip"), &elsewhere.0);
let mut opened = Session::default();
run(&mut opened, "doc.open", json!({"path": elsewhere.path("case.solidcraft")}));
let links = run(&mut opened, "component.links", json!({}));
assert!(links["links"].as_array().unwrap().iter().all(|l| l["found"] == true), "{links}");
}

/// A design with no file or unsaved changes, a path that isn't a .zip, and a link to a file that
/// can't be read, a device, a network location not allowed, the design itself or anything that
/// isn't a design are refused, and nothing is written. A refused link is named by its path, never
/// by what the file holds, and one judged from its text asks nothing of the disk.
#[test]
fn what_cant_be_packed_is_refused_and_nothing_is_written() {
let folder = Folder::new("pack-refused");
let zip = folder.path("out.zip");
let mut s = Session::default();
assert!(refused(&mut s, json!({"path": zip})).contains("no file yet"));
let plate = folder.path("plate.solidcraft");
save_box(&plate, 30.0);
let case = folder.path("case.solidcraft");
let mut s = assembly(&case, &[&plate]);
for (path, why) in [
(json!(folder.path("out.svg")), "path must be a .zip file"),
(json!(folder.path("zip")), "path must be a .zip file"),
(json!(format!("{}.zip", "a".repeat(MAX_PATH_BYTES))), "path must be a .zip file"),
(json!(5), "path"),
] {
let e = refused(&mut s, json!({"path": path}));
assert!(e.contains(why), "{path}: {e}");
}
assert!(refused(&mut s, json!({})).contains("path"));
run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1}));
assert!(refused(&mut s, json!({"path": zip})).contains("unsaved changes"));
run(&mut s, "edit.undo", json!({}));
run(&mut s, "file.save", json!({}));
// Not a design: refused by its link alone.
std::fs::write(&plate, "a key that must never be copied").unwrap();
let e = refused(&mut s, json!({"path": zip}));
assert!(e.contains("not a design file") && !e.contains("never be copied"), "{e}");
std::fs::remove_file(&plate).unwrap();
assert!(refused(&mut s, json!({"path": zip})).contains("plate.solidcraft"));
// Links judged from their text before the disk is asked.
for (link, why) in [(r"\\server\share\plate.solidcraft", "network location"), ("NUL", "device"), (case.as_str(), "its own link")] {
let component = *s.doc.links.keys().next().unwrap();
s.doc_mut().links.get_mut(&component).unwrap().path = link.to_string();
run(&mut s, "file.save", json!({}));
let calls = solidcraft_io::vfs::file_calls();
let e = refused(&mut s, json!({"path": zip}));
assert!(e.contains(why), "{link}: {e}");
assert_eq!(solidcraft_io::vfs::file_calls(), calls, "{link}: nothing asked of the disk");
}
// More than a pack holds in all: refused from the files' sizes, before any is read.
let big = folder.path("big.solidcraft");
std::fs::File::create(&big).unwrap().set_len(solidcraft_io::MAX_PACK_BYTES + 1).unwrap();
let component = *s.doc.links.keys().next().unwrap();
s.doc_mut().links.get_mut(&component).unwrap().path = big.clone();
run(&mut s, "file.save", json!({}));
let e = refused(&mut s, json!({"path": zip}));
assert!(e.contains("a pack holds at most 1024 MiB"), "{e}");
std::fs::remove_file(&big).unwrap();
assert!(!Path::new(&zip).exists());
}

/// A design saved as JSON goes in the pack as JSON, its link pointing into the pack.
#[test]
fn a_json_design_is_packed_as_json() {
let folder = Folder::new("pack-json");
let plate = folder.path("plate.solidcraft");
save_box(&plate, 30.0);
let case = folder.path("case.json");
let mut s = assembly(&case, &[&plate]);
let zip = folder.path("out.zip");
assert_eq!(run(&mut s, CMD, json!({"path": zip}))["design"], json!("case.json"));
let elsewhere = Folder::new("pack-json-unpacked");
let entries = unpack(&zip, &elsewhere.0);
let top = entries.iter().find(|(name, _)| name == "case.json").map(|(_, bytes)| bytes).unwrap();
let top: Value = serde_json::from_slice(top).unwrap();
assert!(top.to_string().contains("designs/plate.solidcraft"), "{top}");
}

/// A pack carries at most `MAX_PACK_DESIGNS` linked files: one more is refused from the links alone.
#[test]
fn a_pack_carries_at_most_its_designs() {
let folder = Folder::new("pack-cap");
let plate = folder.path("plate.solidcraft");
save_box(&plate, 30.0);
let case = folder.path("case.solidcraft");
let mut s = assembly(&case, &[&plate]);
let link = s.doc.links.values().next().cloned().unwrap();
let mut files = |n: usize| {
s.doc_mut().links = (1..=n as u64)
.map(|i| {
let mut link = link.clone();
link.path = folder.path(&format!("part-{i}.solidcraft"));
(i, link)
})
.collect();
linked_files(&s, &case).map(|files| files.len()).map_err(|e| e.to_string())
};
assert_eq!(files(MAX_PACK_DESIGNS), Ok(MAX_PACK_DESIGNS));
let e = files(MAX_PACK_DESIGNS + 1).unwrap_err();
assert!(e.contains("a pack holds at most 256"), "{e}");
}
2 changes: 2 additions & 0 deletions crates/engine/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ pub use component_link::resolve_design_links;
mod config;
mod design_link;
mod file;
mod file_pack;
mod frame;
pub(crate) mod inspect;
mod interference;
Expand Down Expand Up @@ -374,6 +375,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
v.extend(parameters::COMMANDS.iter());
v.extend(parameter_sweep::COMMANDS.iter());
v.extend(file::COMMANDS.iter());
v.extend(file_pack::COMMANDS.iter());
v.extend(metadata::COMMANDS.iter());
v.extend(inspect::COMMANDS.iter());
v.extend(compare::COMMANDS.iter());
Expand Down
Loading