//! The save pipeline: Save writes a document's own format, Save As / a Copy / as Template, Revert //! and templates. use std::path::PathBuf; use serde_json::{Value, json}; use super::*; use crate::cmd::fileio::{SaveMode, save_plan}; fn session() -> Session { let mut s = Session::new(); s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); s } fn rect(s: &mut Session) { s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); } /// A fresh folder for one test. fn dir(tag: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("vc-save-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); d } fn path(d: &std::path::Path, name: &str) -> String { d.join(name).to_string_lossy().to_string() } fn b64(v: &Value) -> Vec { vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap() } fn objects(s: &Session) -> usize { s.doc().unwrap().doc.node_count() } #[test] fn an_svg_path_writes_svg_and_save_writes_it_back() { let d = dir("svg"); let mut s = session(); rect(&mut s); let svg = path(&d, "art.svg"); let r = s.execute("document.save", &json!({"path": svg})).unwrap(); assert_eq!(r["format"], "svg"); assert!(r["warnings"][0].as_str().unwrap().contains("SVG keeps the artwork"), "{r}"); assert!(std::fs::read_to_string(&svg).unwrap().starts_with(" = o["saveFormats"].as_array().unwrap().iter().map(|f| f["id"].as_str().unwrap()).collect(); assert_eq!(ids, ["vectorcraft", "template", "pdf", "svg", "svgz", "ai"]); // SVGZ is gzip-compressed SVG and reopens as SVGZ. let svgz = path(&d, "doc.svgz"); s.execute("file.saveAs", &json!({"path": svgz})).unwrap(); assert_eq!(&std::fs::read(&svgz).unwrap()[..2], [0x1f, 0x8b]); s.execute("document.open", &json!({"path": svgz})).unwrap(); assert_eq!(s.doc().unwrap().format, "svgz"); // Export formats aren't save formats. let e = s.execute("file.saveAs", &json!({"path": path(&d, "x.png")})).unwrap_err().to_string(); assert!(e.contains("document.export"), "{e}"); assert!(s.execute("document.save", &json!({"format": "webp"})).is_err()); assert!(s.execute("file.saveAs", &json!({"path": svgz, "options": 3})).is_err()); let _ = std::fs::remove_dir_all(d); } #[test] fn another_format_without_a_path_hands_the_bytes_back() { let d = dir("otherfmt"); let mut s = session(); let native = path(&d, "a.vectorcraft"); s.execute("document.save", &json!({"path": native})).unwrap(); let r = s.execute("document.save", &json!({"format": "svg"})).unwrap(); assert!(String::from_utf8(b64(&r)).unwrap().starts_with(" empty && !st.selection.is_empty(), "the template's art is placed and selected"); }