Skip to content

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

fix(camera-raw): preserve document identity across queued completions

ametadot16e5374bcf5c
diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs
index 47045a37c..8108647b0 100644
--- a/crates/engine/src/jobs.rs
+++ b/crates/engine/src/jobs.rs
@@ -477,7 +477,9 @@ impl Session {
/// Open a file in the background: read (for a path) and decode on a worker, with progress
/// (per layer for PSD/PSB) and cancellation, then add the document like
/// [`Session::open_document`] (Color Settings policies apply). `name` names the document.
- /// The job's result is `{document, name, warnings, color}`; on wasm it runs inline. When
+ /// The job's result is `{document, docId, name, warnings, color}`; on wasm it runs inline.
+ /// `document` is the tab index at apply time; resolve `docId` before handling a delayed
+ /// completion, since earlier handlers may have moved or closed tabs. When
/// Color Settings ask about the file's profile, the document is held back instead and the
/// result is `{held, name, warnings, color}` (`color` the question): take it with
/// [`Session::take_held_open`] once answered.
@@ -518,10 +520,12 @@ impl Session {
return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question}));
}
let (index, color) = s.open_document(r.document, None);
+ // Persisted IDs can collide: report the identity the session actually admitted.
+ let id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id;
if let Some(st) = s.active_mut() {
st.source_read_only = r.source_read_only;
}
- Ok(json!({"document": index, "name": name_a, "warnings": r.warnings, "color": color}))
+ Ok(json!({"document": index, "docId": id.0, "name": name_a, "warnings": r.warnings, "color": color}))
},
)
}
diff --git a/crates/engine/tests/open_identity.rs b/crates/engine/tests/open_identity.rs
new file mode 100644
index 000000000..2fa4ae17f
--- /dev/null
+++ b/crates/engine/tests/open_identity.rs
@@ -0,0 +1,51 @@
+//! Background imports report the admitted document's identity, not just its temporary tab index.
+
+use std::sync::Arc;
+
+use photocraft_engine::Session;
+use photocraft_engine::jobs::{OpenSource, Started};
+use serde_json::{Value, json};
+
+fn source() -> Session {
+ let mut session = Session::new();
+ session.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
+ session.execute("layer.new.layer", json!({})).unwrap();
+ session.execute("edit.fill", json!({"color": "#336699"})).unwrap();
+ session
+}
+
+fn open(session: &mut Session, name: &str, bytes: Vec<u8>) -> Value {
+ match session.start_open(name, OpenSource::Bytes(Arc::new(bytes))).unwrap() {
+ Started::Done(result) => result,
+ Started::Job(job) => session.wait_job(job).unwrap(),
+ }
+}
+
+#[test]
+fn open_identity_reports_the_live_document_after_tabs_move() {
+ let input = source();
+ let bytes = photocraft_io::export(&input.active().unwrap().doc, "synthetic.png", &Default::default()).unwrap().bytes;
+ let mut session = source();
+ let result = open(&mut session, "synthetic.png", bytes);
+ let index = result["document"].as_u64().unwrap() as usize;
+ let imported = session.documents()[index].doc.id;
+ assert_eq!(result["docId"], imported.0, "the engine result must carry the actual admitted identity: {result}");
+ session.move_document(index, 0).unwrap();
+ assert_eq!(session.documents()[0].doc.id.0, result["docId"]);
+ assert_ne!(session.documents()[index].doc.id, imported, "the old index now identifies another document");
+}
+
+#[test]
+fn open_identity_reports_the_remapped_id_when_a_native_document_is_opened_twice() {
+ let mut session = source();
+ let original = session.active().unwrap().doc.clone();
+ // A wholly synthetic in-memory native file retains its DocId. PNG and DNG allocate fresh
+ // IDs during decode, so they cannot deterministically exercise this collision.
+ let bytes = photocraft_format::PcraftWriter::new().save_zip(&original, &Default::default()).unwrap().0;
+ let result = open(&mut session, "synthetic.pcraft", bytes);
+ let index = result["document"].as_u64().unwrap() as usize;
+ let admitted = session.documents()[index].doc.id;
+ assert_ne!(admitted, original.id, "the original document still owns its persisted ID");
+ assert_eq!(result["docId"], admitted.0, "report the remapped identity, not the ID decoded from the file");
+ assert!(Arc::ptr_eq(&session.documents()[0].doc, &original));
+}
diff --git a/crates/ui-egui/src/camera_raw_identity_tests.rs b/crates/ui-egui/src/camera_raw_identity_tests.rs
new file mode 100644
index 000000000..9c6789452
--- /dev/null
+++ b/crates/ui-egui/src/camera_raw_identity_tests.rs
@@ -0,0 +1,164 @@
+//! Re-develop completion must follow the replacement document across intervening tab changes.
+
+use std::sync::Arc;
+
+use super::*;
+
+fn synthetic_raw() -> Vec<u8> {
+ use photocraft_raw::testgen::{DngSpec, mosaic, scene};
+ let (width, height) = (48, 32);
+ DngSpec::cfa(width, height, mosaic(&scene(width, height), width, [0, 1, 1, 2], 0, 30000)).build()
+}
+
+struct Control {
+ doc: Arc<photocraft_doc::Document>,
+ path: Option<String>,
+ revision: u64,
+ saved_revision: u64,
+ history: usize,
+}
+
+impl Control {
+ fn assert_untouched(&self, app: &PhotocraftApp) {
+ let state = app.session.documents().iter().find(|state| state.doc.id == self.doc.id).expect("the accepted control remains open");
+ assert!(Arc::ptr_eq(&state.doc, &self.doc), "the RAW completion must not filter another document");
+ assert_eq!(state.path, self.path);
+ assert_eq!((state.revision, state.saved_revision, state.history.past_len()), (self.revision, self.saved_revision, self.history));
+ assert!(state.is_dirty(), "the unrelated document still needs saving");
+ }
+}
+
+fn identity_app() -> (PhotocraftApp, RawOpen, Control) {
+ let mut session = photocraft_engine::Session::new();
+ session.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
+ session.execute("layer.new.layer", json!({})).unwrap();
+ session.execute("edit.fill", json!({"color": "#336699"})).unwrap();
+ session.active_mut().unwrap().path = Some("accepted-control.pcraft".into());
+ let state = session.active().unwrap();
+ let control = Control {
+ doc: state.doc.clone(),
+ path: state.path.clone(),
+ revision: state.revision,
+ saved_revision: state.saved_revision,
+ history: state.history.past_len(),
+ };
+ let bytes = Arc::new(synthetic_raw());
+ let imported = photocraft_io::import("synthetic.dng", &bytes).unwrap();
+ let (index, _) = session.open_document(imported.document, None);
+ let raw = RawOpen { document: session.documents()[index].doc.id, name: "synthetic.dng".into(), path: None, bytes: Some(bytes) };
+ let mut app = PhotocraftApp::new(session, crate::Services::default());
+ app.sync_views();
+ (app, raw, control)
+}
+
+/// Run the real DNG worker and apply its replacement, holding the UI completion until after
+/// another event changes the tab list. No sleeps, timing races or fake decoder are needed.
+fn completed_redevelop(app: &mut PhotocraftApp, raw: &RawOpen) -> (CameraRaw, Value, photocraft_doc::DocId) {
+ app.background_jobs = true;
+ let params = CameraRaw { exposure: 1.0, contrast: 20.0, ..Default::default() };
+ let started = commit_open_raw(app, &params, raw).unwrap();
+ let job = photocraft_engine::jobs::JobId(started["job"].as_u64().expect("the sensor re-develop runs as a real job"));
+ let mut result = app.session.wait_job(job).unwrap();
+ let replacement = app.session.documents()[result["document"].as_u64().unwrap() as usize].doc.id;
+ // The producer has a separate contract test. Supply the observed identity here to isolate
+ // the UI consumer's handling even when run against the old result schema.
+ result["docId"] = json!(replacement.0);
+ app.raw_redevelop = None;
+ app.background_jobs = false;
+ (params, result, replacement)
+}
+
+#[test]
+fn completion_identity_reports_the_live_replacement_after_id_collision() {
+ let (mut app, raw, control) = identity_app();
+ let mut imported = photocraft_io::import("synthetic.dng", &synthetic_raw()).unwrap();
+ // Exercise the same collision protection as a persisted native document: the result must
+ // name the admitted replacement, even when the incoming ID already belongs to a tab.
+ imported.document.id = control.doc.id;
+ let result = replace_raw_document(&mut app.session, raw.document, imported, false).unwrap();
+ let replacement = app.session.documents()[result["document"].as_u64().unwrap() as usize].doc.id;
+ assert_ne!(replacement, control.doc.id);
+ assert_eq!(result["docId"], replacement.0, "the callback needs the session's actual replacement identity");
+ control.assert_untouched(&app);
+}
+
+#[test]
+fn completion_identity_applies_remaining_settings_after_tab_reordering() {
+ let (mut app, raw, control) = identity_app();
+ let (params, result, replacement) = completed_redevelop(&mut app, &raw);
+ let index = result["document"].as_u64().unwrap() as usize;
+ app.session.move_document(index, 0).unwrap();
+ assert_eq!(app.session.documents()[index].doc.id, control.doc.id, "another completion may move this tab before the RAW callback");
+ finish_redevelop(&mut app, &params, &raw, &result).unwrap();
+ control.assert_untouched(&app);
+ let state = app.session.active().unwrap();
+ assert_eq!(state.doc.id, replacement);
+ assert!(!state.is_dirty(), "development finishes opening only the replacement");
+ assert!(state.history.past_len() > 0, "remaining Camera Raw settings were applied");
+ assert!(!app.view_docs.contains(&raw.document));
+ assert!(app.view_docs.contains(&replacement));
+}
+
+#[test]
+fn completion_identity_rejects_a_closed_replacement_without_filtering_the_active_control() {
+ let (mut app, raw, control) = identity_app();
+ let (params, result, replacement) = completed_redevelop(&mut app, &raw);
+ let index = app.session.documents().iter().position(|state| state.doc.id == replacement).unwrap();
+ app.session.close(index).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.id, control.doc.id);
+ assert!(finish_redevelop(&mut app, &params, &raw, &result).is_err(), "a closed replacement must not fall back to the active document");
+ control.assert_untouched(&app);
+ assert_eq!(app.session.documents().len(), 1);
+}
+
+#[test]
+fn completion_identity_rejects_missing_and_invalid_ids_before_any_side_effect() {
+ for identity in [None, Some(Value::Null), Some(json!("invalid")), Some(json!(-1)), Some(json!(u64::MAX)), Some(json!(1.5))] {
+ let (mut app, raw, control) = identity_app();
+ let (params, mut result, _) = completed_redevelop(&mut app, &raw);
+ result["document"] = json!(0);
+ match identity {
+ None => {
+ result.as_object_mut().unwrap().remove("docId");
+ }
+ Some(value) => result["docId"] = value,
+ }
+ app.session.set_active(0);
+ let views = app.view_docs.clone();
+ let notices = app.ui.notices.len();
+ assert!(finish_redevelop(&mut app, &params, &raw, &result).is_err(), "invalid identity was accepted: {result}");
+ control.assert_untouched(&app);
+ assert_eq!(app.session.active().unwrap().doc.id, control.doc.id);
+ assert_eq!(app.view_docs, views, "identity validation precedes view remapping");
+ assert_eq!(app.ui.notices.len(), notices, "identity validation precedes import notifications");
+ }
+}
+
+#[test]
+fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document() {
+ let (mut app, raw, control) = identity_app();
+ app.session.set_active(0);
+ assert_eq!(app.session.active().unwrap().doc.id, control.doc.id);
+ queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice)).unwrap();
+ let queued = app.pending_raw_open.as_ref().expect("the explicitly named RAW was queued");
+ assert_eq!(queued.document, raw.document);
+ assert_eq!((&queued.name, &queued.path, &queued.bytes), (&raw.name, &raw.path, &raw.bytes));
+ assert_eq!(app.session.active().unwrap().doc.id, control.doc.id, "queueing does not activate the target");
+ control.assert_untouched(&app);
+}
+
+#[test]
+fn queue_identity_rejects_a_missing_document_without_replacing_the_pending_review() {
+ let (mut app, raw, control) = identity_app();
+ queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice)).unwrap();
+ let pending = app.pending_raw_open.as_ref().unwrap().clone();
+ app.session.set_active(0);
+ let missing = photocraft_doc::DocId::fresh();
+ assert!(!app.session.documents().iter().any(|state| state.doc.id == missing));
+ assert!(queue_open_dialog(&mut app, missing, "missing.dng", Some("missing.dng"), Some(&[1, 2, 3])).is_err());
+ let queued = app.pending_raw_open.as_ref().expect("the existing review is preserved");
+ assert_eq!(queued.document, pending.document);
+ assert_eq!((&queued.name, &queued.path, &queued.bytes), (&pending.name, &pending.path, &pending.bytes));
+ assert_eq!(app.session.active().unwrap().doc.id, control.doc.id);
+ control.assert_untouched(&app);
+}
diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs
index d2f78a35c..375b52adf 100644
--- a/crates/ui-egui/src/camera_raw_ui.rs
+++ b/crates/ui-egui/src/camera_raw_ui.rs
@@ -28,6 +28,10 @@ const PROXY_SIDE: usize = 900;
const PANEL_W: f32 = 330.0;
const BANDS: [&str; 8] = ["Red", "Orange", "Yellow", "Green", "Aqua", "Blue", "Purple", "Magenta"];
+#[cfg(test)]
+#[path = "camera_raw_identity_tests.rs"]
+mod identity_tests;
+
pub struct CameraRawDialog {
pub layer: LayerId,
layer_name: String,
@@ -219,16 +223,15 @@ pub fn without_develop_note(warnings: &[String]) -> Vec<String> {
warnings.iter().filter(|w| !w.contains(photocraft_io::raw::DEVELOPED_NOTE)).cloned().collect()
}
-/// Queues the open-time dialog for the active document (shown on the next frame).
-pub fn queue_open_dialog(app: &mut PhotocraftApp, name: &str, path: Option<&str>, bytes: Option<&[u8]>) {
- if let Some(st) = app.session.active() {
- app.pending_raw_open = Some(RawOpen {
- document: st.doc.id,
- name: name.to_string(),
- path: path.map(str::to_string),
- bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())),
- });
+/// Queues the open-time dialog for the document whose import completed, independent of the
+/// active tab. A delayed completion for a closed document must not review another photograph.
+pub fn queue_open_dialog(app: &mut PhotocraftApp, document: photocraft_doc::DocId, name: &str, path: Option<&str>, bytes: Option<&[u8]>) -> Result<(), String> {
+ if document_index(app, document).is_none() {
+ return Err("the imported raw document is missing".into());
}
+ app.pending_raw_open =
+ Some(RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())) });
+ Ok(())
}
/// Opens the queued open-time dialog on its document's (only) layer.
@@ -354,7 +357,8 @@ fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen) -
}
/// Swap the default-developed document `doc_id` for the re-developed one, at the same tab
-/// position and with the same path. Returns `{document, previous, warnings, wb}`.
+/// position and with the same path. Returns `{document, docId, previous, warnings, wb}`:
+/// `document` is the tab index at apply time, `docId` is the replacement's stable identity.
fn replace_raw_document(
s: &mut photocraft_engine::Session,
doc_id: photocraft_doc::DocId,
@@ -366,22 +370,24 @@ fn replace_raw_document(
let path = s.documents().get(index).and_then(|st| st.path.clone());
s.close(index);
let (opened, _) = s.open_document(r.document, path);
+ let replacement = s.documents().get(opened).ok_or(photocraft_engine::EngineError::NoDocument)?.doc.id;
let index = match s.execute("document.move", json!({"document": opened, "to": index})) {
Ok(moved) => moved.get("document").and_then(Value::as_u64).map_or(opened, |i| i as usize),
Err(_) => opened,
};
s.set_active(index);
- Ok(json!({"document": index, "previous": doc_id.0, "warnings": r.warnings, "wb": wb}))
+ Ok(json!({"document": index, "docId": replacement.0, "previous": doc_id.0, "warnings": r.warnings, "wb": wb}))
}
/// After the re-develop: keep the old document's view (zoom, scroll) on the new one, report
/// the import's notes, then apply the remaining settings.
fn finish_redevelop(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen, v: &Value) -> Result<Value, String> {
- let index = v.get("document").and_then(Value::as_u64).ok_or("the re-develop returned no document")? as usize;
- if let Some(new_id) = app.session.documents().get(index).map(|st| st.doc.id) {
- for id in app.view_docs.iter_mut().filter(|id| **id == raw.document) {
- *id = new_id;
- }
+ // A preceding completion (for example Save and Close) may have shifted the tab indices.
+ // Validate identity before remapping views, filtering or marking any document unmodified.
+ let replacement = v.get("docId").and_then(Value::as_u64).map(photocraft_doc::DocId).ok_or("the re-develop returned no document identity")?;
+ let index = document_index(app, replacement).ok_or("the re-developed document was closed")?;
+ for id in app.view_docs.iter_mut().filter(|id| **id == raw.document) {
+ *id = replacement;
}
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();
diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs
index 00db3ef96..108c7eeb4 100644
--- a/crates/ui-egui/src/file_open/tests.rs
+++ b/crates/ui-egui/src/file_open/tests.rs
@@ -858,7 +858,8 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() {
let i = app.jobs.opens.iter().position(|o| o.order.is_some_and(|x| x.seq == seq)).unwrap();
let tab = app.jobs.opens.remove(i);
let index = app.session.add_document(Document::new(&tab.name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None);
- jobs_ui::finish_open_tab(&mut app, &tab, &json!({"document": index})).unwrap();
+ let id = app.session.documents()[index].doc.id;
+ jobs_ui::finish_open_tab(&mut app, &tab, &json!({"document": index, "docId": id.0})).unwrap();
}
assert_eq!(doc_names(&app), ["existing.psd", "f0.psd", "f1.psd", "f2.psd", "f3.psd"]);
assert_eq!(app.session.active().map(|d| d.doc.name.as_str()), Some("f2.psd"), "the one that just opened is active");
@@ -867,10 +868,12 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() {
// A tab with a slot (dropped on the tabs) keeps it; one from a forgotten set goes to the end.
let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, slot: Some(0), order: None };
let index = app.session.add_document(Document::new("dropped.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None);
- jobs_ui::finish_open_tab(&mut app, &dropped, &json!({"document": index})).unwrap();
+ let id = app.session.documents()[index].doc.id;
+ jobs_ui::finish_open_tab(&mut app, &dropped, &json!({"document": index, "docId": id.0})).unwrap();
let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) };
let index = app.session.add_document(Document::new("late.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None);
- jobs_ui::finish_open_tab(&mut app, &late, &json!({"document": index})).unwrap();
+ let id = app.session.documents()[index].doc.id;
+ jobs_ui::finish_open_tab(&mut app, &late, &json!({"document": index, "docId": id.0})).unwrap();
assert_eq!(doc_names(&app), ["dropped.psd", "existing.psd", "f0.psd", "f1.psd", "f2.psd", "f3.psd", "late.psd"]);
}
diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs
index 29da41d48..db7f4f1a8 100644
--- a/crates/ui-egui/src/jobs_ui.rs
+++ b/crates/ui-egui/src/jobs_ui.rs
@@ -525,7 +525,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) {
}
/// What [`crate::PhotocraftApp::open_bytes`] does after decoding, for a background open's result
-/// (`{document, warnings, color}`).
+/// (`{document, docId, warnings, color}` or `{held, …}`).
fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option<usize>) -> Result<(), String> {
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();
@@ -546,8 +546,11 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu
crate::open_prompt::arrive(app, held(doc, read_only, v.get("color").cloned(), false));
return Ok(());
}
- let mut index = v.get("document").and_then(Value::as_u64).ok_or("the open job returned no document")? as usize;
- // An earlier file is waiting on its prompt: this one opens after it, in order.
+ // poll_jobs applies all ready jobs before the shell handles their events. An earlier
+ // handler may have moved or closed tabs, so the apply-time index is no longer authority.
+ let document = v.get("docId").and_then(Value::as_u64).map(DocId).ok_or("the open job returned no document identity")?;
+ let index = app.session.documents().iter().position(|st| st.doc.id == document).ok_or("the open job's document is missing")?;
+ // An earlier file is waiting on its prompt: this document waits after it, in order.
if crate::open_prompt::waiting(app)
&& let Some(st) = app.session.close(index)
{
@@ -556,20 +559,25 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu
crate::open_prompt::arrive(app, held(doc, read_only, None, true));
return Ok(());
}
- if let Some(slot) = slot
- && let Ok(moved) = app.run("document.move", json!({"document": index, "to": slot}))
- {
- index = moved.get("document").and_then(Value::as_u64).map_or(index, |i| i as usize);
+ if let Some(slot) = slot {
+ let _ = app.run("document.move", json!({"document": index, "to": slot}));
}
- app.session.set_active(index);
- after_open(app, name, path, &warnings, None);
- Ok(())
+ after_open(app, document, name, path, &warnings, None)
}
-/// What every open does once its document is the active one: remember where it came from, say
+/// What every open does for its admitted document: remember where it came from, say
/// so, show the import warnings (a raw opens in Camera Raw first, developed from `path` or
/// `bytes`) and fire the "Open Document" script events.
-pub(crate) fn after_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, warnings: &[String], bytes: Option<&[u8]>) {
+pub(crate) fn after_open(
+ app: &mut PhotocraftApp,
+ document: DocId,
+ name: &str,
+ path: Option<&str>,
+ warnings: &[String],
+ bytes: Option<&[u8]>,
+) -> Result<(), String> {
+ let index = app.session.documents().iter().position(|st| st.doc.id == document).ok_or("the opened document is missing")?;
+ app.session.set_active(index);
if let Some(p) = path {
app.opened_from(p);
}
@@ -582,7 +590,7 @@ pub(crate) fn after_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>
app.ui.status_error = false;
// A raw opens in Camera Raw first; the dialog says how it was developed.
if crate::camera_raw_ui::wants_open_dialog(app, warnings) {
- crate::camera_raw_ui::queue_open_dialog(app, name, path, bytes);
+ crate::camera_raw_ui::queue_open_dialog(app, document, name, path, bytes)?;
notices::io_warnings(app, &opened, &crate::camera_raw_ui::without_develop_note(warnings));
} else {
notices::io_warnings(app, &opened, warnings);
@@ -590,6 +598,7 @@ pub(crate) fn after_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>
// Script events bound to "Open Document".
photocraft_engine::automate_cmds::document_opened(&mut app.session);
app.sync_views();
+ Ok(())
}
// ------------------------------------------------------------------------------------- drawing
diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rs
index f2b7d0fbc..7fcd7674e 100644
--- a/crates/ui-egui/src/jobs_ui_tests.rs
+++ b/crates/ui-egui/src/jobs_ui_tests.rs
@@ -778,7 +778,161 @@ fn background_open_warns_about_missing_fonts() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
// What the open job leaves behind: the decoded document in the session, then its result.
let (index, _) = app.session.open_document(doc, None);
- super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "warnings": []}), None).unwrap();
+ let id = app.session.documents()[index].doc.id;
+ super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None).unwrap();
let want = vec!["font 'NoSuchFamily4559' is not installed; text may render using a fallback face".to_string()];
assert!(app.ui.notices.last().is_some_and(|n| n.title.contains("poster.psd") && n.lines == want), "{:?}", app.ui.notices);
}
+
+fn identity_app() -> PhotocraftApp {
+ let mut session = photocraft_engine::Session::new();
+ session.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
+ session.execute("layer.new.layer", json!({})).unwrap();
+ session.execute("edit.fill", json!({"color": "#336699"})).unwrap();
+ session.active_mut().unwrap().path = Some("accepted-control.pcraft".into());
+ assert!(session.active().unwrap().is_dirty());
+ PhotocraftApp::new(session, crate::Services::default())
+}
+
+fn identity_png(profile: Option<photocraft_cms::Builtin>) -> Vec<u8> {
+ let app = identity_app();
+ let mut doc = (*app.session.active().unwrap().doc).clone();
+ doc.icc_profile = profile.map(|profile| profile.profile().to_bytes());
+ photocraft_io::export(&doc, "synthetic.png", &Default::default()).unwrap().bytes
+}
+
+/// Complete the real decoder/apply path without delivering its result to the UI yet. This is
+/// the same boundary as a poll that applies all ready jobs before handling their UI events.
+fn completed_identity_open(app: &mut PhotocraftApp, name: &str, bytes: Vec<u8>) -> Value {
+ match app.session.start_open(name, photocraft_engine::jobs::OpenSource::Bytes(Arc::new(bytes))).unwrap() {
+ Started::Done(result) => result,
+ Started::Job(job) => app.session.wait_job(job).unwrap(),
+ }
+}
+
+struct IdentityControl {
+ doc: Arc<photocraft_doc::Document>,
+ path: Option<String>,
+ revision: u64,
+ saved_revision: u64,
+ history: usize,
+ redo: bool,
+}
+
+impl IdentityControl {
+ fn capture(app: &PhotocraftApp) -> Self {
+ let state = app.session.active().unwrap();
+ Self {
+ doc: state.doc.clone(),
+ path: state.path.clone(),
+ revision: state.revision,
+ saved_revision: state.saved_revision,
+ history: state.history.past_len(),
+ redo: state.history.can_redo(),
+ }
+ }
+
+ fn assert_untouched(&self, app: &PhotocraftApp) {
+ let state = app.session.documents().iter().find(|state| state.doc.id == self.doc.id).expect("the accepted control remains open");
+ assert!(Arc::ptr_eq(&state.doc, &self.doc), "the accepted control's pixels and document data must not change");
+ assert_eq!(state.path, self.path, "an import must not rebind another document's save path");
+ assert_eq!(
+ (state.revision, state.saved_revision, state.history.past_len(), state.history.can_redo()),
+ (self.revision, self.saved_revision, self.history, self.redo)
+ );
+ assert!(state.is_dirty(), "the unrelated document must still need saving");
+ }
+}
+
+/// Exercise the consumer separately from the engine result-schema regression: the identity is
+/// observed from the real imported document, then supplied even on the old producer.
+fn identified_result(app: &PhotocraftApp, mut result: Value) -> (Value, photocraft_doc::DocId) {
+ let id = app.session.documents()[result["document"].as_u64().unwrap() as usize].doc.id;
+ result["docId"] = json!(id.0);
+ (result, id)
+}
+
+#[test]
+fn open_identity_survives_tab_reordering() {
+ let mut app = identity_app();
+ let control = IdentityControl::capture(&app);
+ let result = completed_identity_open(&mut app, "imported.png", identity_png(None));
+ let (result, imported) = identified_result(&app, result);
+ let old_index = result["document"].as_u64().unwrap() as usize;
+ app.session.move_document(old_index, 0).unwrap();
+ assert_eq!(app.session.documents()[old_index].doc.id, control.doc.id);
+ super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None).unwrap();
+ control.assert_untouched(&app);
+ assert_eq!(app.session.active().unwrap().doc.id, imported);
+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some("imported.png"));
+}
+
+#[test]
+fn open_identity_survives_an_earlier_tab_closing() {
+ let mut app = identity_app();
+ let control = IdentityControl::capture(&app);
+ app.session.execute("file.new", json!({"width": 2, "height": 2})).unwrap();
+ let result = completed_identity_open(&mut app, "imported.png", identity_png(None));
+ let (result, imported) = identified_result(&app, result);
+ app.session.close(1).unwrap();
+ app.session.set_active(0);
+ super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0)).unwrap();
+ control.assert_untouched(&app);
+ assert_eq!(app.session.active().unwrap().doc.id, imported);
+ assert_eq!(app.session.documents()[0].doc.id, imported, "the requested destination slot applies to the correct document");
+}
+
+#[test]
+fn open_identity_rejects_closed_missing_and_invalid_identities() {
+ for identity in [None, Some(Value::Null), Some(json!("not-an-id")), Some(json!(-1)), Some(json!(u64::MAX)), Some(json!(1.5))] {
+ let mut app = identity_app();
+ let control = IdentityControl::capture(&app);
+ let result = completed_identity_open(&mut app, "closed.png", identity_png(None));
+ let (mut result, imported) = identified_result(&app, result);
+ app.session.close(result["document"].as_u64().unwrap() as usize).unwrap();
+ // A reused/stale index must never become permission to finish another document.
+ result["document"] = json!(0);
+ match identity {
+ None => {
+ result.as_object_mut().unwrap().remove("docId");
+ }
+ Some(value) => result["docId"] = value,
+ }
+ assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0)).is_err(), "invalid identity was accepted: {result}");
+ control.assert_untouched(&app);
+ assert_eq!(app.session.active().unwrap().doc.id, control.doc.id);
+ assert_eq!(app.session.documents().len(), 1);
+ result["docId"] = json!(imported.0);
+ assert!(
+ super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None).is_err(),
+ "a closed identity must not fall back to the old tab index"
+ );
+ control.assert_untouched(&app);
+ }
+}
+
+#[test]
+fn open_identity_keeps_same_poll_results_in_the_profile_queue() {
+ let mut app = identity_app();
+ let control = IdentityControl::capture(&app);
+ app.session.execute("edit.colorSettings", json!({"askOnMismatch": true, "askOnMissing": false, "policyRgb": "preserve"})).unwrap();
+ let mismatched = identity_png(photocraft_cms::Builtin::from_id("adobe-rgb-compat"));
+ let prompt = completed_identity_open(&mut app, "profile.png", mismatched);
+ assert!(prompt["held"].as_u64().is_some());
+ let first = completed_identity_open(&mut app, "first.png", identity_png(None));
+ let (first, first_id) = identified_result(&app, first);
+ let second = completed_identity_open(&mut app, "second.png", identity_png(None));
+ let (second, second_id) = identified_result(&app, second);
+ // All engine applies have finished. Handling the first ordinary result removes its tab,
+ // shifting the second result before its UI callback runs.
+ super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None).unwrap();
+ super::finish_open(&mut app, "first.png", Some("first.png"), &first, None).unwrap();
+ super::finish_open(&mut app, "second.png", Some("second.png"), &second, None).unwrap();
+ assert_eq!(app.held_opens.iter().map(|held| held.name.as_str()).collect::<Vec<_>>(), ["profile.png", "first.png", "second.png"]);
+ assert_eq!(app.held_opens.iter().skip(1).map(|held| held.doc.id).collect::<Vec<_>>(), [first_id, second_id]);
+ assert_eq!(app.session.documents().len(), 1, "both completed imports wait behind the profile prompt");
+ control.assert_untouched(&app);
+ assert_eq!(crate::open_prompt::answer(&mut app, None).unwrap()["cancelled"], 3);
+ assert!(app.held_opens.is_empty());
+ control.assert_untouched(&app);
+}
diff --git a/crates/ui-egui/src/open_prompt.rs b/crates/ui-egui/src/open_prompt.rs
index a4d93ca05..e2b160306 100644
--- a/crates/ui-egui/src/open_prompt.rs
+++ b/crates/ui-egui/src/open_prompt.rs
@@ -169,6 +169,8 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Val
} else {
app.session.open_document(doc, None).0
};
+ // add_document may remap a persisted ID already owned by another open document.
+ let document = app.session.documents().get(index).map(|st| st.doc.id).ok_or("the opened document is missing")?;
if let Some(st) = app.session.active_mut() {
st.source_read_only = read_only;
}
@@ -181,6 +183,6 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Val
None => index,
};
app.session.set_active(index);
- crate::jobs_ui::after_open(app, &name, path.as_deref(), &warnings, bytes.as_deref().map(Vec::as_slice));
+ crate::jobs_ui::after_open(app, document, &name, path.as_deref(), &warnings, bytes.as_deref().map(Vec::as_slice))?;
Ok(json!({"document": index, "action": action}))
}