PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(web): File › Place Embedded is enabled in the browser and places the picked file's bytes (#1209, #5749) (#5585)
Gustavo Zigerd900daa0ba43
diff --git a/Cargo.toml b/Cargo.tomlindex 0d0f93ae7..4716812f0 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -136,6 +136,14 @@ opt-level = "z"[profile.wasm-release.package.naga]opt-level = "z"+# The browser UI toolkit favors size to stay within the WebAssembly upload budget.+[profile.wasm-release.package.egui]+opt-level = "z"+[profile.wasm-release.package.epaint]+opt-level = "z"+[profile.wasm-release.package.eframe]+opt-level = "z"+# Pixel processing keeps its speed-oriented optimization level, with two exceptions.# Colour-management transforms are built once and cached (`transform::cached`), so "z" costs# little runtime. The browser app composites per frame on the GPU (`crates/gpu`, WebGPU/WebGL2),diff --git a/apps/photocraft-web/src/main.rs b/apps/photocraft-web/src/main.rsindex 428143c88..0802a02eb 100644--- a/apps/photocraft-web/src/main.rs+++ b/apps/photocraft-web/src/main.rs@@ -6,10 +6,10 @@//!//! Differences from the desktop app://! - no TCP control server (browsers can't listen on sockets);-//! - File → Open uses the browser file picker; bytes arrive asynchronously through-//! `Services::inbox`;+//! - file pickers return browser file contents asynchronously through `Services::file_dialog`;+//! this includes File → Open and commands such as Place Embedded;//! - saving/exporting triggers a browser download;-//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox.+//! - dropped files are read asynchronously by `web::WebShell` and delivered through `Services::inbox`.//!//! URL query flags: `?cpu` forces the CPU canvas path (same as `PHOTOCRAFT_CPU_CANVAS=1`);//! `?webgl` forces the WebGL2 backend instead of WebGPU.diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rsindex 2a325ea2c..9e4c878f6 100644--- a/crates/ui-egui/src/file_dialog/tests.rs+++ b/crates/ui-egui/src/file_dialog/tests.rs@@ -687,6 +687,53 @@ fn smart_source(app: &PhotocraftApp, id: u64) -> photocraft_doc::SmartSource {}}+#[test]+fn place_embedded_uses_the_single_file_picker_and_accepts_contents() {+ let (mut app, open, _) = app();+ let ctx = egui::Context::default();+ assert!(menus::is_enabled(&app, "file.placeEmbedded"));+ let source = photocraft_io::export(&app.session.active().unwrap().doc, "source.png", &Default::default()).unwrap().bytes;+ let layers_before = app.session.active().unwrap().doc.layers.len();++ // Cancel leaves the document alone and does not report an error.+ menus::invoke(&mut app, &ctx, "file.placeEmbedded", 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!(app.session.active().unwrap().doc.layers.len(), layers_before);+ assert!(!app.ui.status_error, "{}", app.ui.status);++ // The Web picker returns the selected file's name and bytes instead of a filesystem path.+ menus::invoke(&mut app, &ctx, "file.placeEmbedded", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ answer(&open, Some(FileDialogAnswer::Contents("source.png".into(), source)));+ app.poll_file_dialog(&ctx, None);+ assert!(!app.ui.status_error, "{}", app.ui.status);+ let st = app.session.active().unwrap();+ assert_eq!(st.doc.layers.len(), layers_before + 1);+ let layer = st.doc.layer(st.active_layer.unwrap()).unwrap();+ assert_eq!(layer.name, "source");+ assert_eq!(app.ui.transform.as_ref().and_then(|t| t.made), Some(crate::state::MadeLayer::Place));+ assert!(matches!(+ &layer.content,+ photocraft_doc::LayerContent::Smart(sm)+ if matches!(&sm.source, photocraft_doc::SmartSource::Embedded { file_name, .. } if file_name == "source.png")+ ));++ // Finish the successful placement before starting the next picker.+ crate::transform_tool::commit(&mut app);+ assert!(app.ui.transform.is_none());++ // Invalid contents are reported without adding a layer.+ menus::invoke(&mut app, &ctx, "file.placeEmbedded", json!({})).unwrap();+ app.poll_file_dialog(&ctx, None);+ answer(&open, Some(FileDialogAnswer::Contents("broken.png".into(), b"not an image".to_vec())));+ app.poll_file_dialog(&ctx, None);+ assert!(app.ui.status_error);+ assert_eq!(app.session.active().unwrap().doc.layers.len(), layers_before + 1);+}+#[test]fn replace_contents_picks_a_file_for_every_instance() {let (mut app, open, _, ids) = smart_app();diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rsindex 8acd676f9..1da1f918d 100644--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@ -459,6 +459,11 @@ pub fn handles(id: &str) -> bool {}pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option<bool> {+ is_enabled_with_engine(app, id, || app.session.is_enabled(id))+}++/// Keep picker enablement testable with the engine's native filesystem check disabled.+fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabled: impl FnOnce() -> bool) -> Option<bool> {if !handles(id) && !wraps(id) {return None;}@@ -476,7 +481,10 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option<bool> {|| (doc && matches!(&i["window.arrange.".len()..], "floatAllInWindows" | "cascade" | "tile" | "tileAllVertically" | "tileAllHorizontally"))}},- i if wraps(i) => app.session.is_enabled(i),+ // Embedded placement reads the picker's bytes on every platform. Linked placement keeps+ // the engine's native filesystem guard because its source must remain reachable.+ "file.placeEmbedded" => doc && app.services.file_dialog.is_some(),+ i if wraps(i) => engine_enabled(),_ => true,})}diff --git a/crates/ui-egui/src/view_cmds/tests.rs b/crates/ui-egui/src/view_cmds/tests.rsindex 2205b6e15..1abe86355 100644--- a/crates/ui-egui/src/view_cmds/tests.rs+++ b/crates/ui-egui/src/view_cmds/tests.rs@@ -14,6 +14,32 @@ fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {menu_items(app).into_iter().find(|i| i.id == id).and_then(|i| i.checked)}+/// #1209: the browser picker supplies bytes even when the engine cannot read native paths.+#[test]+fn place_embedded_enablement_does_not_require_native_doc() {+ for has_doc in [true, false] {+ for has_picker in [true, false] {+ let (mut app, _) = app_with(usize::from(has_doc));+ if has_picker {+ app.services.file_dialog = Some(Box::new(|_, _, _| {}));+ }+ for native_filesystem in [false, true] {+ let native_doc = native_filesystem && has_doc;+ assert_eq!(+ is_enabled_with_engine(&app, "file.placeEmbedded", || native_doc),+ Some(has_doc && has_picker),+ "Place Embedded: doc={has_doc}, picker={has_picker}, native_doc={native_doc}"+ );+ assert_eq!(+ is_enabled_with_engine(&app, "file.placeLinked", || native_doc),+ Some(native_doc),+ "Place Linked must retain the engine's native_doc guard"+ );+ }+ }+ }+}+#[test]fn show_snap_extras_and_screen_modes_are_state() {let (mut app, ctx) = app_with(1);diff --git a/docs/development.md b/docs/development.mdindex 67f688b6b..035efbbcf 100644--- a/docs/development.md+++ b/docs/development.md@@ -399,9 +399,9 @@ HTTPS/reverse-proxy deployment and browser limitations.How the web shell (`apps/photocraft-web/src/web.rs`) differs from desktop:-- **Open** uses `rfd::AsyncFileDialog`. The bytes arrive asynchronously in `Services::inbox`, which the app drains every frame.+- **File dialogs** use `rfd::AsyncFileDialog`. Chosen file contents arrive asynchronously through `Services::file_dialog`; this includes File › Open and single-file commands such as Place Embedded.- **Save / Save As / Export** trigger a browser download of the encoded bytes. The shell does this with a Blob, an object URL and a temporary `<a download>`, all created from Rust. There is no save dialog, so the suggested name becomes the download name.-- **Drag-and-drop:** `WebShell` takes the frame's `dropped_files` before the app sees them. It reads each file with `DroppedFile::bytes_async` and pushes the bytes into the inbox.+- **Drag-and-drop:** `WebShell` takes the frame's `dropped_files` before the app sees them. It reads each file with `DroppedFile::bytes_async` and pushes the bytes into `Services::inbox`.- **Startup failures:** `index.html` shows "Loading PhotoCraft…" until the app removes it, or replaces it with the error when the web runner fails to start. If the `.wasm` never downloads or doesn't match the page's `.js` (a stale cached `index.html` after a deploy), no Rust runs at all, so the page itself (CSS only, no script) adds a hint with a Reload link after 20 seconds.- **No control server:** browsers can't listen on TCP. To automate the web build, drive headless Chrome with `--remote-debugging-port`. `Page.setInterceptFileChooserDialog` plus `DOM.setFileInputFiles` covers Open, `Input.dispatchDragEvent` with `files` covers drops, and `Browser.setDownloadBehavior` captures downloads.- Headless Chrome on macOS (`--headless=new --enable-unsafe-webgpu`) gets a real WebGPU adapter.