PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Web: Place Embedded and canvas drops place images (#5749) (#5817)
Michael Higgins1d65bd605b25
diff --git a/apps/photocraft-web/Cargo.toml b/apps/photocraft-web/Cargo.tomlindex 786165b53..4ecad80ae 100644--- a/apps/photocraft-web/Cargo.toml+++ b/apps/photocraft-web/Cargo.toml@@ -34,7 +34,7 @@ rfd = { workspace = true }wasm-bindgen = "0.2"wasm-bindgen-futures = "0.4"js-sys = "0.3"-web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "Navigator"] }+web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "DomRect", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "Navigator"] }[dev-dependencies]serde_json = { workspace = true }diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rsindex eb350d17e..6fd362048 100644--- a/apps/photocraft-web/src/web.rs+++ b/apps/photocraft-web/src/web.rs@@ -1,6 +1,8 @@//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.+use std::cell::Cell;use std::collections::{HashMap, HashSet};+use std::rc::Rc;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};@@ -79,11 +81,13 @@ pub fn start() {Box::new(move |cc| {PhotocraftApp::setup_context(&cc.egui_ctx, ThemeKind::Pro);let inbox: Inbox = Arc::default();+ let place_inbox: Inbox = Arc::default();let served: Served = Arc::default();load_font_manifest(served.clone(), cc.egui_ctx.clone());let (session, warnings) = crate::preset_bridge::session(presets.clone());preset_warnings.extend(warnings);- let mut app = PhotocraftApp::new(session, services(inbox.clone()));+ let drag = listen_drag(&pen_target);+ let mut app = PhotocraftApp::new(session, services(inbox.clone(), place_inbox.clone(), drag_pos_service(pen_target.clone(), drag)));if !preset_warnings.is_empty() {photocraft_ui_egui::notices::post(&mut app, i18n::t("Some brush presets could not be loaded"), preset_warnings, true, None);}@@ -97,7 +101,7 @@ pub fn start() {}let unsaved = Arc::new(AtomicBool::new(false));guard_unload(unsaved.clone());- Ok(Box::new(WebShell { app, inbox, unsaved, served, database, presets }))+ Ok(Box::new(WebShell { app, inbox, place_inbox, unsaved, served, database, presets }))}),).await;@@ -140,6 +144,38 @@ fn listen_pen(target: &web_sys::HtmlCanvasElement, feed: photocraft_ui_egui::sty}}+/// The pointer in a drag over the page, in CSS pixels relative to the viewport (`clientX`,+/// `clientY`): the last `dragover` or `drop` event's.+type DragPos = Rc<Cell<Option<(f32, f32)>>>;++/// Follows files dragged over the canvas. eframe's drop events carry no pointer position and the+/// page gets no pointer events during a drag, so this is where a drop lands: on the document's+/// canvas it places the files, elsewhere it opens them (#5749).+fn listen_drag(target: &web_sys::HtmlCanvasElement) -> DragPos {+ use wasm_bindgen::closure::Closure;+ let pos = DragPos::default();+ for kind in ["dragover", "drop"] {+ let pos = pos.clone();+ // A DragEvent is a MouseEvent: only its client position is read.+ let cb = Closure::<dyn FnMut(web_sys::MouseEvent)>::new(move |e: web_sys::MouseEvent| pos.set(Some((e.client_x() as f32, e.client_y() as f32))));+ if target.add_event_listener_with_callback(kind, cb.as_ref().unchecked_ref()).is_ok() {+ cb.forget();+ }+ }+ pos+}++/// `Services::cursor_pos` for the web: the last drag position in egui points, mapped as eframe+/// maps pointer events (relative to the canvas, divided by the zoom factor).+fn drag_pos_service(canvas: web_sys::HtmlCanvasElement, pos: DragPos) -> photocraft_ui_egui::CursorPosFn {+ Box::new(move |ctx: &egui::Context| {+ let (x, y) = pos.get()?;+ let rect = canvas.get_bounding_client_rect();+ let zoom = ctx.zoom_factor();+ (zoom.is_finite() && zoom > 0.0).then(|| egui::pos2((x - rect.left() as f32) / zoom, (y - rect.top() as f32) / zoom))+ })+}+/// Closing or reloading the tab while a document has unsaved changes asks first, as closing the/// desktop window does: the browser shows its own "Leave site?" prompt (#1380). `unsaved` is/// refreshed every frame by [`WebShell`].@@ -219,10 +255,13 @@ async fn fetch_bytes(url: &str, integrity: Option<&str>) -> Result<Vec<u8>, Stri}/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously,-/// so the app's own drop path can't handle them) and feed them through the inbox.+/// so the app's own drop path can't handle them) and feed them through the inboxes.struct WebShell {app: PhotocraftApp,+ /// Dropped files to open as documents.inbox: Inbox,+ /// Dropped files to place on the active document's canvas.+ place_inbox: Inbox,/// Read by the `beforeunload` listener ([`guard_unload`]).unsaved: Arc<AtomicBool>,served: Served,@@ -285,17 +324,26 @@ impl WebShell {impl eframe::App for WebShell {fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));- for f in dropped {- let inbox = self.inbox.clone();+ if !dropped.is_empty() {+ let names: Vec<String> =+ dropped.iter().map(|f| f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into())).collect();+ // Decided now, where the drop landed: on the document's canvas the files are placed+ // as layers (as on the desktop), elsewhere opened.+ let places = self.app.dropped_on_canvas(ctx, &names);+ let files: Vec<_> = dropped.into_iter().zip(names).zip(places).collect();+ let (inbox, place_inbox) = (self.inbox.clone(), self.place_inbox.clone());let ctx = ctx.clone();+ // One after another, so they open or place in the order they were dropped.wasm_bindgen_futures::spawn_local(async move {- let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());- match f.bytes_async().await {- Ok(bytes) => {- inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));- ctx.request_repaint();+ for ((f, name), place) in files {+ match f.bytes_async().await {+ Ok(bytes) => {+ let queue = if place { &place_inbox } else { &inbox };+ queue.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));+ ctx.request_repaint();+ }+ Err(e) => log::error!("couldn't read dropped file {name}: {e}"),}- Err(e) => log::error!("couldn't read dropped file {name}: {e}"),}});}@@ -333,7 +381,7 @@ impl eframe::App for WebShell {}}-fn services(inbox: Inbox) -> Services {+fn services(inbox: Inbox, place_inbox: Inbox, cursor_pos: photocraft_ui_egui::CursorPosFn) -> Services {Services {screen_pick: screen_color_service(),import: Some(Box::new(|name: &str, bytes: &[u8], max_svg_group_depth: usize| {@@ -384,6 +432,8 @@ fn services(inbox: Inbox) -> Services {photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())})),inbox: Some(inbox),+ place_inbox: Some(place_inbox),+ cursor_pos: Some(cursor_pos),// Preferences live in the browser's localStorage.load_prefs: Some(Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten())),save_prefs: Some(Box::new(|text: &str| local_storage().ok_or("no localStorage")?.set_item(PREFS_KEY, text).map_err(|e| format!("{e:?}")))),diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rsindex 53e908bec..1cf61e98d 100644--- a/crates/ui-egui/src/file_open.rs+++ b/crates/ui-egui/src/file_open.rs@@ -33,6 +33,15 @@ pub enum DropTarget {Elsewhere,}+/// A file dropped on the canvas, waiting its turn to be placed.+pub(crate) enum DropPlace {+ /// Dropped onto the window (desktop): read from its path, or through egui.+ File(egui::DroppedFileHandle),+ /// Read by the shell itself (the browser reads dropped files asynchronously): its name and+ /// contents, delivered through [`Services::place_inbox`](crate::Services::place_inbox).+ Bytes(String, Vec<u8>),+}+/// `warnings` from an import, plus one for each font family the active document's type uses that/// isn't installed (#4559): Photoshop warns about missing fonts as a file opens, and the CLI and/// automation already report them; the type would otherwise silently render in a fallback face.@@ -211,7 +220,7 @@ impl PhotocraftApp {for f in files {let name = dropped_name(&f);if target == DropTarget::Canvas && !crate::preset_files_ui::is_preset_file(&name) {- self.drop_places.push_back(f);+ self.drop_places.push_back(DropPlace::File(f));continue;}match self.open_dropped_file(&f, &name, slot) {@@ -222,6 +231,24 @@ impl PhotocraftApp {}}+ /// Which of the files called `names`, dropped onto the window just now, are placed on the+ /// active document's canvas rather than opened, for a shell that reads dropped files itself+ /// (the browser reads them asynchronously, so the web shell can't hand them to+ /// [`open_dropped`](Self::open_dropped)). It delivers those through+ /// [`Services::place_inbox`](crate::Services::place_inbox) and the rest through+ /// [`Services::inbox`](crate::Services::inbox). The pointer comes from+ /// [`Services::cursor_pos`](crate::Services::cursor_pos). As with a desktop canvas drop, a Free+ /// Transform still open is applied first (#4833).+ pub fn dropped_on_canvas(&mut self, ctx: &egui::Context, names: &[String]) -> Vec<bool> {+ let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx));+ let canvas = self.drop_target(ctx, at) == DropTarget::Canvas;+ let places: Vec<bool> = names.iter().map(|n| canvas && !crate::preset_files_ui::is_preset_file(n)).collect();+ if places.contains(&true) && self.ui.transform.is_some() {+ crate::transform_tool::commit(self);+ }+ places+ }+/// Where a drop at `at` lands. Over a window or dialog it's neither the canvas nor the tabs.pub(crate) fn drop_target(&self, ctx: &egui::Context, at: Option<egui::Pos2>) -> DropTarget {let Some(p) = at.filter(|p| ctx.layer_id_at(*p).is_none_or(|l| l.order == egui::Order::Background)) else {@@ -259,11 +286,20 @@ impl PhotocraftApp {/// transform is in progress (so several files are placed and transformed one after another).pub(crate) fn place_next_dropped(&mut self, ctx: &egui::Context) {while self.ui.transform.is_none() {- let Some(f) = self.drop_places.pop_front() else { return };- let placed = if f.path().is_absolute() {- self.run("file.placeEmbedded", serde_json::json!({"path": f.path().to_string_lossy()}))- } else {- crate::read_dropped(&*f).and_then(|bytes| self.place_bytes(&dropped_name(&f), bytes, None))+ let Some(next) = self.drop_places.pop_front() else { return };+ let (name, placed) = match next {+ DropPlace::File(f) if f.path().is_absolute() => {+ (dropped_name(&f), self.run("file.placeEmbedded", serde_json::json!({"path": f.path().to_string_lossy()})))+ }+ DropPlace::File(f) => {+ let name = dropped_name(&f);+ let placed = crate::read_dropped(&*f).and_then(|bytes| self.place_bytes(&name, bytes, None));+ (name, placed)+ }+ DropPlace::Bytes(name, bytes) => {+ let placed = self.place_bytes(&name, bytes, None);+ (name, placed)+ }};match placed {Ok(_) => {@@ -271,7 +307,7 @@ impl PhotocraftApp {self.ui.status = e;}}- Err(e) => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &dropped_name(&f)), ("error", &e)])),+ Err(e) => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &name), ("error", &e)])),}}}diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rsindex b43a10a64..00db3ef96 100644--- a/crates/ui-egui/src/file_open/tests.rs+++ b/crates/ui-egui/src/file_open/tests.rs@@ -173,6 +173,35 @@ fn the_web_opens_every_selected_file() {assert!(app.ui.notices.iter().any(|n| n.error && n.title.contains("broken.png")), "{:?}", app.ui.notices);}+/// #5749: the web shell reads dropped files itself, so it asks where they landed: image files+/// dropped on the canvas are placed from their bytes, presets and drops elsewhere are opened.+#[test]+fn web_drops_onto_the_canvas_are_placed_from_their_bytes() {+ let ctx = egui::Context::default();+ let mut app = app_with_canvas();+ let names = vec!["photo.png".to_string(), "brushes.abr".to_string()];+ // No pointer known: nothing is placed.+ assert_eq!(app.dropped_on_canvas(&ctx, &names), [false, false]);+ let at = Rc::new(std::cell::Cell::new(egui::pos2(400.0, 300.0)));+ let reported = at.clone();+ app.services.cursor_pos = Some(Box::new(move |_: &egui::Context| Some(reported.get())));+ assert_eq!(app.dropped_on_canvas(&ctx, &names), [true, false]);+ at.set(egui::pos2(20.0, 20.0));+ assert_eq!(app.dropped_on_canvas(&ctx, &names), [false, false], "off the canvas: opened");+ let layers = layer_count(&app);+ app.drop_places.push_back(crate::file_open::DropPlace::Bytes("photo.png".into(), png_bytes(4, 3)));+ app.drop_places.push_back(crate::file_open::DropPlace::Bytes("bad.png".into(), b"bad".to_vec()));+ app.place_next_dropped(&ctx);+ assert_eq!(layer_count(&app), layers + 1);+ assert_eq!(app.ui.transform.as_ref().and_then(|t| t.made), Some(crate::state::MadeLayer::Place));+ crate::transform_tool::commit(&mut app);+ // The undecodable one is reported, not placed.+ app.place_next_dropped(&ctx);+ assert_eq!(layer_count(&app), layers + 1);+ assert!(app.ui.notices.iter().any(|n| n.error && n.title.contains("bad.png")), "{:?}", app.ui.notices);+ assert!(app.drop_places.is_empty());+}+#[test]fn pcraft_documents_save_in_place_but_flat_files_ask() {let (mut app, written) = app_with(vec![None]);diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 496b20828..5adfd7886 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -485,8 +485,13 @@ pub struct Services {/// Preferences ▸ General ▸ Beep When Done: the platform's default beep, played when a/// background job finishes successfully. `None` in the web build (and in tests).pub beep: Option<fn()>,- /// Files delivered asynchronously (web drag-and-drop): drained every frame.+ /// Files delivered asynchronously (web drag-and-drop): drained every frame and opened as+ /// documents.pub inbox: Option<Inbox>,+ /// Files delivered asynchronously for a drop onto the active document's canvas (web+ /// drag-and-drop, routed by [`PhotocraftApp::dropped_on_canvas`]): placed as layers like a+ /// desktop canvas drop (Place Embedded, each in Free Transform).+ pub place_inbox: Option<Inbox>,/// OS clipboard images: copies go out, screenshots and images from other apps come in.pub clipboard_set_image: Option<ClipboardSetFn>,pub clipboard_get_image: Option<ClipboardGetFn>,@@ -513,8 +518,9 @@ pub struct Services {pub append_text: Option<AppendTextFn>,/// OS requests (macOS open-documents / quit Apple events), polled every frame.pub os_events: Option<OsEventsFn>,- /// The pointer position read from the OS (desktop): winit 0.30's file drops carry none, and- /// the window gets no pointer events during an OS drag (see `file_open::DropTarget`).+ /// The pointer position read from the OS (desktop) or from the page's drag events (web):+ /// file drops carry none, and the window gets no pointer events during an OS drag (see+ /// `file_open::DropTarget`).pub cursor_pos: Option<CursorPosFn>,/// Caps Lock toggled on (desktop; `None` on Wayland and the web). Read once per frame, so/// the canvas can show the precise crosshair for painting tools, whatever the preference.@@ -672,7 +678,7 @@ pub struct PhotocraftApp {/// The document tab strip last frame: a drop there opens the file at the slot under it.pub(crate) tab_strip: Option<canvas::TabStrip>,/// Files dropped on the canvas still to place, one Free Transform at a time.- pub(crate) drop_places: std::collections::VecDeque<egui::DroppedFileHandle>,+ pub(crate) drop_places: std::collections::VecDeque<file_open::DropPlace>,/// The document each of `ui.views` belongs to, as of the last [`Self::sync_views`].view_docs: Vec<DocId>,pub fps: f32,@@ -1917,6 +1923,10 @@ impl eframe::App for PhotocraftApp {self.open_failed(&name, &e);}}+ // Web drops onto the canvas, read since the last frame: placed below, one at a time.+ let to_place: Vec<(String, Vec<u8>)> =+ self.services.place_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default();+ self.drop_places.extend(to_place.into_iter().map(|(name, bytes)| file_open::DropPlace::Bytes(name, bytes)));// Finder double-click / Open With / Dock drops (macOS open-documents events).self.drain_os_events(ctx);// While files are dragged over the window it gets no pointer events: keep frames coming so