LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Merge #2701@52ce53622 (photos dropped with no library open wait for one) into round3a-integration
francoisgnedecba5ae899
diff --cc crates/ui-egui/src/drop_overlay.rsindex e8c5d4724,000000000..59aa5bd91mode 100644,000000..100644--- a/crates/ui-egui/src/drop_overlay.rs+++ b/crates/ui-egui/src/drop_overlay.rs@@@ -1,92 -1,0 +1,95 @@@+//! What dropping the files dragged over the window will do: the same sorting the drop applies,+//! shown on a veil over the whole window while the drag lasts.++use egui::{Align2, Color32, Context, Order, Rect, Stroke, StrokeKind, vec2};++use crate::LightcraftApp;+use crate::theme::Tokens;++/// Dropped paths by what becomes of them.+#[derive(Default, Debug, PartialEq)]+pub struct Sorted {+ /// Face models (`.onnx`): the first opens the licence dialog.+ pub models: Vec<String>,+ /// Preset files: imported as presets.+ pub presets: Vec<String>,+ /// Everything else: photos and folders, for the import.+ pub photos: Vec<String>,+}++/// Sort `paths` as a drop does.+pub fn classify(paths: Vec<String>) -> Sorted {+ let (models, rest): (Vec<String>, Vec<String>) = paths.into_iter().partition(|p| crate::is_model_file(p));+ let (presets, photos) = crate::split_presets(rest);+ Sorted { models, presets, photos }+}++/// The lines the card shows for files hovering over the window (`unknown`: how many have no path+/// to look at, as on some platforms and in browsers), for the current settings.+fn lines(app: &LightcraftApp, paths: Vec<String>, unknown: bool) -> Vec<String> {+ if app.ui.dialog.is_some() {+ return vec![crate::i18n::tr("Close the open dialog to drop files here").to_string()];+ }+ let drop = classify(paths);+ let mut out = Vec::new();+ if !drop.models.is_empty() {+ out.push(crate::i18n::tr("Drop to open the face model").to_string());+ }+ let plural = |n: usize| if n == 1 { "" } else { "s" };+ if !drop.presets.is_empty() {+ let n = drop.presets.len();+ out.push(crate::i18n::tr_format!("Drop to import {n} preset{}", plural(n), n = n));+ }- if !drop.photos.is_empty() && app.lightroom.is_some() && !cfg!(target_arch = "wasm32") {++ if !drop.photos.is_empty() && crate::panels::library_problem::holds_drops(app) {++ // no library open yet: they wait for the one chosen (the drop handler holds them)++ out.push(crate::i18n::tr("The photos are imported once a library is open").to_string());++ } else if !drop.photos.is_empty() && app.lightroom.is_some() && !cfg!(target_arch = "wasm32") {+ // the drop is refused while a Lightroom catalog import owns the catalog+ out.push(crate::i18n::tr("Finish Lightroom catalog import before adding photos").to_string());+ } else if !drop.photos.is_empty() && crate::import::running(app) && !cfg!(target_arch = "wasm32") {+ out.push(crate::i18n::tr("An import is running. Drop photos when it has finished").to_string());+ } else if !drop.photos.is_empty() {+ let n = drop.photos.len();+ // the web build has no review to open: its drops import at once+ if app.ui.settings.import_dropped_directly || cfg!(target_arch = "wasm32") {+ out.push(crate::i18n::tr_format!("Drop to import {n} item{}", plural(n), n = n));+ } else {+ out.push(crate::i18n::tr_format!("Drop to review {n} item{} for import", plural(n), n = n));+ }+ }+ if out.is_empty() || unknown {+ out.push(crate::i18n::tr("Drop to import").to_string());+ }+ out+}++/// Veil and card while files are dragged over the window.+pub fn show(app: &LightcraftApp, ctx: &Context) {+ let count = ctx.input(|i| i.raw.hovered_files.len());+ if count == 0 {+ return;+ }+ let known: Vec<String> = ctx.input(|i| {+ i.raw.hovered_files.iter().filter_map(|f| f.path.as_ref()).map(|p| p.to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect()+ });+ let lines = lines(app, known.clone(), known.len() < count);+ let t = Tokens::get(ctx);+ let screen = ctx.content_rect();+ let painter = ctx.layer_painter(egui::LayerId::new(Order::Tooltip, egui::Id::new("drop-overlay")));+ painter.rect_filled(screen, 0.0, Color32::from_black_alpha(150));+ painter.rect_stroke(screen.shrink(10.0), 12.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);+ let galleys: Vec<_> = lines.into_iter().map(|l| painter.layout(l, t.semibold(18.0), t.text, (screen.width() - 120.0).max(200.0))).collect();+ let (w, h) = galleys.iter().fold((0.0f32, 0.0f32), |(w, h), g| (w.max(g.size().x), h + g.size().y + 8.0));+ let card = Rect::from_center_size(screen.center(), vec2(w + 64.0, h + 40.0));+ painter.rect_filled(card, 10.0, t.chrome);+ painter.rect_stroke(card, 10.0, Stroke::new(1.0, t.accent), StrokeKind::Inside);+ let mut y = card.top() + 24.0;+ for g in galleys {+ let at = egui::pos2(card.center().x, y);+ let height = g.size().y;+ painter.galley(Align2::CENTER_TOP.anchor_size(at, g.size()).min, g, t.text);+ y += height + 8.0;+ }+ crate::widgets::register(ctx, "dropOverlay", card);+ ctx.request_repaint();+}diff --cc crates/ui-egui/src/lib.rsindex bf58fc9a9,634771214..f777b3afd--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -1276,51 -1243,30 +1276,53 @@@ impl LightcraftAppshortcuts::handle(self, ctx);}#[cfg(not(target_arch = "wasm32"))]+ self.handle_dropped_files(ctx);+ }++ /// Files dropped on the window: face models open their licence dialog, presets import as+ /// presets, photos and folders go to the import review (or straight in, Settings ▸ Import).+ #[cfg(not(target_arch = "wasm32"))]+ fn handle_dropped_files(&mut self, ctx: &egui::Context) {+ let dropped: Vec<String> =+ ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect());+ if dropped.is_empty() {+ return;+ }+ // a dialog is on screen: the review would replace it, losing what it holds+ if self.ui.dialog.is_some() {+ self.toast(ctx, crate::i18n::tr("Close the open dialog, then drop the files again"));+ return;+ }+ let drop = drop_overlay::classify(dropped);+ if let Some(model) = drop.models.first()+ && let Err(e) = panels::faces::open_dialog(self, model){- let dropped: Vec<String> =- ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_string_lossy().to_string()).filter(|p| !p.is_empty()).collect());- // preset files import as presets, everything else as photos- // a dropped face model opens its licence dialog; presets and photos as before- let (models, dropped): (Vec<String>, Vec<String>) = dropped.into_iter().partition(|p| is_model_file(p));- if let Some(model) = models.first()- && let Err(e) = panels::faces::open_dialog(self, model)- {- self.toast(ctx, e);- }- let (presets, photos) = split_presets(dropped);- if !presets.is_empty() {- let _ = self.run("file.importPresets", serde_json::json!({"paths": presets}));- }+ self.toast(ctx, e);+ }+ if !drop.presets.is_empty() {+ let _ = self.run("file.importPresets", serde_json::json!({"paths": drop.presets}));+ }+ if drop.photos.is_empty() {+ return;+ }++ // no library open yet (the launch list, a library that failed to open): they wait for one++ let Some(photos) = panels::library_problem::hold_dropped(self, ctx, drop.photos) else { return };+ if self.lightroom.is_some() {+ self.toast(ctx, crate::i18n::tr("Finish Lightroom catalog import before adding photos"));+ return;+ }+ if import::running(self) {+ self.toast(ctx, crate::i18n::tr("An import is running"));+ return;+ }+ let started = if self.ui.settings.import_dropped_directly {// read and added on a worker thread (dropped folders can be large, or on a slow drive)- import::start_paths(self, drop.photos).map(|_| ())- let photos = panels::library_problem::hold_dropped(self, ctx, photos).unwrap_or_default();- if !photos.is_empty() {- if self.lightroom.is_some() {- self.toast(ctx, "Finish Lightroom catalog import before adding photos");- } else if let Err(e) = import::start_paths(self, photos) {- self.toast(ctx, e);- }- }++ import::start_paths(self, photos).map(|_| ())+ } else {- import::open(self, drop.photos).map(|_| ())++ import::open(self, photos).map(|_| ())+ };+ if let Err(e) = started {+ self.toast(ctx, e);}}diff --cc crates/ui-egui/src/tests_drop_import.rsindex c82d62278,000000000..d4b362d5bmode 100644,000000..100644--- a/crates/ui-egui/src/tests_drop_import.rs+++ b/crates/ui-egui/src/tests_drop_import.rs@@@ -1,253 -1,0 +1,270 @@@+//! Files dragged from the file manager onto the window: while they hover, the window says what+//! dropping will do; dropping photos or folders opens the import review (unless Settings ▸ Import+//! says to import dropped files directly); a drop while a dialog is open is refused.++use std::time::Duration;++use serde_json::json;++use crate::headless::Headless;+use crate::state::Dialog;+use crate::{LightcraftApp, Services};++const T: Duration = Duration::from_secs(20);+const SETTLE: Duration = Duration::from_secs(120);++/// A scratch folder that goes away with the test, however it ends.+struct Scratch(std::path::PathBuf);++impl Scratch {+ fn new(tag: &str) -> Scratch {+ let dir = std::env::temp_dir().join(format!("lc-ui-drop-import-{tag}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ Scratch(dir)+ }+ fn path(&self, rel: &str) -> String {+ self.0.join(rel).to_string_lossy().to_string()+ }+}++impl Drop for Scratch {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++fn write_png(path: &str, seed: u8) {+ let (w, h) = (24usize, 16usize);+ let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 9) as u8, (i / w * 13) as u8, seed, 255]).collect();+ let img = lightcraft_raster::Rgba8 { width: w, height: h, data };+ let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();+ std::fs::create_dir_all(std::path::Path::new(path).parent().unwrap()).unwrap();+ std::fs::write(path, bytes).unwrap();+}++/// An empty library, a folder `trip` with two photos, a window big enough for the overlay.+fn app(dir: &Scratch) -> Headless {+ write_png(&dir.path("trip/a.png"), 1);+ write_png(&dir.path("trip/b.png"), 2);+ let session = lightcraft_engine::Session::new().with_fs();+ let mut h = Headless::new(LightcraftApp::new(session, Services { png: None, ..Default::default() }), [1300.0, 900.0], 1.0);+ for _ in 0..4 {+ h.step();+ }+ h+}++fn drop_files(h: &mut Headless, paths: &[String], hover: bool) {+ let r = h.request("ui.dropFiles", json!({"paths": paths, "hover": hover}), T);+ assert_eq!(r["ok"], true, "{r}");+ for _ in 0..3 {+ h.step();+ }+}++fn overlay(h: &Headless) -> bool {+ h.app.widgets.iter().any(|(w, _)| w == "dropOverlay")+}++fn said(h: &Headless, word: &str) -> bool {+ h.painted_text().iter().any(|t| t.contains(word))+}++fn photos(h: &Headless) -> usize {+ h.app.session.catalog.photos().count()+}++#[test]+fn hovering_photos_says_they_will_be_reviewed_and_lets_go_when_they_leave() {+ let dir = Scratch::new("hover");+ let mut h = app(&dir);+ assert!(!overlay(&h), "nothing is dragged over the window");+ drop_files(&mut h, &[dir.path("trip/a.png"), dir.path("trip/b.png")], true);+ assert!(overlay(&h), "the window shows where to drop");+ assert!(said(&h, "review 2 items"), "{:?}", h.painted_text());+ drop_files(&mut h, &[], true);+ assert!(!overlay(&h), "the files left the window");+}++#[test]+fn hovering_presets_says_they_will_be_imported_as_presets() {+ let dir = Scratch::new("hover-presets");+ let mut h = app(&dir);+ std::fs::write(dir.path("warm.lcpreset"), "{}").unwrap();+ drop_files(&mut h, &[dir.path("warm.lcpreset")], true);+ assert!(overlay(&h));+ assert!(said(&h, "1 preset"), "{:?}", h.painted_text());+ assert!(!said(&h, "review"), "presets are not reviewed");+}++#[test]+fn hovering_unknown_files_says_only_that_dropping_imports() {+ let dir = Scratch::new("hover-unknown");+ let mut h = app(&dir);+ drop_files(&mut h, &[String::new()], true);+ assert!(overlay(&h));+ assert!(said(&h, "Drop to import"), "{:?}", h.painted_text());+}++#[test]+fn dropping_a_folder_opens_the_import_review_and_imports_nothing_yet() {+ let dir = Scratch::new("review");+ let mut h = app(&dir);+ drop_files(&mut h, &[dir.path("trip")], false);+ assert!(h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens");+ let Some(Dialog::Import { opts }) = &h.app.ui.dialog else { panic!("no import review") };+ assert_eq!(opts.candidates.len(), 2);+ assert_eq!(photos(&h), 0, "nothing is imported until the review is confirmed");+ assert!(!overlay(&h), "the files were let go");+}++#[test]+fn dropping_imports_directly_when_settings_say_so() {+ let dir = Scratch::new("direct");+ let mut h = app(&dir);+ h.app.ui.settings.import_dropped_directly = true;+ drop_files(&mut h, &[dir.path("trip")], false);+ assert!(h.step_until(SETTLE, |h| photos(h) == 2 && h.app.import.is_none()), "both photos arrive");+ assert!(h.app.ui.dialog.is_none(), "no review");+}++#[test]+fn a_drop_while_a_dialog_is_open_leaves_the_dialog_and_imports_nothing() {+ let dir = Scratch::new("dialog");+ let mut h = app(&dir);+ h.app.ui.dialog = Some(Dialog::WhatsNew);+ drop_files(&mut h, &[dir.path("trip/a.png")], true);+ assert!(overlay(&h), "the window still answers the hover");+ assert!(said(&h, "Close the open dialog"), "{:?}", h.painted_text());+ drop_files(&mut h, &[dir.path("trip")], false);+ for _ in 0..30 {+ h.step();+ }+ assert!(matches!(h.app.ui.dialog, Some(Dialog::WhatsNew)), "the open dialog stays");+ assert!(h.app.scan.is_none() && h.app.import.is_none(), "no scan or import started");+ assert_eq!(photos(&h), 0);+ assert!(h.app.ui.toast.is_some(), "the person is told why");+}++/// The scan of a dropped folder finishing while another dialog is open (the face model's licence, Settings…)+/// keeps that dialog; the review opens, with the scan's photos, once it is closed.+#[test]+fn a_finished_scan_waits_for_the_open_dialog_before_opening_the_review() {+ let dir = Scratch::new("waits");+ let mut h = app(&dir);+ crate::import::open(&mut h.app, vec![dir.path("trip")]).unwrap();+ h.app.ui.dialog = Some(Dialog::WhatsNew);+ assert!(h.step_until(SETTLE, |h| h.app.scan.is_none()), "the scan ends");+ for _ in 0..10 {+ h.step();+ }+ assert!(matches!(h.app.ui.dialog, Some(Dialog::WhatsNew)), "the dialog the person had open stays");+ h.app.ui.dialog = None;+ assert!(h.step_until(T, |h| matches!(h.app.ui.dialog, Some(Dialog::Import { .. }))), "the review opens once the dialog is closed");+ let Some(Dialog::Import { opts }) = &h.app.ui.dialog else { panic!("no import review") };+ assert_eq!(opts.candidates.len(), 2, "the scan's photos were kept");+}++/// A drop while an import runs would open a review whose OK replaces the running import: it is+/// refused instead, and the card says so.+#[test]+fn a_drop_while_an_import_runs_is_refused() {+ let dir = Scratch::new("running");+ let mut h = app(&dir);+ write_png(&dir.path("more/c.png"), 3);+ let _scan = crate::import::stall_scan(&mut h.app);+ drop_files(&mut h, &[dir.path("more/c.png")], true);+ assert!(said(&h, "An import is running"), "{:?}", h.painted_text());+ assert!(!said(&h, "review"), "{:?}", h.painted_text());+ drop_files(&mut h, &[dir.path("more")], false);+ for _ in 0..30 {+ h.step();+ }+ assert!(h.app.ui.dialog.is_none(), "no review opened");+ assert!(h.app.scan.is_some() && h.app.import.is_none(), "the running scan was left alone and nothing else started");+ assert!(h.app.ui.toast.is_some(), "the person is told why");+ assert_eq!(photos(&h), 0);+}++/// An import that is running stays the one that runs: a direct drop doesn't start a second.+#[test]+fn a_direct_drop_while_an_import_runs_is_refused_too() {+ let dir = Scratch::new("running-direct");+ let mut h = app(&dir);+ h.app.ui.settings.import_dropped_directly = true;+ write_png(&dir.path("more/c.png"), 3);+ let _scan = crate::import::stall_scan(&mut h.app);+ drop_files(&mut h, &[dir.path("more")], false);+ assert!(h.app.import.is_none(), "no second import");+ assert!(h.app.ui.toast.is_some());+}++/// A Local folder browse scan counts too: a review-first drop would be rejected by `open`, and a+/// direct drop would be replaced when the browse completes.+#[test]+fn a_drop_while_a_browse_scan_runs_is_refused_in_both_modes() {+ for direct in [false, true] {+ let dir = Scratch::new("running-browse");+ let mut h = app(&dir);+ h.app.ui.settings.import_dropped_directly = direct;+ write_png(&dir.path("more/c.png"), 3);+ let _scan = crate::import::stall_scan_of(&mut h.app, true);+ drop_files(&mut h, &[dir.path("more/c.png")], true);+ assert!(said(&h, "An import is running"), "{:?}", h.painted_text());+ drop_files(&mut h, &[dir.path("more")], false);+ for _ in 0..30 {+ h.step();+ }+ assert!(h.app.ui.dialog.is_none() && h.app.import.is_none(), "direct={direct}: nothing started");+ assert!(h.app.scan.is_some(), "the browse was left alone");+ assert!(h.app.ui.toast.is_some(), "the person is told why");+ }+}++/// While a Lightroom catalog import is pending the drop is refused, and the card says so instead of+/// promising a review.+#[test]+fn hovering_photos_while_a_lightroom_import_is_pending_says_they_will_be_refused() {+ let dir = Scratch::new("lightroom");+ let mut h = app(&dir);+ let _task = crate::lightroom_import::stall_import(&mut h.app);+ drop_files(&mut h, &[dir.path("trip")], true);+ assert!(said(&h, "Finish Lightroom catalog import"), "{:?}", h.painted_text());+ assert!(!said(&h, "review"), "{:?}", h.painted_text());+ drop_files(&mut h, &[dir.path("trip")], false);+ assert!(h.app.ui.dialog.is_none(), "no review opened");+ assert!(h.app.ui.toast.is_some(), "the person is told why");+ assert_eq!(photos(&h), 0);+}++/// A script is not told `ok` for the part of a `paths` list that was strings.+#[test]+fn drop_files_with_a_non_string_path_is_rejected_and_drops_nothing() {+ let dir = Scratch::new("badpaths");+ let mut h = app(&dir);+ let r = h.request("ui.dropFiles", json!({"paths": [dir.path("trip"), 7]}), T);+ assert_eq!(r["ok"], false, "{r}");+ for _ in 0..30 {+ h.step();+ }+ assert!(h.app.ui.dialog.is_none(), "nothing was dropped");+ assert_eq!(photos(&h), 0);+}++++/// No library open yet (the window of a library that failed to open, or the launch list): the++/// card says the photos wait, and a drop keeps them for the library chosen instead of importing++/// them into the session that library replaces.++#[test]++fn photos_dropped_with_no_library_open_wait_for_one() {++ let dir = Scratch::new("no-library");++ let mut h = app(&dir);++ h.app.library_problem = Some(crate::panels::library_problem::LibraryProblem::new(dir.path("Gone"), "not found"));++ drop_files(&mut h, &[dir.path("trip/a.png")], true);++ assert!(said(&h, "once a library is open"), "{:?}", h.painted_text());++ drop_files(&mut h, &[], true);++ drop_files(&mut h, &[dir.path("trip/a.png"), dir.path("trip/b.png")], false);++ assert_eq!(h.app.library_problem.as_ref().map(|p| p.pending_import.len()), Some(2));++ assert!(h.app.ui.dialog.is_none() && h.app.import.is_none(), "no review, no import into the temporary session");++ assert_eq!(photos(&h), 0);++}