Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Don't embed linked smart-object files in automation PSD saves

James Chapmanb4d6d3f639b6
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index 1e3e83e1b..bed78c0f6 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -261,7 +261,10 @@ impl Headless {
files::save(&doc, &target, format, opts, Some(writer))?
}
Filesystem::Workspace(workspace) => {
- let (bytes, warnings) = files::save_bytes(&doc, target_text, format, opts)?;
+ // Only the target is granted: a linked smart object's stored path is document
+ // data, so PSD export writes that layer as pixels instead of embedding the file.
+ let opts = ExportOptions { read_linked_files: false, ..opts.clone() };
+ let (bytes, warnings) = files::save_bytes(&doc, target_text, format, &opts)?;
workspace.write(target_text, &bytes)?;
warnings
}
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index 14fb82bfe..64f67f9d9 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -871,6 +871,39 @@ mod tests {
std::fs::remove_dir_all(base).unwrap();
}
+ #[test]
+ fn workspace_psd_saves_embed_no_file_a_linked_smart_object_names() {
+ use photocraft_engine::doc::{LayerContent, SmartSource};
+
+ const MARKER: &[u8] = b"PHOTOCRAFT-LINKED-0001";
+ let has_marker = |bytes: &[u8]| bytes.windows(MARKER.len()).any(|w| w == MARKER);
+ let base = std::env::temp_dir().join(format!("pc-psd-linked-embed-{}", std::process::id()));
+ let root = base.join("workspace");
+ std::fs::create_dir_all(&root).unwrap();
+ let outside = base.join("outside.txt");
+ std::fs::write(&outside, MARKER).unwrap();
+ // A document whose smart object names a file outside the roots as its source.
+ let mut session = photocraft_engine::Session::new();
+ session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
+ session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
+ let state = session.active_mut().unwrap();
+ let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") };
+ smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() };
+ std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap();
+ // A trusted export embeds the linked file, as before.
+ assert!(has_marker(&photocraft_io::export(&state.doc, "psd", &Default::default()).unwrap().bytes));
+
+ let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap());
+ h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap();
+ let saved = h.handle("doc.save", json!({"path": "out.psd"})).unwrap();
+ let warnings = saved["warnings"].to_string();
+ assert!(warnings.contains("written as pixels"), "{warnings}");
+ assert!(!has_marker(&std::fs::read(root.join("out.psd")).unwrap()), "the linked file outside the roots is not embedded");
+ // Release directory capabilities before cleanup on Windows.
+ drop(h);
+ std::fs::remove_dir_all(base).unwrap();
+ }
+
#[test]
fn trusted_local_render_keeps_full_size_behavior() {
let mut h = Headless::trusted_local();
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 406bdbe49..e07885993 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -510,6 +510,8 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> R
psd_maximize_compatibility: save.psd_maximize_compatibility,
// Linked files a PSD embeds are resolved against the document being worked on.
document_path: crate::doc_path::current(),
+ // An untrusted session's stored paths are document data: embed none of them.
+ read_linked_files: !crate::jobs::authorization_installed(),
..Default::default()
};
// No quality chosen: write the file the way it was opened (a JPEG at its own quality, a WebP
diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs
index 57846617d..4a1c30424 100644
--- a/crates/engine/src/jobs.rs
+++ b/crates/engine/src/jobs.rs
@@ -66,6 +66,11 @@ pub(crate) fn authorize_render_command(id: &str, params: &Value) -> Result<()> {
}
}
+/// Whether the work on this thread is done for an untrusted session (a gate is installed).
+pub(crate) fn authorization_installed() -> bool {
+ RENDER_AUTHORIZATION.with(std::cell::Cell::get).is_some()
+}
+
/// Identifies one background job for the session's lifetime.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, serde::Deserialize)]
pub struct JobId(pub u64);
diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rs
index 10eb9b613..67aa1fe4f 100644
--- a/crates/engine/src/variables_cmds.rs
+++ b/crates/engine/src/variables_cmds.rs
@@ -442,7 +442,8 @@ pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str,
for (set, name) in sets.iter().zip(&names) {
let mut doc = (*original).clone();
apply_to_doc(&mut doc, &vars, set)?;
- let opts = photocraft_io::ExportOptions::default();
+ // An untrusted session's PSD export embeds no file a linked smart object names.
+ let opts = photocraft_io::ExportOptions { read_linked_files: s.authorize.is_none(), ..Default::default() };
let bytes = photocraft_io::export(&doc, format, &opts).map(|r| r.bytes).map_err(|e| EngineError::Other(format!("export `{}`: {e}", set.name)))?;
write(name, &bytes)?;
written.push(name.clone());
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index a0fc3e87e..2289670db 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -232,6 +232,9 @@ pub struct ExportOptions {
pub document_path: Option<std::path::PathBuf>,
/// Reuse one cache per open document for native saves; other formats ignore it.
pub pcraft_cache: Option<PcraftExportCache>,
+ /// PSD/PSB and layered TIFF: read and embed the files linked smart objects name (see
+ /// [`PsdExportOptions::read_linked_files`]). On by default; automation turns it off.
+ pub read_linked_files: bool,
}
impl Default for ExportOptions {
@@ -246,6 +249,7 @@ impl Default for ExportOptions {
psd_maximize_compatibility: true,
document_path: None,
pcraft_cache: None,
+ read_linked_files: true,
}
}
}
@@ -526,6 +530,7 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &
force_psb: opts.force_psb || ext == "psb",
maximize_compatibility: opts.psd_maximize_compatibility,
document_path: opts.document_path.clone(),
+ read_linked_files: opts.read_linked_files,
..Default::default()
};
let (mut file, mut warnings) = with_span(ctl, 0.0, PSD_MODEL_DONE, |ctl| psd_export::document_to_psd_interruptible(doc, &o, ctl));
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index 90a5d86ce..fd07adde5 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -50,6 +50,10 @@ pub struct PsdExportOptions {
/// The path of the document's own file: linked smart objects are resolved against it
/// ([`crate::doc_path::resolve`]) before they are read and embedded.
pub document_path: Option<std::path::PathBuf>,
+ /// Read and embed the files linked smart objects name. On by default; automation turns it
+ /// off, since a stored path is document data rather than a granted file: such a layer is
+ /// then written as pixels, with a warning.
+ pub read_linked_files: bool,
}
impl Default for PsdExportOptions {
@@ -61,6 +65,7 @@ impl Default for PsdExportOptions {
merged_compression: Compression::Rle,
maximize_compatibility: true,
document_path: None,
+ read_linked_files: true,
}
}
}
@@ -71,6 +76,8 @@ struct Ex {
dpi: f32,
/// The document's own file, which linked smart objects are resolved against.
document: Option<std::path::PathBuf>,
+ /// Whether linked files may be read and embedded ([`PsdExportOptions::read_linked_files`]).
+ read_linked_files: bool,
/// Character/paragraph styles written into every type layer's engine data.
text_styles: photocraft_doc::TextStyles,
mask_fmt: PixelFormat,
@@ -977,6 +984,9 @@ impl Ex {
SmartSource::Linked { path } => {
#[cfg(not(target_arch = "wasm32"))]
{
+ if !self.read_linked_files {
+ return Err(format!("the linked file {path} is not read for this export"));
+ }
let file = crate::doc_path::resolve(path, self.document.as_deref()).map_err(|e| format!("the linked file {path} is not opened: {e}"))?;
let bytes = std::fs::read(file).map_err(|e| format!("the linked file {path} can't be read: {e}"))?;
let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string();
@@ -1049,7 +1059,7 @@ impl Ex {
let doc = photocraft_format::load_from_bytes(bytes).map_err(|e| format!("its contents can't be read: {e}"))?;
let (file, warnings) = document_to_psd_nested(
&doc,
- &PsdExportOptions { force_psb: true, document_path: self.document.clone(), ..Default::default() },
+ &PsdExportOptions { force_psb: true, document_path: self.document.clone(), read_linked_files: self.read_linked_files, ..Default::default() },
self.smart.depth + 1,
&Interrupt::NONE,
);
@@ -1595,6 +1605,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
fmt,
dpi: doc.resolution_dpi,
document: opts.document_path.clone(),
+ read_linked_files: opts.read_linked_files,
text_styles: doc.text_styles.clone(),
text_index: Default::default(),
mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false),
diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs
index 6caf33576..d6c0a845b 100644
--- a/crates/io/src/tiff_layers.rs
+++ b/crates/io/src/tiff_layers.rs
@@ -216,6 +216,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
merged_compression: Compression::Raw,
maximize_compatibility: true,
document_path: opts.document_path.clone(),
+ read_linked_files: opts.read_linked_files,
};
// TIFF has no palette, bitmap or duotone layout: the PSD model of an Indexed Color, Bitmap
// or Duotone document is made in its pixel format (RGB or Grayscale), which the PSD exporter
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 274380ba9..0b8e35870 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -369,6 +369,9 @@ pub struct ExportSettings {
pub document_path: Option<std::path::PathBuf>,
/// Native save cache owned by the open document; exports without one remain one-shot.
pub pcraft_cache: Option<photocraft_io::PcraftExportCache>,
+ /// Read and embed the files linked smart objects name ([`photocraft_io::ExportOptions::read_linked_files`]).
+ /// Off for automation saves, which are granted only their target.
+ pub read_linked_files: bool,
}
impl Default for ExportSettings {
@@ -388,6 +391,7 @@ impl Default for ExportSettings {
embed_metadata: true,
document_path: None,
pcraft_cache: None,
+ read_linked_files: true,
}
}
}
@@ -415,6 +419,7 @@ impl ExportSettings {
opts.psd_maximize_compatibility = self.psd_maximize_compatibility;
opts.document_path = self.document_path.clone();
opts.pcraft_cache = self.pcraft_cache.clone();
+ opts.read_linked_files = self.read_linked_files;
opts
}
}
@@ -2119,11 +2124,14 @@ impl PhotocraftApp {
)?
};
let reply = |path: &str, warnings: &[String]| json!({"path": path, "warnings": warnings});
+ // Only the target is granted: a linked smart object's stored path is document data, so
+ // PSD export writes that layer as pixels instead of embedding the file.
+ let settings = ExportSettings { read_linked_files: false, ..choices.apply(self.save_settings()) };
// #2017: the File › Save worker path, so the encode doesn't block the frame loop.
if self.background_jobs
&& let Some(save) = self.services.automation_save.clone()
{
- return match jobs_ui::start_save(self, target.clone(), choices.apply(self.save_settings()), false, save, true)? {
+ return match jobs_ui::start_save(self, target.clone(), settings, false, save, true)? {
Some((path, warnings)) => Ok(reply(&path, &warnings)),
None => {
let job = self.jobs.last_started;
@@ -2133,7 +2141,6 @@ impl PhotocraftApp {
}
let state = self.session.active().ok_or("no document")?;
let (doc, revision) = (state.doc.id, state.revision);
- let settings = choices.apply(self.save_settings());
let export = self.services.export.as_ref().ok_or("no exporter configured")?;
let (bytes, warnings) = export(&state.doc, &target, &settings)?;
let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?;