PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Open file pickers for Replace Contents, Export Contents and Convert to Linked (#2438)
Fabian Ghenof141c80d3e8ee
diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rsindex 3a0aa9323..3a3dd7e52 100644--- a/crates/engine/src/smart_cmds.rs+++ b/crates/engine/src/smart_cmds.rs@@ -740,16 +740,25 @@ fn set_shared_source(s: &mut Session, id: LayerId, label: &str, keep_psd: bool,fn replace_contents(s: &mut Session, p: &Value) -> Result<Value> {let path = path_param("layer.smartObjects.replaceContents", p)?.to_string();let bytes = photocraft_format::read_file(std::path::Path::new(&path)).map_err(|e| other(format!("can't read {path}: {e}")))?;- let name = base_name(&path);- decode_source(&name, &bytes)?; // fail before touching the document- set_source(s, p, "Replace Contents", false, |_, _| Ok(SmartSource::Embedded { file_name: name, bytes: Arc::new(bytes) }))+ let id = layer_param(s, p)?;+ replace_contents_bytes(s, id, &base_name(&path), bytes)+}++/// Replace Contents from a file's name and bytes: what the desktop and web file pickers hand over.+pub fn replace_contents_bytes(s: &mut Session, id: LayerId, file_name: &str, bytes: Vec<u8>) -> Result<Value> {+ decode_source(file_name, &bytes)?; // fail before touching the document+ set_shared_source(s, id, "Replace Contents", false, SmartSource::Embedded { file_name: file_name.to_string(), bytes: Arc::new(bytes) })+}++/// The file name and bytes of smart object `id`'s contents.+pub fn contents_of(doc: &Document, id: LayerId) -> Result<(String, Arc<Vec<u8>>)> {+ source_bytes(&doc.metadata, &smart(doc, id)?.source).ok_or_else(|| other("the smart object's contents are unavailable"))}fn export_contents(s: &mut Session, p: &Value) -> Result<Value> {let path = path_param("layer.smartObjects.exportContents", p)?;let id = layer_param(s, p)?;- let st = s.active().ok_or(EngineError::NoDocument)?;- let (name, bytes) = source_bytes(&st.doc.metadata, &smart(&st.doc, id)?.source).ok_or_else(|| other("the smart object's contents are unavailable"))?;+ let (name, bytes) = contents_of(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?;crate::file_cmds::write_file(path, &bytes)?;Ok(json!({"path": path, "fileName": name, "bytes": bytes.len()}))}diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rsindex d88958393..2c114c496 100644--- a/crates/ui-egui/src/file_dialog/tests.rs+++ b/crates/ui-egui/src/file_dialog/tests.rs@@ -478,3 +478,93 @@ fn an_answer_of_the_wrong_kind_is_an_error_not_a_crash() {app.poll_file_dialog(&ctx, None);assert_eq!(app.session.documents().len(), 1);}++/// The app with a painted layer converted to a smart object and a duplicate instance of it.+fn smart_app() -> (PhotocraftApp, Open, Rc<RefCell<Vec<String>>>, [u64; 2]) {+ let (mut app, open, written) = app();+ app.run("layer.new.layer", json!({})).unwrap();+ app.session+ .edit("paint", |doc, active| {+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[0.0, 0.0, 1.0, 1.0]);+ Ok(())+ })+ .unwrap();+ let a = app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap();+ let b = app.run("layer.duplicate", json!({"layer": a})).unwrap()["layer"].as_u64().unwrap();+ app.session.select_layer(photocraft_doc::LayerId(a)).unwrap();+ (app, open, written, [a, b])+}++fn smart_source(app: &PhotocraftApp, id: u64) -> photocraft_doc::SmartSource {+ match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content {+ photocraft_doc::LayerContent::Smart(sm) => sm.source.clone(),+ other => panic!("not a smart object: {}", other.kind_name()),+ }+}++#[test]+fn replace_contents_picks_a_file_for_every_instance() {+ let (mut app, open, _, ids) = smart_app();+ let ctx = egui::Context::default();+ let before = ids.map(|id| smart_source(&app, id));+ // Cancelling changes nothing.+ menus::invoke(&mut app, &ctx, "layer.smartObjects.replaceContents", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ assert!(matches!(open.borrow().as_slice(), [(FileDialogRequest::Open { multiple: false, .. }, _)]));+ answer(&open, None);+ app.poll_file_dialog(&ctx, None);+ assert_eq!(ids.map(|id| smart_source(&app, id)), before);+ // A picked file (by contents, as on the web) replaces the contents of both instances.+ let png = photocraft_io::export(&app.session.active().unwrap().doc, "png", &Default::default()).unwrap().bytes;+ menus::invoke(&mut app, &ctx, "layer.smartObjects.replaceContents", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ answer(&open, Some(FileDialogAnswer::Contents("art.png".into(), png)));+ app.poll_file_dialog(&ctx, None);+ assert!(!app.ui.status_error, "{}", app.ui.status);+ for id in ids {+ assert!(matches!(smart_source(&app, id), photocraft_doc::SmartSource::Embedded { ref file_name, .. } if file_name == "art.png"));+ }+ // A file that isn't an image is an error, and the contents stay.+ menus::invoke(&mut app, &ctx, "layer.smartObjects.replaceContents", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ answer(&open, Some(FileDialogAnswer::Contents("notes.png".into(), b"not an image".to_vec())));+ app.poll_file_dialog(&ctx, None);+ assert!(app.ui.status_error);+ assert!(matches!(smart_source(&app, ids[1]), photocraft_doc::SmartSource::Embedded { ref file_name, .. } if file_name == "art.png"));+}++#[test]+fn export_contents_suggests_the_contents_file_name() {+ let (mut app, open, written, _) = smart_app();+ let ctx = egui::Context::default();+ menus::invoke(&mut app, &ctx, "layer.smartObjects.exportContents", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ assert!(+ matches!(open.borrow().as_slice(), [(FileDialogRequest::Save { suggested }, _)] if suggested == "Layer 1.pcraft"),+ "{:?}",+ open.borrow().first().map(|(r, _)| r.clone())+ );+ answer(&open, Some(FileDialogAnswer::SaveTo("/out/contents.pcraft".into())));+ app.poll_file_dialog(&ctx, None);+ assert_eq!(*written.borrow(), ["/out/contents.pcraft"]);+}++#[test]+fn convert_to_linked_asks_where_to_write_the_contents() {+ let (mut app, open, _, ids) = smart_app();+ let ctx = egui::Context::default();+ let dir = std::env::temp_dir().join(format!("pcraft-convert-linked-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("linked.pcraft").to_string_lossy().into_owned();+ menus::invoke(&mut app, &ctx, "layer.smartObjects.convertToLinked", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ assert!(matches!(open.borrow().as_slice(), [(FileDialogRequest::Save { .. }, _)]));+ answer(&open, Some(FileDialogAnswer::SaveTo(path.clone())));+ app.poll_file_dialog(&ctx, None);+ assert!(!app.ui.status_error, "{}", app.ui.status);+ assert!(std::fs::metadata(&path).is_ok_and(|m| m.len() > 0));+ std::fs::remove_dir_all(&dir).ok();+ for id in ids {+ assert_eq!(smart_source(&app, id), photocraft_doc::SmartSource::Linked { path: path.clone() });+ }+}diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rsindex 9bfd6bb01..422e51702 100644--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@ -424,6 +424,9 @@ fn wraps(id: &str) -> bool {| "file.saveACopy"| "file.placeEmbedded"| "file.placeLinked"+ | "layer.smartObjects.replaceContents"+ | "layer.smartObjects.exportContents"+ | "layer.smartObjects.convertToLinked"| "file.closeAll"| "file.closeOthers"| "file.fileInfo"@@ -861,6 +864,29 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Valapp.place_bytes(&name, bytes, linked)}))}+ "layer.smartObjects.replaceContents" => {+ let st = app.session.active()?;+ let (doc, layer) = (st.doc.id, st.active_layer?);+ Some(app.pick_file_bytes(move |app, name, bytes| {+ app.with_document(doc, |app| {+ let r = photocraft_engine::smart_cmds::replace_contents_bytes(&mut app.session, layer, &name, bytes).map_err(|e| e.to_string());+ app.sync_views();+ r+ })+ }))+ }+ "layer.smartObjects.exportContents" => Some(export_contents(app)),+ "layer.smartObjects.convertToLinked" => {+ let st = app.session.active()?;+ let (doc, layer) = (st.doc.id, st.active_layer?);+ let (name, _) = match photocraft_engine::smart_cmds::contents_of(&st.doc, layer) {+ Ok(c) => c,+ Err(e) => return Some(Err(e.to_string())),+ };+ Some(app.pick_save(&name, move |app, path| {+ app.with_document(doc, |app| app.run("layer.smartObjects.convertToLinked", json!({"layer": layer.0, "path": path})))+ }))+ }"file.fileInfo" => {let info = app.session.execute("file.fileInfo", json!({})).ok()?;let kw = info["keywords"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ")).unwrap_or_default();@@ -1059,6 +1085,21 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {})}+/// Layer › Smart Objects › Export Contents: saves the contents file under its own name by default.+fn export_contents(app: &mut PhotocraftApp) -> Result<Value, String> {+ let st = app.session.active().ok_or("no document")?;+ let layer = st.active_layer.ok_or("no layer selected")?;+ // The contents as they were when asked, like Save a Copy.+ let (name, bytes) = photocraft_engine::smart_cmds::contents_of(&st.doc, layer).map_err(|e| e.to_string())?;+ app.pick_save(&name.clone(), move |app, path| {+ let write = app.services.write.as_mut().ok_or("no writer configured")?;+ write(&path, &bytes)?;+ app.ui.status = format!("Exported contents to {path}");+ app.ui.status_error = false;+ Ok(json!({"path": path, "fileName": name, "bytes": bytes.len()}))+ })+}+#[cfg(test)]#[path = "view_cmds/tests.rs"]mod tests;