Skip to content

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

fix(file): open .psdt templates as new untitled documents (#807)

reese48bfaa9d0d91
diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs
index 3fb95b6ee..b4372ae52 100644
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@ -14,8 +14,8 @@ type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
/// Everything File › Open reads: PhotoCraft and Photoshop documents, flat images, and Photoshop
/// brushes (.abr) and gradients (.grd), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
- "pcraft", "psd", "psb", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam", "pfm",
- "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
+ "pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",
+ "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
];
const CANVAS_ID: &str = "photocraft_canvas";
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 7644b5bd8..9818719aa 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -14,8 +14,8 @@ use std::sync::Arc;
/// Everything File › Open reads: PhotoCraft and Photoshop documents, flat images, and Photoshop
/// brushes (.abr) and gradients (.grd), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
- "pcraft", "psd", "psb", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam", "pfm",
- "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
+ "pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",
+ "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd",
];
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index b685c3d3c..e3bd8c74b 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -75,7 +75,7 @@ impl Headless {
/// Open a file and make it the active document.
pub fn open(&mut self, path: &Path) -> Result<Value, AutomationError> {
let requested = path.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?;
- let o = match &self.filesystem {
+ let mut o = match &self.filesystem {
Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into())),
Filesystem::TrustedLocal => files::open(path)?,
Filesystem::Workspace(workspace) => {
@@ -84,7 +84,14 @@ impl Headless {
files::open_bytes(name, &bytes)?
}
};
- let index = self.session.add_document(o.document, Some(requested.to_string()));
+ let path = match file_cmds::template_name(&self.session, requested) {
+ Some(untitled) => {
+ o.document.name = untitled;
+ None
+ }
+ None => Some(requested.to_string()),
+ };
+ let index = self.session.add_document(o.document, path);
let d = &self.session.documents()[index];
Ok(json!({
"index": index,
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index 30c588b51..cf745dc75 100644
--- a/crates/automation/tests/mcp.rs
+++ b/crates/automation/tests/mcp.rs
@@ -356,6 +356,13 @@ async fn save_without_path_never_flattens_over_the_opened_file() {
json_of(&call(&client, "doc_save", json!({"path": "work.pcraft"})).await);
assert_eq!(json_of(&call(&client, "doc_save", json!({})).await)["path"], "work.pcraft");
assert_eq!(std::fs::read(dir.join("seed.png")).unwrap(), png);
+
+ // A template opens untitled, without its path.
+ std::fs::write(dir.join("card.psdt"), &psd).unwrap();
+ assert_eq!(json_of(&call(&client, "doc_open", json!({"path": "card.psdt"})).await)["name"], "Untitled-1");
+ let r = call(&client, "doc_save", json!({})).await;
+ assert!(refused(&r), "{}", text(&r));
+ assert_eq!(std::fs::read(dir.join("card.psdt")).unwrap(), psd);
client.cancel().await.unwrap();
cleanup(&dir);
}
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 45f7e0f70..cbc03f948 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -135,6 +135,23 @@ pub fn saves_in_place(path: &str) -> bool {
extension(path).is_some_and(|ext| matches!(ext.as_str(), "psd" | "psb" | "pcraft"))
}
+/// Whether `path` names a document template (.psdt). A template opens as a new untitled document
+/// without its path, so a save never writes over the template.
+pub fn is_template(path: &str) -> bool {
+ extension(path).as_deref() == Some("psdt")
+}
+
+/// The first "`base`-N" that isn't `taken`.
+pub fn untitled_name(base: &str, taken: impl Fn(&str) -> bool) -> String {
+ (1..).map(|i| format!("{base}-{i}")).find(|n| !taken(n)).unwrap_or_default()
+}
+
+/// The name a document opened from `path` gets when `path` is a template: the first "Untitled-N"
+/// no open document has.
+pub fn template_name(s: &Session, path: &str) -> Option<String> {
+ is_template(path).then(|| untitled_name("Untitled", |n| s.documents().iter().any(|d| d.doc.name == n)))
+}
+
pub(crate) fn stem(path: &str) -> String {
let n = file_name(path);
match n.rfind('.') {
@@ -309,7 +326,16 @@ pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&
};
let r = photocraft_io::import(&decode_name, bytes).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?;
let mut doc = r.document;
- doc.name = file_name(name);
+ let path = match template_name(s, name) {
+ Some(untitled) => {
+ doc.name = untitled;
+ None
+ }
+ None => {
+ doc.name = file_name(name);
+ path
+ }
+ };
// Color Settings policies (preserve / convert / discard the embedded profile).
let (i, color) = s.open_document(doc, path);
// Import notes (e.g. how a camera raw was developed, or that only its preview opened).
diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs
index 4f9e863b0..8de181fbd 100644
--- a/crates/engine/src/file_cmds/tests.rs
+++ b/crates/engine/src/file_cmds/tests.rs
@@ -391,6 +391,19 @@ fn only_layered_files_save_in_place() {
assert_eq!(extension("my.dir/name"), None);
}
+#[test]
+fn templates_open_untitled_without_their_path() {
+ assert!(is_template("dir/card.PSDT") && !is_template("card.psd") && !is_template("psdt"));
+ let dir = tmp("template");
+ let path = format!("{dir}/card.psdt");
+ let mut s = session(8, 8, 8);
+ std::fs::write(&path, encode(doc(&s), "x.psd", None).unwrap().0).unwrap();
+ s.execute("file.openAs", json!({"path": path})).unwrap();
+ s.execute("file.openAs", json!({"path": path, "as": "psd"})).unwrap();
+ let opened: Vec<_> = s.documents()[1..].iter().map(|d| (d.doc.name.as_str(), d.path.as_deref())).collect();
+ assert_eq!(opened, [("Untitled-1", None), ("Untitled-2", None)]);
+}
+
/// Two inputs with one output name: the first result is kept and the second is an error, never
/// a silent overwrite listed as written (#422).
#[test]
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 56c6d9d84..1f0ba203e 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -576,13 +576,11 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
None => Err("automation read authority is not configured".into()),
};
wrap(opened.and_then(|(name, bytes)| {
+ let name = app.open_name(&name);
let warnings = app.open_automation_bytes(&name, &bytes)?;
// Brushes/gradients go to the preset libraries: no document, no Open Recent entry.
if !crate::preset_files_ui::is_preset_file(&name) {
- if let Some(state) = app.session.active_mut() {
- state.path = Some(path.to_string());
- }
- app.push_recent(path);
+ app.opened_from(path);
}
Ok(json!({"path": path, "name": name, "warnings": warnings}))
}))
@@ -952,6 +950,12 @@ mod tests {
let r = call(&mut app, &ctx, "app.save", json!({}));
assert_eq!(r["result"]["path"], "in/layered.psd", "{r}");
assert_eq!(written.borrow().last().map(String::as_str), Some("in/layered.psd"));
+ // A template opens untitled, so a save without `path` never writes over it.
+ let r = call(&mut app, &ctx, "app.open", json!({"path": "in/card.psdt"}));
+ assert_eq!(r["result"]["name"], "Untitled-1", "{r}");
+ assert_eq!(app.session.active().unwrap().path, None);
+ let r = call(&mut app, &ctx, "app.save", json!({}));
+ assert!(r["error"].as_str().unwrap().contains("pass `path`"), "{r}");
}
fn deny_ambient_file(id: &str, _: &serde_json::Value) -> photocraft_engine::Result<()> {
diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs
index 40acd925f..9fcc8437c 100644
--- a/crates/ui-egui/src/file_open.rs
+++ b/crates/ui-egui/src/file_open.rs
@@ -5,6 +5,7 @@
//! Recent. Failures are shown as errors (status bar + notice); import warnings as a notice.
use crate::{PhotocraftApp, notices};
+use photocraft_engine::file_cmds::{is_template, untitled_name};
/// A request from the operating system, delivered by the platform shell through
/// [`Services::os_events`](crate::Services::os_events).
@@ -37,11 +38,28 @@ impl PhotocraftApp {
return Ok(Vec::new());
}
let warnings = self.open_bytes(&display_name(path), bytes)?;
- if let Some(st) = self.session.active_mut() {
+ self.opened_from(path);
+ Ok(warnings)
+ }
+
+ /// Record that the active document was just opened from `path`: File › Save writes back to it
+ /// (unless it's a template) and it goes to the top of Open Recent.
+ pub(crate) fn opened_from(&mut self, path: &str) {
+ if !is_template(path)
+ && let Some(st) = self.session.active_mut()
+ {
st.path = Some(path.to_string());
}
self.push_recent(path);
- Ok(warnings)
+ }
+
+ /// The name a file called `name` opens under: its own, or the first free "Untitled-N" for a
+ /// template.
+ pub(crate) fn open_name(&self, name: &str) -> String {
+ if !is_template(name) {
+ return name.to_string();
+ }
+ untitled_name(tl!("Untitled"), |n| self.session.documents().iter().any(|d| d.doc.name == n) || self.jobs.opens.iter().any(|o| o.name == n))
}
/// Read and open the file at `path` (see [`open_file`](Self::open_file)).
diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs
index 0967e72d1..19a4fe85c 100644
--- a/crates/ui-egui/src/file_open/tests.rs
+++ b/crates/ui-egui/src/file_open/tests.rs
@@ -125,6 +125,28 @@ fn pcraft_documents_save_in_place_but_flat_files_ask() {
assert_eq!(written.borrow().len(), 1);
}
+#[test]
+fn templates_open_as_new_untitled_documents() {
+ let (mut app, written) = app_with(None, None);
+ let ctx = egui::Context::default();
+ app.open_file("/pics/card.PSDT", b"x").unwrap();
+ app.open_file("/pics/card.psdt", b"x").unwrap();
+ let names: Vec<_> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
+ assert_eq!(names, ["Untitled-1", "Untitled-2"]);
+ assert!(app.session.documents().iter().all(|d| d.path.is_none()));
+ assert_eq!(app.ui.recent_files.first().map(String::as_str), Some("/pics/card.psdt"));
+ // File › Save asks for a new name (cancelled here) rather than suggesting the template.
+ let suggested: Rc<RefCell<Vec<String>>> = Rc::default();
+ let rec = suggested.clone();
+ app.services.pick_save = Some(Box::new(move |s: &str| {
+ rec.borrow_mut().push(s.to_string());
+ None
+ }));
+ assert_eq!(menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap_err(), "cancelled");
+ assert_eq!(*suggested.borrow(), ["Untitled-2.psd"]);
+ assert!(written.borrow().is_empty());
+}
+
#[test]
fn import_warnings_reach_status_notice_and_control_response() {
let dir = std::env::temp_dir().join(format!("photocraft-open-warn-{}", std::process::id()));
diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs
index d189158fb..40af9a4dc 100644
--- a/crates/ui-egui/src/jobs_ui.rs
+++ b/crates/ui-egui/src/jobs_ui.rs
@@ -71,6 +71,7 @@ pub fn run(app: &mut PhotocraftApp, id: &str, params: Value) -> Result<Value, St
/// Open a file in the background: a tab appears at once and shows the progress; the document
/// replaces it when decoded. `path` is remembered for File › Save and Open Recent.
pub fn start_open(app: &mut PhotocraftApp, name: &str, path: Option<String>, source: OpenSource) -> Result<(), String> {
+ let name = &app.open_name(name);
match app.session.start_open(name, source).map_err(|e| e.to_string())? {
// Inline (wasm): finish now, like a background open that ended at once.
Started::Done(v) => finish_open(app, name, path.as_deref(), &v),
@@ -193,11 +194,8 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu
let warnings: Vec<String> =
v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default();
app.session.set_active(index);
- if let (Some(p), Some(st)) = (path, app.session.active_mut()) {
- st.path = Some(p.to_string());
- }
if let Some(p) = path {
- app.push_recent(p);
+ app.opened_from(p);
}
app.sync_views();
app.ui.status = format!("Opened {name}");
diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rs
index 25735cdb6..946a53829 100644
--- a/crates/ui-egui/src/jobs_ui_tests.rs
+++ b/crates/ui-egui/src/jobs_ui_tests.rs
@@ -257,3 +257,18 @@ fn files_open_in_the_background_with_a_tab_and_cancel_closes_it() {
assert_eq!(h.state().session.documents().len(), 2);
assert!(h.state().jobs.focus.is_none());
}
+
+#[test]
+fn templates_open_untitled_in_the_background() {
+ let mut h = app_harness();
+ h.state_mut().open_file("/tmp/photocraft-test/card.psdt", &psd_bytes()).unwrap();
+ assert_eq!(h.state().jobs.opens[0].name, "Untitled-1");
+ let t = Instant::now();
+ while !h.state().jobs.opens.is_empty() && t.elapsed() < Duration::from_secs(30) {
+ h.step();
+ }
+ h.run_steps(2);
+ let st = h.state().session.active().unwrap();
+ assert_eq!((st.doc.name.as_str(), st.path.as_deref()), ("Untitled-1", None));
+ assert_eq!(h.state().ui.recent_files.first().map(String::as_str), Some("/tmp/photocraft-test/card.psdt"));
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 385937ce1..c5dcb27bd 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -687,6 +687,7 @@ impl PhotocraftApp {
if let Some(r) = preset_files_ui::open(self, name, bytes) {
return r.map(|()| Vec::new());
}
+ let name = &self.open_name(name);
// Decoded on a worker: a tab with progress appears now, the document when it's ready
// (warnings are shown then).
if self.background_jobs {
@@ -736,7 +737,8 @@ impl PhotocraftApp {
fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result<Vec<String>, String> {
let import = self.services.import.as_ref().ok_or("no importer configured")?;
let (doc, warnings) = import(name, bytes)?;
- self.session.add_document(doc, Some(name.to_string()));
+ // The caller records the path it read from.
+ self.session.add_document(doc, None);
self.sync_views();
self.ui.status = format!("Opened {name}");
self.ui.status_error = false;