From d7bb456cb1e50ea42f2e78b26b49eaa2fddbdd45 Mon Sep 17 00:00:00 2001 From: Hasan Zayni Date: Sun, 1 Nov 2026 17:55:11 +0300 Subject: [PATCH] Drops: route by a pure function, say when a folder is dropped, log how far a drag got (#10492) A file dragged onto the window did nothing visible for the reporter on Windows 11 (0.18.0), with no way to tell whether Windows never offered the files or PhotoCraft mishandled them. The app side checks out: winit's Windows backend (OLE IDropTarget, CF_HDROP) emits DroppedFile, egui-winit puts it in raw.dropped_files, and a drop with no document open or off the canvas opens like File > Open. What this changes: - Routing is a pure, tested decision: `target_at` (tab strip / canvas / elsewhere, from what the last frame drew) and `DropTarget::route` (place vs open, presets always open). Tests cover several file types, no document, a stale canvas rectangle, covered pointer, multiple files and presets. - A dropped folder is refused with "it is a folder, not a file" instead of Windows' "Access is denied" (or Place Embedded's error), and the other dropped files still go through. - A drag over the window and a drop each log one info line (counts and target, never file names). A drag with neither line never reached PhotoCraft, which is how an elevated PhotoCraft (UIPI, see #8559) or a non-file drag source shows up in a bug report. --- crates/ui-egui/src/app/frame.rs | 4 +- crates/ui-egui/src/file_open.rs | 101 +++++++++++++--- crates/ui-egui/src/file_open/tests.rs | 163 ++++++++++++++++++++++++++ docs/development.md | 2 + 4 files changed, 255 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 07ea17b7e8..a65535f1e5 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -107,9 +107,11 @@ impl PhotocraftApp { self.drain_os_events(ctx); // While files are dragged over the window it gets no pointer events: keep frames coming so // the tab strip can follow the pointer. - if ctx.input(|i| !i.raw.hovered_files.is_empty()) { + let hovering = ctx.input(|i| i.raw.hovered_files.len()); + if hovering > 0 { ctx.request_repaint(); } + file_open::log_drag_over(ctx, hovering); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); if !dropped.is_empty() { let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 65c1fb5758..7eaa6fceab 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -33,6 +33,77 @@ pub enum DropTarget { Elsewhere, } +impl DropTarget { + /// What a dropped file called `name` does here. Preset files (brushes, gradients) go to their + /// libraries wherever they land, so only a canvas drop of anything else is placed. This is the + /// whole routing decision, apart from where the pointer is ([`target_at`]). + pub fn route(self, name: &str) -> DropRoute { + if self == DropTarget::Canvas && !crate::preset_files_ui::is_preset_file(name) { DropRoute::Place } else { DropRoute::Open } + } +} + +/// What happens to one dropped file, by [`DropTarget::route`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DropRoute { + /// Placed on the active document's canvas (File › Place Embedded), in Free Transform. + Place, + /// Opened like File › Open (at the drop's tab position when it landed on the tab strip). + Open, +} + +/// Where a drop at `at` lands, from what the last frame drew: the tab strip, the canvas (a drop +/// is placed only while a document is open) and whether `at` is free of windows and dialogs above +/// the workspace (`uncovered`). No pointer, a covered one, or none of those regions means +/// [`DropTarget::Elsewhere`]: the files open like File › Open, which is also what a drop onto the +/// Home screen or an empty workspace does (#10492). +pub(crate) fn target_at( + at: Option, + uncovered: bool, + tabs: Option<&crate::canvas::TabStrip>, + canvas: Option, + has_document: bool, +) -> DropTarget { + let Some(p) = at.filter(|_| uncovered) else { + return DropTarget::Elsewhere; + }; + if let Some(strip) = tabs.filter(|s| s.rect.contains(p)) { + return DropTarget::Tabs(strip.slot(p.x)); + } + // The canvas shown last frame may belong to a document closed since. + if has_document && canvas.is_some_and(|r| r.contains(p)) { + return DropTarget::Canvas; + } + DropTarget::Elsewhere +} + +/// Why a dropped `path` can't be opened or placed when it is a folder, for a clear message in +/// place of the operating system's (Windows says "Access is denied" for reading a directory). +/// `None` for anything else, including a path that can't be inspected: the open reports that. +pub(crate) fn folder_error(path: &std::path::Path) -> Option { + #[cfg(not(target_arch = "wasm32"))] + if std::fs::metadata(path).is_ok_and(|m| m.is_dir()) { + return Some(tl!("it is a folder, not a file; drop the files inside it instead").to_string()); + } + #[cfg(target_arch = "wasm32")] + let _ = path; + None +} + +/// Log, once per drag, that files are being dragged over the window (`hovering` of them). Together +/// with the line `open_dropped` logs for a drop, it shows how far a drag got: nothing logged +/// means the operating system never offered the files to PhotoCraft (a window running as +/// administrator is not offered files from a File Explorer that isn't, #10492). +pub(crate) fn log_drag_over(ctx: &egui::Context, hovering: usize) { + let id = egui::Id::unique("log-drag-over"); + let was = ctx.data_mut(|d| d.get_temp::(id).unwrap_or(false)); + if (hovering > 0) != was { + ctx.data_mut(|d| d.insert_temp(id, hovering > 0)); + if hovering > 0 { + log::info!("{hovering} file(s) dragged over the window"); + } + } +} + /// 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. @@ -225,6 +296,9 @@ impl PhotocraftApp { /// absolute path, read in bounded reads (#375) rather than egui's whole-file read. pub fn open_dropped(&mut self, ctx: &egui::Context, files: Vec, at: Option) { let target = self.drop_target(ctx, at); + // The log tells a drop that never reached the app (the operating system, or an elevated + // process, refused it) from one the app routed (#10492). File names stay out of it. + log::info!("{} file(s) dropped on the window: {target:?}, pointer {}", files.len(), if at.is_some() { "known" } else { "unknown" }); let mut slot = match target { DropTarget::Tabs(slot) => Some(slot), DropTarget::Canvas | DropTarget::Elsewhere => None, @@ -232,12 +306,20 @@ impl PhotocraftApp { // A box still open from an earlier drop (or any Free Transform) is applied first (#4833): // the queue below places the next file only once no box is open, so a separate drop // would otherwise wait unseen for ↩. Files dropped together still go one by one. - if target == DropTarget::Canvas && self.ui.transform.is_some() && files.iter().any(|f| !crate::preset_files_ui::is_preset_file(&dropped_name(f))) { + if target == DropTarget::Canvas && self.ui.transform.is_some() && files.iter().any(|f| target.route(&dropped_name(f)) == DropRoute::Place) { crate::transform_tool::commit(self); } for f in files { let name = dropped_name(&f); - if target == DropTarget::Canvas && !crate::preset_files_ui::is_preset_file(&name) { + let route = target.route(&name); + if let Some(why) = folder_error(f.path()) { + match route { + DropRoute::Place => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &name), ("error", &why)])), + DropRoute::Open => self.open_failed(&name, &why), + } + continue; + } + if route == DropRoute::Place { self.drop_places.push_back(DropPlace::File(f)); continue; } @@ -260,7 +342,7 @@ impl PhotocraftApp { pub fn dropped_on_canvas(&mut self, ctx: &egui::Context, names: &[String]) -> Vec { 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 = names.iter().map(|n| canvas && !crate::preset_files_ui::is_preset_file(n)).collect(); + let places: Vec = names.iter().map(|n| canvas && DropTarget::Canvas.route(n) == DropRoute::Place).collect(); if places.contains(&true) && self.ui.transform.is_some() { crate::transform_tool::commit(self); } @@ -269,17 +351,8 @@ impl PhotocraftApp { /// 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) -> DropTarget { - let Some(p) = at.filter(|p| ctx.layer_id_at(*p).is_none_or(|l| l.order == egui::Order::Background)) else { - return DropTarget::Elsewhere; - }; - if let Some(strip) = self.tab_strip.as_ref().filter(|s| s.rect.contains(p)) { - return DropTarget::Tabs(strip.slot(p.x)); - } - // The canvas shown last frame may belong to a document closed since. - if self.session.active().is_some() && self.drop_canvas_rect.is_some_and(|r| r.contains(p)) { - return DropTarget::Canvas; - } - DropTarget::Elsewhere + let uncovered = at.is_some_and(|p| ctx.layer_id_at(p).is_none_or(|l| l.order == egui::Order::Background)); + target_at(at, uncovered, self.tab_strip.as_ref(), self.drop_canvas_rect, self.session.active().is_some()) } /// Open one dropped file; with `slot`, its tab goes there (when it finishes opening, for diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index c0323da9a1..38545414b3 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -1127,3 +1127,166 @@ fn opening_an_open_file_again_shows_its_tab() { let _ = std::fs::remove_dir_all(&d); } } + +// ---- Where a drop goes (#10492) ---- + +/// A tab strip of three 100-wide tabs at y 14-50 over x 0-700, and a canvas below it. +fn strip() -> crate::canvas::TabStrip { + let tab = |i: usize| (i, egui::Rect::from_min_max(egui::pos2(104.0 * i as f32, 20.0), egui::pos2(104.0 * i as f32 + 100.0, 46.0))); + crate::canvas::TabStrip { rect: egui::Rect::from_min_max(egui::pos2(0.0, 14.0), egui::pos2(700.0, 50.0)), tabs: vec![tab(0), tab(1), tab(2)] } +} + +fn canvas() -> Option { + Some(egui::Rect::from_min_max(egui::pos2(100.0, 50.0), egui::pos2(700.0, 550.0))) +} + +#[test] +fn a_drop_lands_on_the_region_under_the_pointer() { + let strip = strip(); + let on = |at, uncovered, tabs, canvas, doc| target_at(at, uncovered, tabs, canvas, doc); + // Over the canvas of an open document: placed. + assert_eq!(on(Some(egui::pos2(300.0, 300.0)), true, Some(&strip), canvas(), true), DropTarget::Canvas); + // Over the tab strip: that tab position (the strip wins where it overlaps the canvas). + assert_eq!(on(Some(egui::pos2(4.0, 30.0)), true, Some(&strip), canvas(), true), DropTarget::Tabs(0)); + assert_eq!(on(Some(egui::pos2(150.0, 30.0)), true, Some(&strip), canvas(), true), DropTarget::Tabs(1)); + assert_eq!(on(Some(egui::pos2(690.0, 30.0)), true, Some(&strip), canvas(), true), DropTarget::Tabs(3)); + // Over a panel, outside every region. + assert_eq!(on(Some(egui::pos2(750.0, 300.0)), true, Some(&strip), canvas(), true), DropTarget::Elsewhere); + // The pointer can't be read, or a window or dialog covers it: open, never place. + assert_eq!(on(None, true, Some(&strip), canvas(), true), DropTarget::Elsewhere); + assert_eq!(on(Some(egui::pos2(300.0, 300.0)), false, Some(&strip), canvas(), true), DropTarget::Elsewhere); + assert_eq!(on(Some(egui::pos2(4.0, 30.0)), false, Some(&strip), canvas(), true), DropTarget::Elsewhere); + // No document: the Home screen or an empty workspace. A canvas rectangle left from a document + // closed since doesn't make the drop a placement with nothing to place into. + assert_eq!(on(Some(egui::pos2(300.0, 300.0)), true, None, None, false), DropTarget::Elsewhere); + assert_eq!(on(Some(egui::pos2(300.0, 300.0)), true, None, canvas(), false), DropTarget::Elsewhere); +} + +#[test] +fn only_a_canvas_drop_of_a_non_preset_file_is_placed() { + let files = + ["photo.png", "photo.JPG", "layers.psd", "big.psb", "scan.tif", "shot.heic", "notes.txt", "no_extension", "", "C:\\pics\\a.webp", "/pics/b.svg"]; + let presets = ["brushes.abr", "Sunsets.GRD", "/lib/set.abr", "C:\\lib\\x.grd"]; + for target in [DropTarget::Canvas, DropTarget::Tabs(0), DropTarget::Tabs(7), DropTarget::Elsewhere] { + for name in files { + let want = if target == DropTarget::Canvas { DropRoute::Place } else { DropRoute::Open }; + assert_eq!(target.route(name), want, "{target:?} {name:?}"); + } + for name in presets { + assert_eq!(target.route(name), DropRoute::Open, "presets go to their libraries: {target:?} {name:?}"); + } + } +} + +/// A scratch folder, removed by the test. +fn scratch(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("photocraft-drop-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn error_titles(app: &PhotocraftApp) -> Vec { + app.ui.notices.iter().filter(|n| n.error).map(|n| n.title.clone()).collect() +} + +/// The Home screen (no document open) is where a first drop lands: every file opens as its own +/// document, in drop order, whatever the type, and nothing is placed. +#[test] +fn files_dropped_with_no_document_open_all_open() { + let dir = scratch("home"); + let names = ["a.png", "b.jpg", "c.psd", "d.tif"]; + let files: Vec<_> = names + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, b"x").unwrap(); + dropped(p, Err("read from the path".into())) + }) + .collect(); + let (mut app, _) = app_with(Vec::new()); + // A canvas rectangle left from an earlier document must not turn the drop into a placement. + app.drop_canvas_rect = canvas(); + assert_eq!(app.drop_target(&egui::Context::default(), Some(egui::pos2(300.0, 300.0))), DropTarget::Elsewhere); + app.open_dropped(&egui::Context::default(), files, Some(egui::pos2(300.0, 300.0))); + assert_eq!(doc_names(&app), names); + assert!(app.drop_places.is_empty()); + assert!(error_titles(&app).is_empty(), "{:?}", app.ui.notices); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A folder dragged in says it is a folder (Windows' own error for reading one is "Access is +/// denied"), opens nothing and places nothing, and the files dropped with it still go through. +#[test] +fn a_dropped_folder_is_refused_with_a_clear_message() { + let dir = scratch("folder"); + let folder = dir.join("Holiday photos"); + std::fs::create_dir_all(&folder).unwrap(); + let file = dir.join("ok.psd"); + std::fs::write(&file, b"x").unwrap(); + let ctx = egui::Context::default(); + // Opened (no document, or off the canvas). + let (mut app, _) = app_with(Vec::new()); + app.open_dropped(&ctx, vec![dropped(folder.clone(), Err("read from the path".into())), dropped(file, Err("read from the path".into()))], None); + assert_eq!(doc_names(&app), ["ok.psd"]); + let errors = error_titles(&app); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert!(errors[0].starts_with("Couldn't open Holiday photos: ") && errors[0].contains("folder"), "{errors:?}"); + // On the canvas: not queued for placing, and the layers stay as they were. + let mut app = app_with_canvas(); + let layers = layer_count(&app); + app.open_dropped(&ctx, vec![dropped(folder, Err("read from the path".into()))], Some(egui::pos2(300.0, 300.0))); + assert!(app.drop_places.is_empty()); + app.place_next_dropped(&ctx); + assert_eq!(layer_count(&app), layers); + assert_eq!(app.session.documents().len(), 1); + let errors = error_titles(&app); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert!(errors[0].starts_with("Couldn't place Holiday photos: ") && errors[0].contains("folder"), "{errors:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file that isn't an image is an error the user can read, on either route, not a silent no-op. +#[test] +fn a_dropped_file_that_is_not_an_image_reports_why() { + let dir = scratch("text"); + let file = dir.join("notes.txt"); + std::fs::write(&file, b"bad").unwrap(); + let ctx = egui::Context::default(); + let (mut app, _) = app_with(Vec::new()); + app.open_dropped(&ctx, vec![dropped(file.clone(), Err("read from the path".into()))], None); + assert!(app.session.documents().is_empty()); + assert!(app.ui.status_error); + assert!(error_titles(&app).iter().any(|t| t.starts_with("Couldn't open notes.txt: ")), "{:?}", app.ui.notices); + let mut app = app_with_canvas(); + let layers = layer_count(&app); + app.open_dropped(&ctx, vec![dropped(file, Err("read from the path".into()))], Some(egui::pos2(300.0, 300.0))); + app.place_next_dropped(&ctx); + assert_eq!(layer_count(&app), layers); + assert!(app.ui.status_error); + assert!(error_titles(&app).iter().any(|t| t.starts_with("Couldn't place notes.txt: ")), "{:?}", app.ui.notices); + assert!(app.ui.transform.is_none(), "a failed place starts no Free Transform"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Several files dropped on the canvas together are all queued, in order; a preset file among +/// them goes to its library instead. +#[test] +fn several_files_dropped_on_the_canvas_are_queued_in_order() { + let ctx = egui::Context::default(); + let mut app = app_with_canvas(); + app.open_dropped( + &ctx, + vec![dropped("/pics/one.png", Err("unused".into())), dropped("/pics/set.abr", Err("unused".into())), dropped("/pics/two.jpg", Err("unused".into()))], + Some(egui::pos2(300.0, 300.0)), + ); + let queued: Vec = app + .drop_places + .iter() + .map(|p| match p { + DropPlace::File(f) => dropped_name(f), + DropPlace::Bytes(name, _) => name.clone(), + }) + .collect(); + assert_eq!(queued, ["one.png", "two.jpg"]); +} diff --git a/docs/development.md b/docs/development.md index 3ecefb9f59..2101fced8f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -157,6 +157,8 @@ The desktop app writes its `log` records to standard error and to `logs/photocra By default PhotoCraft's own crates log at `info` and everything else at `warn`. `RUST_LOG` replaces that with env_logger-style directives, for example `RUST_LOG=debug`, `RUST_LOG=warn,photocraft_gpu=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`photocraft*=debug`). The logger is `apps/photocraft/src/logging.rs`; the web build logs to the browser console instead. +A file dragged in from the desktop logs two lines at `info` (`file_open.rs`; file names are left out): `N file(s) dragged over the window` when the drag reaches the window, and `N file(s) dropped on the window: , pointer known|unknown` when it is released. Neither line means the operating system never offered the files to PhotoCraft: on Windows, a PhotoCraft started with Run as administrator gets nothing from a File Explorer that is not elevated, and a drag from a browser or a zip folder carries no file path. Only the first line means PhotoCraft saw the drag but not the drop. Both lines with no document opened mean a routing or open error, which also shows as a notice. + ## Environment variables `photocraft --help` lists the desktop app's flags and, beside the control, automation-root and in-window-menu flags, the variable that stands in for each. A flag wins over its variable and an empty variable counts as unset. A bad flag value is a usage error naming the flag (exit status 2), as is an unknown option, a repeated flag or a flag without its value; a bad value in one of those listed variables is a usage error naming the variable. `PHOTOCRAFT_PRESENT_MODE` and `PHOTOCRAFT_FRAME_LATENCY` are not listed: a bad value there is logged and ignored. On Windows, release builds use the GUI subsystem and have no console, so `--help`, `--version` and usage errors print nothing in a terminal; redirect them to see the text (`photocraft --help | more` or `photocraft --help > help.txt`). The exit status is the same either way.