Open as Smart Object: import on a worker and complete through File > Open's colour policy and prompts (#11678)

The command is a job (inline under execute, a worker under start) that returns File > Open's result shape; the UI tracks it as an OpenTab so finish_open gives it the profile prompt (held, admitted with the smart object label) and after_open gives a raw the Camera Raw open dialog and the import warnings. Import options and the Color Settings policy match File > Open. The paths form is removed: the UI calls the command once per file.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Model-Effort: Opus 5.5 drove; Fable 5.1 briefed; Sonnet 5.5 wrote at medium
This commit is contained in:
Trevor BrownandClaude Sonnet 5.5 committed 2026-11-07 20:38:18 -05:00
1 parent b29fdc5a29
commit 2341642056
11 files changed
+196 -56

No files matched your search

+1 -1
View File
@@ -293,7 +293,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open as Smart Object…",
&["File"],
None,
r##"{"path":str (or "paths":[str], one document each)} (opens the file as a new untitled document named "<file name without its last extension>-N" with the file's size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer named after the file) → {document, name, layer} ({documents:[…]} for paths)"##,
r##"{"path":str} (opens the file as a new untitled document named "<file name without its last extension>-N" with the file's size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer named after the file) → {document, docId, name, layer, warnings, color} (or {held, name, warnings, color, smartObject} while the profile prompt waits)"##,
native,
open_as_smart_object
),
+1 -1
View File
@@ -74,7 +74,7 @@ fn import_result(name: &str, bytes: &[u8]) -> Result<photocraft_io::ImportResult
/// The one import path every caller shares: allocation checkpoint, native `.pcraft` and format
/// dispatch through `photocraft_io::import_with_options`, typed memory refusals, and the
/// preview-only refusal wherever the import came from.
fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
pub(super) fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
crate::allocation::checkpoint("importing document")?;
let r = photocraft_io::import_with_options(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?;
// Auxiliary imports return only a document and cannot surface the preview's fidelity warning.
@@ -5,9 +5,9 @@
//! size and position `0, 0`) and put into the document before it is admitted, so the opening
//! snapshot already shows it.
use super::open::import_opened;
use super::open::import_result_with;
use super::paths::{file_name, read_file, stem, untitled_name};
use super::{Affine, Arc, Document, EngineError, Layer, LayerContent, Result, Session, SmartObject, SmartSource, Value, flattened_checked, json, str_param};
use super::{Affine, Arc, Document, Layer, LayerContent, Result, Session, SmartObject, SmartSource, Value, flattened_checked, json, str_param};
use crate::layer_place::Place;
const CMD: &str = "file.openAsSmartObject";
@@ -15,42 +15,40 @@ const CMD: &str = "file.openAsSmartObject";
/// The history step's name.
const LABEL: &str = "Open As Smart Object";
fn bad(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
}
/// The files to open: `paths` (several selected files) or `path` (one); whether it was one.
fn paths_param(p: &Value) -> Result<(Vec<String>, bool)> {
match p.get("paths") {
None | Some(Value::Null) => Ok((vec![str_param(p, "path", CMD)?.to_string()], true)),
Some(Value::Array(list)) if p.get("path").is_none_or(Value::is_null) => {
let paths: Option<Vec<String>> = list.iter().map(|v| v.as_str().filter(|v| !v.is_empty()).map(str::to_string)).collect();
match paths {
Some(paths) if !paths.is_empty() => Ok((paths, false)),
_ => Err(bad("\"paths\" must be a non-empty list of file paths")),
}
}
Some(Value::Array(_)) => Err(bad("give \"path\" or \"paths\", not both")),
Some(_) => Err(bad("\"paths\" must be a list of file paths")),
}
}
/// Opens each file as its own document, in order. A file that cannot be read stops the command
/// with an error; the documents opened before it stay open.
/// Opens the file as a document holding one embedded smart object. The read, decode and flatten
/// run on the job's worker (inline under `execute`); the document is built, given File › Open's
/// colour policy and admitted, or held for its profile prompt, when the job is applied. The reply
/// has the shape of File › Open's job: `{document, docId, name, layer, warnings, color}`, or
/// `{held, name, warnings, color, smartObject}` while the profile prompt waits.
pub(super) fn open_as_smart_object(s: &mut Session, p: &Value) -> Result<Value> {
let (paths, single) = paths_param(p)?;
let mut opened = Vec::new();
for path in &paths {
opened.push(open_one(s, path)?);
}
Ok(if single { opened.swap_remove(0) } else { json!({"documents": opened}) })
let path = str_param(p, "path", CMD)?.to_string();
let name = file_name(&path);
let opts = crate::jobs::import_options(s.prefs());
crate::jobs::run(
s,
&format!("Opening {name}"),
false,
move |ctx| {
ctx.progress(0.0, "Reading");
let bytes = read_file(&path)?;
ctx.check()?;
ctx.progress(0.05, "Decoding");
let r = import_result_with(&name, &bytes, &opts)?;
ctx.check()?;
ctx.progress(0.9, "Flattening");
// The file as one image: the smart object's rendered contents.
let pixels = flattened_checked(&r.document, r.document.pixel_format(), CMD)?;
Ok((path, name, Arc::new(bytes), r, pixels))
},
|s, (path, name, bytes, r, pixels)| apply(s, &path, &name, bytes, r, pixels),
)
}
fn open_one(s: &mut Session, path: &str) -> Result<Value> {
let bytes = read_file(path)?;
let src = import_opened(s, path, &bytes)?;
// The file as one image: the smart object's rendered contents.
let pixels = flattened_checked(&src, src.pixel_format(), CMD)?;
fn apply(s: &mut Session, path: &str, file: &str, bytes: Arc<Vec<u8>>, r: photocraft_io::ImportResult, pixels: photocraft_raster::Surface) -> Result<Value> {
let warnings = r.warnings;
let mut src = r.document;
super::tag_exr_colorspace(s, file, &mut src);
super::raw_defaults(s, &warnings, &mut src);
let layer_name = stem(path);
// "<name>-1", the next free number while a document with that name is open.
let name = untitled_name(&layer_name, |n| s.documents().iter().any(|d| d.doc.name == n));
@@ -62,13 +60,24 @@ fn open_one(s: &mut Session, path: &str) -> Result<Value> {
doc.duotone = src.duotone.clone();
// Embedded (not linked): the original file name keeps its extension, so Edit Contents opens it.
let source = SmartSource::Embedded { file_name: file_name(path), bytes: Arc::new(bytes) };
let source = SmartSource::Embedded { file_name: file.to_string(), bytes };
let so = SmartObject::new(source, Affine { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] }, Some(pixels));
let layer = Layer::new(layer_name, LayerContent::Smart(so));
let layer_id = layer.id;
crate::layer_place::insert_new(&mut doc, None, layer, Place::AutoEditable);
// File › Open's completion: a raw has no embedded profile to ask about; otherwise the profile
// prompt holds the document, and without a question the Color Settings policy is applied.
let raw = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE));
let question = s.color.open_question(&doc).filter(|_| !raw);
if question.is_some() {
let held = s.hold_open(doc, false);
return Ok(json!({"held": held, "name": name, "warnings": warnings, "color": question, "smartObject": true}));
}
let color = s.color.open_policy(&mut doc, s.prefs().file_handling.ignore_exif_profile_tag);
let index = admit_as_smart_object(s, doc);
Ok(json!({"document": index, "name": name, "layer": layer_id.0}))
let id = s.documents().get(index).map(|st| st.doc.id.0);
Ok(json!({"document": index, "docId": id, "name": name, "layer": layer_id.0, "warnings": warnings, "color": color}))
}
/// Admits a document built by Open as Smart Object (one smart object layer) as an untitled
@@ -101,6 +101,8 @@ fn a_16_bit_psd_keeps_size_resolution_mode_depth_and_profile() {
let dir = tmp("psd");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let mut s = Session::new();
// The files were measured in the working spaces, where nothing asks; Preserve keeps Display P3.
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let file = imported(&path);
assert_eq!(file.resolution_dpi, 300.0);
@@ -175,8 +177,9 @@ fn several_files_open_one_document_each() {
let a = write_png(&dir, "a_test.png", 8, 8);
let b = write_psd16(&dir, "d_other.psd", 12, 10);
let mut s = Session::new();
let r = s.execute("file.openAsSmartObject", json!({"paths": [a, b]})).unwrap();
assert_eq!(r["documents"].as_array().map(Vec::len), Some(2), "{r}");
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": a})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": b})).unwrap();
assert_eq!(names(&s), ["a_test-1", "d_other-1"]);
for st in s.documents() {
assert_eq!(st.doc.layers.len(), 1);
@@ -202,9 +205,76 @@ fn a_missing_or_unreadable_file_is_an_error_not_a_crash() {
#[test]
fn bad_params_are_errors() {
let mut s = Session::new();
for params in [json!({}), json!({"path": 7}), json!({"path": null}), json!({"paths": "a.png"}), json!({"paths": []}), json!({"paths": [1]})] {
for params in [json!({}), json!({"path": 7}), json!({"path": null})] {
let r = s.execute("file.openAsSmartObject", params.clone());
assert!(r.is_err(), "{params}: {r:?}");
}
assert!(s.documents().is_empty());
}
fn job(r: crate::jobs::Started) -> crate::jobs::JobId {
match r {
crate::jobs::Started::Job(id) => id,
crate::jobs::Started::Done(v) => panic!("expected a background job, ran inline: {v}"),
}
}
/// Poll until job `id` ends (or 60 s pass); returns its event.
fn wait_event(s: &mut Session, id: crate::jobs::JobId) -> crate::jobs::JobEvent {
let t = std::time::Instant::now();
loop {
if let Some(e) = s.poll_jobs().into_iter().find(|e| e.id == id) {
return e;
}
assert!(t.elapsed() < std::time::Duration::from_secs(60), "job {id:?} did not finish");
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
#[test]
fn the_import_runs_as_a_job_when_started() {
let dir = tmp("job");
let path = write_png(&dir, "a_test.png", 32, 24);
let mut s = Session::new();
let id = job(s.start("file.openAsSmartObject", json!({"path": path})).unwrap());
assert!(s.documents().is_empty(), "nothing is admitted before the job is applied");
let e = wait_event(&mut s, id);
let crate::jobs::JobOutcome::Done(v) = &e.outcome else { panic!("{e:?}") };
assert!(v["docId"].is_u64(), "{v}");
assert_eq!(v["name"], "a_test-1", "{v}");
assert_eq!(s.documents().len(), 1);
embedded(&s);
}
#[test]
fn the_colour_policy_matches_file_open() {
let dir = tmp("policy");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let settings = json!({"askOnMismatch": false, "policyRgb": "convert"});
let mut open = Session::new();
open.execute("edit.colorSettings", settings.clone()).unwrap();
open.execute("file.openAs", json!({"path": path})).unwrap();
let mut so = Session::new();
so.execute("edit.colorSettings", settings).unwrap();
so.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let (a, b) = (active(&open), active(&so));
assert_eq!(a.icc_profile, b.icc_profile, "Convert is applied as File > Open applies it");
assert_eq!((a.mode, a.depth, a.size), (b.mode, b.depth, b.size));
assert_eq!(a.resolution_dpi, b.resolution_dpi);
}
#[test]
fn ask_when_opening_holds_the_document_like_file_open() {
let dir = tmp("ask");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let mut s = Session::new();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(r["color"]["ask"], true, "{r}");
assert_eq!(r["smartObject"], true, "{r}");
assert!(r["held"].is_u64(), "{r}");
assert!(s.documents().is_empty(), "held for the profile prompt, not admitted");
let (doc, _) = s.take_held_open(r["held"].as_u64().unwrap()).unwrap();
assert_eq!(doc.name, "c.layered-1");
assert_eq!(doc.layers.len(), 1);
assert!(matches!(doc.layers[0].content, LayerContent::Smart(_)));
}
+1
View File
@@ -137,6 +137,7 @@ impl PhotocraftApp {
order,
question,
policy_applied: false,
smart_object: false,
},
);
Ok(warnings)
+5 -2
View File
@@ -43,6 +43,9 @@ pub struct Held {
/// The Color Settings policy was already applied (a background open added it before it had
/// to wait); otherwise opening applies it.
pub policy_applied: bool,
/// Held by Open as Smart Object: the document holds the smart object layer already, and is
/// admitted by [`photocraft_engine::file_cmds::admit_as_smart_object`].
pub smart_object: bool,
}
/// Dialog field for the high-memory confirmation prompt.
@@ -323,7 +326,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Val
if held.damage_pending {
return Err("damaged PSD cannot be opened before confirmation".into());
}
let Held { mut doc, read_only, damage_pending: _, name, path, warnings, bytes, slot, order, question, policy_applied } = held;
let Held { mut doc, read_only, damage_pending: _, name, path, warnings, bytes, slot, order, question, policy_applied, smart_object } = held;
let index = if question.is_some() || policy_applied {
if let Some(action) = action
&& let Err(e) = app.session.color.resolve_open(&mut doc, action)
@@ -331,7 +334,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Val
app.open_failed(&name, &e.to_string());
return Err(e.to_string());
}
app.session.add_document(doc, None)
if smart_object { photocraft_engine::file_cmds::admit_as_smart_object(&mut app.session, doc) } else { app.session.add_document(doc, None) }
} else {
app.session.open_document(doc, None).0
};
+9 -3
View File
@@ -263,13 +263,19 @@ impl PhotocraftApp {
pub fn open_dialog_as_smart_object(&mut self) -> Result<Value, String> {
let initial_dir = last_used_dir(&self.ui.recent_files);
self.ask_file(FileDialogRequest::Open { multiple: true, initial_dir, extensions: None }, |app, answer| {
let FileDialogAnswer::Paths(mut paths) = answer else { return Err(UNEXPECTED.into()) };
let FileDialogAnswer::Paths(paths) = answer else { return Err(UNEXPECTED.into()) };
// Each file is a tracked open job like File › Open's, in name order. No `show_if_open`:
// the file opens as another document even when it is already open.
let mut paths: Vec<String> = paths.iter().map(|p| crate::file_open::absolute(p)).collect();
paths.sort_by(|a, b| crate::file_open::natural_cmp(a, b));
for path in &paths {
if let Err(e) = crate::jobs_ui::run(app, "file.openAsSmartObject", json!({"path": path})) {
let batch = crate::jobs_ui::begin_batch(app);
for (seq, path) in paths.iter().enumerate() {
let order = crate::jobs_ui::OpenOrder { batch, seq };
if let Err(e) = crate::jobs_ui::start_open_as_smart_object(app, path, Some(order)) {
app.open_failed(&crate::file_open::display_name(path), &e);
}
}
crate::jobs_ui::end_batch(app);
app.sync_views();
Ok(Value::Null)
})
+2 -2
View File
@@ -594,12 +594,12 @@ fn digit_run(it: &mut std::iter::Peekable<std::str::Chars>) -> String {
}
#[cfg(not(target_arch = "wasm32"))]
fn absolute(p: &str) -> String {
pub(crate) fn absolute(p: &str) -> String {
std::path::absolute(p).map(|a| a.to_string_lossy().to_string()).unwrap_or_else(|_| p.to_string())
}
#[cfg(target_arch = "wasm32")]
fn absolute(p: &str) -> String {
pub(crate) fn absolute(p: &str) -> String {
p.to_string()
}
+23 -1
View File
@@ -1709,6 +1709,28 @@ fn open_as_smart_object_dialog_opens_one_document_per_selected_file() {
assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::<Vec<_>>(), ["one-1", "two-1"]);
assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1));
assert!(app.ui.status_error, "the unreadable file is reported");
assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported");
let _ = std::fs::remove_dir_all(&dir);
}
/// File > Open as Smart Object... runs each file as a tracked background job like File > Open
/// does: a tab per file, the documents landing in name order, untitled, failures reported.
#[test]
fn open_as_smart_object_opens_in_the_background_in_name_order() {
let ctx = egui::Context::default();
let (dir, paths) = files("open-as-so-bg", &["two.png", "one.png", "bad.png"], &png_bytes(8, 6));
std::fs::write(&paths[2], b"not an image").unwrap();
let (mut app, _) = app_with(vec![Some(FileDialogAnswer::Paths(paths.clone()))]);
app.background_jobs = true;
menus::invoke(&mut app, &ctx, "file.openAsSmartObject", json!({})).unwrap();
answer(&mut app);
assert_eq!(app.jobs.opens.len(), 3, "a tab for each file while it opens");
assert!(app.session.documents().is_empty(), "nothing is on the UI thread's critical path");
tick_until(&mut app, &ctx, |app| app.jobs.opens.is_empty());
assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::<Vec<_>>(), ["one-1", "two-1"]);
assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1));
assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported");
let _ = std::fs::remove_dir_all(&dir);
}
+33 -6
View File
@@ -286,11 +286,37 @@ pub fn start_open(
// once. A preflight keeps the slot and set order in its memory prompt.
Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order),
Started::Job(job) => {
app.jobs.opens.push(OpenTab { job, name: name.to_string(), path, slot, order });
app.jobs.focus = Some(job);
app.ui.chrome.home = None;
app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", name)]);
app.ui.status_error = false;
track_open(app, OpenTab { job, name: name.to_string(), path, slot, order });
Ok(())
}
}
}
/// A file opening in the background gets its tab: focused, with the status line naming it.
fn track_open(app: &mut PhotocraftApp, tab: OpenTab) {
app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &tab.name)]);
app.jobs.focus = Some(tab.job);
app.jobs.opens.push(tab);
app.ui.chrome.home = None;
app.ui.status_error = false;
}
/// File › Open as Smart Object… for one file: `file.openAsSmartObject` as a tracked open job, so
/// the result goes through File › Open's completion ([`finish_open`]: the profile prompt, the
/// Camera Raw open dialog for a raw, the import warnings). The document is untitled, so
/// Open Recent is untouched. Inline (background jobs off, or the web) it finishes at once.
pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, order: Option<OpenOrder>) -> Result<(), String> {
let name = crate::file_open::display_name(path);
let params = json!({"path": path});
let started = if app.background_jobs {
app.session.start("file.openAsSmartObject", params).map_err(|e| e.to_string())?
} else {
Started::Done(app.session.execute("file.openAsSmartObject", params).map_err(|e| e.to_string())?)
};
match started {
Started::Done(v) => finish_open(app, &name, None, &v, None, order),
Started::Job(job) => {
track_open(app, OpenTab { job, name, path: None, slot: None, order });
Ok(())
}
}
@@ -608,7 +634,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) {
finish_save(app, ctx, save, &e.label, e.outcome);
return;
}
if e.command == OPEN_JOB {
if e.command == OPEN_JOB || app.jobs.opens.iter().any(|o| o.job == e.id) {
let Some(i) = app.jobs.opens.iter().position(|o| o.job == e.id) else { return };
let tab = app.jobs.opens.remove(i);
match e.outcome {
@@ -703,6 +729,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu
order,
question,
policy_applied,
smart_object: v.get("smartObject").and_then(Value::as_bool).unwrap_or(false),
};
// Held back for the profile prompt (Ask When Opening).
if let Some(id) = v.get("held").and_then(Value::as_u64) {
+2
View File
@@ -569,6 +569,7 @@ fn profile_cancel_cancels_whole_queue_including_memory_prompts() {
order: None,
question: Some(json!({"missing": false, "working": "sRGB", "embedded": "Adobe RGB"})),
policy_applied: false,
smart_object: false,
},
);
@@ -600,6 +601,7 @@ fn mixed_prompts_follow_arrival_order_fifo() {
order: None,
question: None,
policy_applied: false,
smart_object: false,
},
);