Skip to content

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

PSD export: embed linked files only when they are local or on the document's share

aiongg348499a5e01c
diff --git a/crates/engine/src/doc_path/tests.rs b/crates/engine/src/doc_path/tests.rs
index 6b8657911..b28fe3fb4 100644
--- a/crates/engine/src/doc_path/tests.rs
+++ b/crates/engine/src/doc_path/tests.rs
@@ -127,3 +127,21 @@ fn package_copies_only_followed_links() {
assert_eq!(links.len(), 1);
assert!(links[0].as_str().unwrap().ends_with("red.png"), "{links:?}");
}
+
+#[test]
+fn psd_saves_embed_only_followed_links() {
+ let d = dir("psd");
+ png(&d.join("red.png"), |_| [255, 0, 0]);
+ let (mut s, id) = document(&d, &d.join("red.png"));
+ relink(&mut s, id, "red.png");
+ s.execute("file.placeLinked", json!({"path": d.join("red.png").to_string_lossy()})).unwrap();
+ let other = s.active().unwrap().active_layer.unwrap();
+ relink(&mut s, other, REMOTE);
+ let warnings = |r: serde_json::Value| r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect::<Vec<_>>();
+ let saved = warnings(s.execute("file.saveACopy", json!({"path": d.join("copy.psd").to_string_lossy()})).unwrap());
+ assert!(saved.iter().any(|w| w.contains("red.png was embedded")), "{saved:?}");
+ assert!(saved.iter().any(|w| w.contains("is not opened: the path is on another computer")), "{saved:?}");
+ // Package as PSD writes the copy of the document, whose remote link stays as it was.
+ let packaged = warnings(s.execute("file.package", json!({"dir": d.join("pkg").to_string_lossy(), "format": "psd"})).unwrap());
+ assert!(packaged.iter().any(|w| w.contains("is not opened: the path is on another computer")), "{packaged:?}");
+}
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index d9eb4d10c..07ae78904 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -340,6 +340,8 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> R
tga_bits: save.tga_bits,
image_previews: save.image_previews,
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(),
..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/io/src/lib.rs b/crates/io/src/lib.rs
index e3c6365d9..3543cd359 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -188,6 +188,9 @@ pub struct ExportOptions {
/// File Compatibility (see [`PsdExportOptions::maximize_compatibility`]). On by default, as
/// Photoshop's Always.
pub psd_maximize_compatibility: bool,
+ /// The path of the document's own file, which linked smart objects that PSD/PSB and layered
+ /// TIFF embed are resolved against ([`doc_path::resolve`]).
+ pub document_path: Option<std::path::PathBuf>,
}
impl Default for ExportOptions {
@@ -200,6 +203,7 @@ impl Default for ExportOptions {
tga_bits: None,
image_previews: true,
psd_maximize_compatibility: true,
+ document_path: None,
}
}
}
@@ -412,7 +416,12 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &
return Ok(ExportResult { bytes: photocraft_format::save_to_bytes(doc.as_ref(), &previews)?, warnings: Vec::new() });
}
if ext == "psd" || ext == "psb" {
- let o = PsdExportOptions { force_psb: opts.force_psb || ext == "psb", maximize_compatibility: opts.psd_maximize_compatibility, ..Default::default() };
+ let o = PsdExportOptions {
+ force_psb: opts.force_psb || ext == "psb",
+ maximize_compatibility: opts.psd_maximize_compatibility,
+ document_path: opts.document_path.clone(),
+ ..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));
// A cancelled conversion stops early with an incomplete model: never write it.
ctl.check().map_err(|_| IoError::Cancelled)?;
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index 8ba30d83c..64a5e7073 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -41,11 +41,14 @@ pub struct PsdExportOptions {
/// readers that only show the merged image see white. A document without layer records always
/// gets the real image, since its pixels live nowhere else.
pub maximize_compatibility: bool,
+ /// 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>,
}
impl Default for PsdExportOptions {
fn default() -> Self {
- PsdExportOptions { force_psb: false, merged_matte: true, merged_compression: Compression::Rle, maximize_compatibility: true }
+ PsdExportOptions { force_psb: false, merged_matte: true, merged_compression: Compression::Rle, maximize_compatibility: true, document_path: None }
}
}
@@ -53,6 +56,8 @@ struct Ex {
fmt: PixelFormat,
/// Document resolution (for generated type-layer data).
dpi: f32,
+ /// The document's own file, which linked smart objects are resolved against.
+ document: Option<std::path::PathBuf>,
/// Character/paragraph styles written into every type layer's engine data.
text_styles: photocraft_doc::TextStyles,
mask_fmt: PixelFormat,
@@ -929,7 +934,8 @@ impl Ex {
SmartSource::Linked { path } => {
#[cfg(not(target_arch = "wasm32"))]
{
- let bytes = std::fs::read(path).map_err(|e| format!("the linked file {path} can't be read: {e}"))?;
+ 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();
self.warnings.push(format!("the linked smart object {name} was embedded (PSD export keeps no external links)"));
self.embed(sm.contents_id, &name, &bytes)
@@ -998,8 +1004,12 @@ impl Ex {
return Err(format!("smart objects nest more than {MAX_NESTING} deep"));
}
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, ..Default::default() }, self.smart.depth + 1, &Interrupt::NONE);
+ let (file, warnings) = document_to_psd_nested(
+ &doc,
+ &PsdExportOptions { force_psb: true, document_path: self.document.clone(), ..Default::default() },
+ self.smart.depth + 1,
+ &Interrupt::NONE,
+ );
let data = file.to_bytes().map_err(|e| format!("its contents can't be written: {e}"))?;
let stem = file_name.rsplit_once('.').map_or(file_name, |(a, _)| a);
self.warnings.extend(warnings.into_iter().map(|w| format!("smart object {stem}: {w}")));
@@ -1519,6 +1529,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
let mut ex = Ex {
fmt,
dpi: doc.resolution_dpi,
+ document: opts.document_path.clone(),
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 3cd8de5b4..628517b6f 100644
--- a/crates/io/src/tiff_layers.rs
+++ b/crates/io/src/tiff_layers.rs
@@ -202,8 +202,13 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
let big = doc.size.width > 30_000 || doc.size.height > 30_000;
// The PSD exporter renders the composite we need for the TIFF itself: unmatted (the TIFF
// keeps straight alpha) and uncompressed (its planes are interleaved below).
- let psd_opts =
- PsdExportOptions { force_psb: opts.force_psb || big, merged_matte: false, merged_compression: Compression::Raw, maximize_compatibility: true };
+ let psd_opts = PsdExportOptions {
+ force_psb: opts.force_psb || big,
+ merged_matte: false,
+ merged_compression: Compression::Raw,
+ maximize_compatibility: true,
+ document_path: opts.document_path.clone(),
+ };
let (file, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psd_opts, ctl));
// A cancelled conversion stops early with an incomplete model: never encode it.
ctl.check().map_err(|_| IoError::Cancelled)?;
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index bde51ff27..5004e8ccf 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -281,6 +281,9 @@ pub struct ExportSettings {
/// Embed EXIF, resolution and other non-XMP metadata when the format supports it. Export As
/// turns this off for Metadata: None; Save As leaves it on.
pub embed_metadata: bool,
+ /// The path of the document's own file, which linked smart objects that PSD/PSB embed are
+ /// resolved against ([`photocraft_io::ExportOptions::document_path`]).
+ pub document_path: Option<std::path::PathBuf>,
}
impl Default for ExportSettings {
@@ -296,6 +299,7 @@ impl Default for ExportSettings {
psd_maximize_compatibility: true,
embed_icc: true,
embed_metadata: true,
+ document_path: None,
}
}
}
@@ -319,6 +323,7 @@ impl ExportSettings {
opts.tga_bits = self.tga_bits;
opts.image_previews = self.image_previews;
opts.psd_maximize_compatibility = self.psd_maximize_compatibility;
+ opts.document_path = self.document_path.clone();
opts
}
}
@@ -1549,6 +1554,7 @@ impl PhotocraftApp {
settings.jpeg_quality = e.jpeg_quality.map(|q| q.clamp(1, 100));
settings.webp_lossless = e.webp_lossless.unwrap_or(settings.webp_lossless);
settings.webp_quality = e.webp_quality.map(|q| q.min(100));
+ settings.document_path = st.path.as_deref().map(std::path::PathBuf::from);
}
settings
}