[doc] Editor core: document model, exact undo, .pictor format, text layout, display list, tiny-skia render, bitmap tools, SVG import, PNG/JPG/SVG/PDF export; worker doc.open and doc.import_svg

This commit is contained in:
2026-11-17 10:07:12 +01:00
parent e46cbe3547
commit 17db54fdbf
26 changed files with 6589 additions and 7 deletions
+2
View File
@@ -25,6 +25,7 @@ pictor-pdf.workspace = true
pictor-meta.workspace = true
pictor-qr.workspace = true
pictor-save.workspace = true
pictor-doc.workspace = true
[target.'cfg(windows)'.dependencies]
windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_Security"] }
@@ -33,3 +34,4 @@ windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_JobO
tempfile.workspace = true
lopdf.workspace = true
flate2.workspace = true
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
+44
View File
@@ -100,6 +100,18 @@ fn png(img: &image::DynamicImage) -> Result<Vec<u8>, OpError> {
use image::ImageEncoder;
fn doc_error(e: impl std::fmt::Display + std::fmt::Debug) -> OpError {
let msg = e.to_string();
let code = if msg.contains("newer Pictor") {
"newer"
} else if msg.contains("too large") {
"too_large"
} else {
"damaged"
};
OpError::new(code, msg)
}
pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError> {
match op {
// ---- PDF sessions -------------------------------------------------------------------------------------
@@ -368,6 +380,38 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h}))
}
// ---- Documents (.pictor, SVG) ------------------------------------------------------------------------
// An outside .pictor or SVG is read here, with caps, and written back as a clean .pictor of the worker's
// own making; the tray process opens only that copy.
"doc.open" => {
#[derive(Deserialize)]
struct A {
input: String,
output: String,
}
let a: A = args(a)?;
let src = read_file(&a.input)?;
let (doc, fonts) = pictor_doc::format::read(&src, &pictor_doc::Limits::default()).map_err(doc_error)?;
let clean = pictor_doc::format::write(&doc, &fonts).map_err(doc_error)?;
pictor_save::save_overwrite(Path::new(&a.output), &clean)?;
Ok(json!({"path": a.output, "pages": doc.pages.len(), "format": doc.format}))
}
"doc.import_svg" => {
#[derive(Deserialize)]
struct A {
input: String,
output: String,
}
let a: A = args(a)?;
let src = read_file(&a.input)?;
if src.len() > 64 << 20 {
return Err(OpError::new("too_large", "This SVG is larger than 64 MB, which Pictor does not import."));
}
let doc = pictor_doc::svg::import(&src, pictor_doc::svg::system_fontdb()).map_err(doc_error)?;
let clean = pictor_doc::format::write(&doc, &[]).map_err(doc_error)?;
pictor_save::save_overwrite(Path::new(&a.output), &clean)?;
Ok(json!({"path": a.output, "width": doc.pages[0].width, "height": doc.pages[0].height}))
}
"image.convert" => {
#[derive(Deserialize)]
struct A {
+70
View File
@@ -0,0 +1,70 @@
//! The worker's side of documents: `doc.open` turns a good .pictor into a clean copy and refuses hostile ones
//! (zip slip, a bomb, a newer format) with a clear error, staying alive for the next request; `doc.import_svg`
//! turns an SVG into a .pictor.
use pictor_worker::client::{Worker, WorkerOptions};
use serde_json::json;
use std::io::Write;
use std::path::PathBuf;
use std::time::Duration;
const CAP: Duration = Duration::from_secs(30);
fn worker() -> Worker {
let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-worker"));
o.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
o.memory_mb = 1024;
o.debug = true;
Worker::new(o)
}
fn zip_of(entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
for (n, d) in entries {
z.start_file(*n, opts).unwrap();
z.write_all(d).unwrap();
}
z.finish().unwrap().into_inner()
}
#[test]
fn doc_open_cleans_good_files_and_refuses_hostile_ones() {
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
let mut w = worker();
let good = dir.path().join("good.pictor");
std::fs::write(&good, pictor_doc::format::write(&pictor_doc::fixtures::bitmap(), &[]).unwrap()).unwrap();
let out = dir.path().join("clean.pictor");
let r = w.call("doc.open", json!({"input": good, "output": out}), CAP).expect("a good document opens");
assert_eq!(r["pages"], 1);
let (doc, _) = pictor_doc::format::read(&std::fs::read(&out).unwrap(), &Default::default()).unwrap();
assert_eq!(doc, pictor_doc::fixtures::bitmap());
let json = br#"{"format":1,"next_id":3,"pages":[{"id":1,"width":100,"height":100,"layers":[]}]}"#;
let cases: Vec<(&str, Vec<u8>, &str)> = vec![
("slip", zip_of(&[("document.json", json), ("../../evil.dll", b"MZ")]), "damaged"),
("newer", zip_of(&[("document.json", br#"{"format":9}"#)]), "newer"),
("not a zip", b"hello".to_vec(), "damaged"),
];
for (name, bytes, code) in cases {
let p = dir.path().join(format!("{}.pictor", name.replace(' ', "-")));
std::fs::write(&p, bytes).unwrap();
let e = w.call("doc.open", json!({"input": p, "output": dir.path().join("x.pictor")}), CAP).expect_err(name);
let msg = format!("{e:?}");
assert!(msg.contains(code), "{name}: {msg}");
assert!(!dir.path().join("evil.dll").exists() && !dir.path().parent().unwrap().join("evil.dll").exists());
}
// Still alive for the next request.
w.call("doc.open", json!({"input": good, "output": out}), CAP).expect("the worker survives hostile files");
}
#[test]
fn doc_import_svg_writes_a_document() {
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
let svg = dir.path().join("logo.svg");
std::fs::write(&svg, br##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><circle cx="20" cy="20" r="18" fill="#f27ab9"/></svg>"##).unwrap();
let out = dir.path().join("logo.pictor");
let r = worker().call("doc.import_svg", json!({"input": svg, "output": out}), CAP).unwrap();
assert_eq!(r["width"], 30.0);
let (doc, _) = pictor_doc::format::read(&std::fs::read(&out).unwrap(), &Default::default()).unwrap();
assert_eq!(doc.pages.len(), 1);
}