diff --git a/README.md b/README.md index 53ec908de39..220e1c0a591 100644 --- a/README.md +++ b/README.md @@ -367,7 +367,7 @@ Workspace builds, including the desktop, web and CLI applications, require Rust ```sh git clone https://github.com/storytold/lightcraft && cd lightcraft -cargo run --release -p lightcraft # opens your library (~/Pictures/LightCraft Library; a new one starts with demo photos) +cargo run --release -p lightcraft # opens your library (~/Pictures/LightCraft Library; a new one asks how to begin) cargo run --release -p lightcraft -- ~/Pictures/trip # import your photos (folders are scanned, duplicates skipped) cargo run --release -p lightcraft -- --memory # a throwaway in-memory demo session (writes nothing) cargo run --release -p lightcraft -- --control 7980 # with the automation channel diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 95739b3e973..1cf2f62ea3a 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -4,10 +4,11 @@ //! //! The library (catalog, presets, thumbnail cache) lives in `--library DIR`, else //! `$LIGHTCRAFT_LIBRARY`, else the library last opened with Settings → Open Library…, else -//! `~/Pictures/LightCraft Library`; a new library starts with the -//! procedural demo photos unless `--no-demo` or files are given. Files and folders on the command -//! line are imported (duplicates are skipped). `--memory` runs an in-memory session that writes -//! nothing (demo photos unless files are given; used by the README showcase scripts). A library +//! `~/Pictures/LightCraft Library`; a new library starts empty, and its first screen offers to +//! import photos, a Lightroom catalog, or the procedural sample photos (`library.addSamples`). +//! Files and folders on the command line are imported (duplicates are skipped). `--memory` runs an +//! in-memory session that writes nothing (demo photos unless `--no-demo` or files are given; used +//! by the README showcase scripts). A library //! that can't be opened is never replaced silently: the window says why and asks what to do //! (`lightcraft_ui_egui::panels::library_problem`). //! @@ -61,7 +62,7 @@ impl eframe::App for App { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] if let Some(m) = self.2.as_mut() - && m.update(&mut self.0, ctx) + && m.update(&mut self.0) && lightcraft_ui_egui::panels::notices::may_close(&mut self.0) { // Quit from the menu bar: save exactly what closing the window saves (settings and @@ -744,7 +745,8 @@ fn open_library_session(in_memory: bool, dir: Option, seed_d }; let t0 = std::time::Instant::now(); let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock(); - match s.open_library(&dir, seed_demo) { + // a new library starts empty: its first screen asks how to begin (sample photos are one way) + match s.open_library(&dir, false) { Ok(r) => { let (replayed, torn) = (r.replayed, r.torn_bytes); log::info!( @@ -770,7 +772,7 @@ USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported OPTIONS: --library DIR open (or create) this library (default: ~/Pictures/LightCraft Library; env LIGHTCRAFT_LIBRARY) - --no-demo don't seed a new library with the procedural demo photos + --no-demo with --memory, start without the procedural demo photos --memory throwaway in-memory session (alias --demo); nothing is saved --control PORT serve the JSON-lines control channel on 127.0.0.1:PORT (env LIGHTCRAFT_CONTROL_PORT; see docs/control-protocol.md) diff --git a/apps/lightcraft/src/native_menu.rs b/apps/lightcraft/src/native_menu.rs index 4ac40bcacba..ae9107d8831 100644 --- a/apps/lightcraft/src/native_menu.rs +++ b/apps/lightcraft/src/native_menu.rs @@ -360,7 +360,7 @@ impl NativeMenu { /// accelerators with the app state. Returns whether Quit was chosen: the caller saves /// everything and exits the process itself (closing the viewport while AppKit terminates the /// app can crash in winit's teardown, PR #444). - pub fn update(&mut self, app: &mut LightcraftApp, ctx: &egui::Context) -> bool { + pub fn update(&mut self, app: &mut LightcraftApp) -> bool { lightcraft_ui_egui::i18n::set_language(app.ui.language); let mut quit = false; while let Ok(key) = self.rx.try_recv() { @@ -416,7 +416,8 @@ impl NativeMenu { } walk(&bar.iter().flat_map(|(_, v)| v.clone()).collect::>(), &mut self.items); - let focus = ctx.egui_wants_keyboard_input(); + // a text field has the keyboard (not a focused plain button, such as the welcome's Import) + let focus = app.text_focus; let capturing = app.recording_shortcut.is_some(); if focus != self.text_focus || capturing != self.capturing { self.text_focus = focus; diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 1776c895c1e..023bf53a45f 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -293,6 +293,13 @@ pub struct Catalog { /// Lookups derived from the above (never saved), see [`index`]. #[serde(skip)] index: index::Indexes, + /// How many photos are procedural samples (`Source::Demo`), and how many of those are in the + /// library (not in Recently Deleted): kept as ops change photos, and counted again by + /// [`Catalog::repair`] on load, so asking needs no scan of a large library. + #[serde(skip)] + demo_photos: usize, + #[serde(skip)] + demo_in_library: usize, } /// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a @@ -396,6 +403,19 @@ impl Catalog { pub fn is_empty(&self) -> bool { self.photos.is_empty() } + /// No photo was ever added (photo ids are never reused): a library as it was created. + pub fn never_held_photos(&self) -> bool { + self.next_photo <= 1 + } + /// How many photos are procedural samples (`Source::Demo`), wherever they are (Recently + /// Deleted too). + pub fn sample_photos(&self) -> usize { + self.demo_photos + } + /// How many sample photos are in the library: not in Recently Deleted. + pub fn sample_photos_in_library(&self) -> usize { + self.demo_in_library + } pub fn album(&self, id: AlbumId) -> Option<&Album> { self.albums.get(&id) } @@ -616,12 +636,36 @@ impl Catalog { // the revision was set from outside: what is remembered is of another past self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() }; } - let inv = self.apply_inner(op)?; + let inv = self.apply_counted(op)?; self.revision += 1; self.changes.seen = self.revision; Ok(inv) } + /// [`Catalog::apply_inner`], keeping the counts of sample photos: an op that changes one + /// photo (adds, removes, deletes, restores, re-sources it) changes them by what it did to it. + fn apply_counted(&mut self, op: Op) -> Result { + let id = match &op { + Op::AddPhoto { photo } => Some(photo.id), + Op::RemovePhoto { id } | Op::SetDeleted { id, .. } | Op::SetLocal { id, .. } | Op::Relink { id, .. } | Op::SetFile { id, .. } => { + Some(*id) + } + _ => None, + }; + // (a sample, a sample in the library) for that photo + let state = |c: &Catalog| { + let p = id.and_then(|id| c.photos.get(&id)); + let demo = p.is_some_and(|p| matches!(p.source, Source::Demo { .. })); + (usize::from(demo), usize::from(demo && p.is_some_and(|p| p.in_library()))) + }; + let before = state(self); + let inv = self.apply_inner(op)?; + let after = state(self); + self.demo_photos = (self.demo_photos + after.0).saturating_sub(before.0); + self.demo_in_library = (self.demo_in_library + after.1).saturating_sub(before.1); + Ok(inv) + } + fn apply_inner(&mut self, op: Op) -> Result { // An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind // can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's @@ -957,12 +1001,12 @@ impl Catalog { Op::Batch { ops } => { let mut inverses = Vec::with_capacity(ops.len()); for op in ops { - match self.apply_inner(op) { + match self.apply_counted(op) { Ok(inv) => inverses.push(inv), Err(e) => { // roll back what was applied for inv in inverses.into_iter().rev() { - let _ = self.apply_inner(inv); + let _ = self.apply_counted(inv); } return Err(e); } @@ -1025,6 +1069,8 @@ impl Catalog { /// missing, not a folder or inside itself moves to the top level. Returns what was changed /// (nothing, for a catalog this build wrote). pub fn repair(&mut self) -> Vec { + let demo = || self.photos.values().filter(|p| matches!(p.source, Source::Demo { .. })); + (self.demo_photos, self.demo_in_library) = (demo().count(), demo().filter(|p| p.in_library()).count()); let mut changed = Vec::new(); for (id, p) in self.photos.iter_mut() { if p.id != *id { diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 7b0e1e56203..d5ec8eec2e9 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -910,6 +910,40 @@ pub fn specs() -> Vec { Ok(json!({"deleted": ids.len()})) } ), + cmd!( + "library.addSamples", + "Add Sample Photos", + ["Help"], + None, + "{} → {added} — adds the procedural sample photos and their albums to the library, to try LightCraft on (one undo step)", + no_samples, + |s, _| { + let ops = crate::demo::ops(s); + let added = ops.iter().filter(|o| matches!(o, Op::AddPhoto { .. })).count(); + s.commit("Add Sample Photos", Op::Batch { ops })?; + crate::demo::select_first(s); + Ok(json!({"added": added})) + } + ), + cmd!( + "library.removeSamples", + "Remove Sample Photos", + ["Help"], + None, + "{} → {removed, albums} — removes every sample photo and the albums only they filled; photos of your own and their albums stay (one undo step)", + has_samples, + |s, _| { + let (op, removed, albums) = crate::demo::remove_ops(&s.catalog); + s.commit("Remove Sample Photos", op)?; + // an album that went can't stay on screen (as `album.delete`) + if matches!(s.source, LibrarySource::Album(a) if albums.contains(&a)) { + s.source = LibrarySource::All; + } + s.selection = Selection::default(); + crate::demo::select_first(s); + Ok(json!({"removed": removed, "albums": albums.len()})) + } + ), cmd!("photo.deletePermanently", "Delete Permanently", ["Photo"], None, "{ids?}", has_selection, |s, p| { let before = s.visible_cloned(); let t = s.targets(p)?; @@ -1755,6 +1789,15 @@ mod gps_tests { #[path = "library/tests_relative_ratings.rs"] mod relative_rating_tests; +/// `library.addSamples` is for a library without them. +fn no_samples(s: &Session) -> std::result::Result<(), String> { + if s.has_samples() { Err("the sample photos are already in this library".into()) } else { Ok(()) } +} + +/// `library.removeSamples` needs sample photos to remove. +fn has_samples(s: &Session) -> std::result::Result<(), String> { + if s.has_samples() { Ok(()) } else { Err("this library has no sample photos".into()) } +} #[cfg(test)] #[path = "library/tests_flag_cycle.rs"] mod flag_cycle_tests; diff --git a/crates/engine/src/demo.rs b/crates/engine/src/demo.rs index 431eec76301..7248dbbe42c 100644 --- a/crates/engine/src/demo.rs +++ b/crates/engine/src/demo.rs @@ -2,12 +2,85 @@ use std::sync::Arc; -use lightcraft_catalog::{Album, Flag, Meta, Op, Photo, Source}; +use std::collections::HashSet; + +use lightcraft_catalog::{Album, AlbumId, Catalog, Flag, Meta, Op, Photo, PhotoId, Source}; use lightcraft_develop::DevelopSettings; use crate::Session; +/// Fill the session's catalog with the demo photos and albums directly (no undo step, no +/// journal entry): a new in-memory session, or a new library that asked for them. pub fn load(s: &mut Session) { + for op in ops(s) { + let _ = s.catalog.apply(op); + } + select_first(s); +} + +/// The sample scenes the empty library's welcome shows, as (scene id, title): five landscapes of +/// different colours (a lake at dawn, dunes, an aurora, lavender, a lagoon). +pub fn welcome_scenes() -> Vec<(u32, String)> { + let scenes = lightcraft_scenes::demo_library(); + [1u32, 2, 4, 6, 9].iter().filter_map(|id| scenes.iter().find(|s| s.id == *id).map(|s| (s.id, s.name.clone()))).collect() +} + +/// A sample scene drawn small for the welcome (`max_edge` on its long side), as it looks before +/// any edit. About 25 ms for one at 320 px on all cores: call it off the UI thread. +pub fn scene_preview(scene: u32, max_edge: usize) -> Option { + let scenes = lightcraft_scenes::demo_library(); + let s = scenes.iter().find(|s| s.id == scene)?; + Some(s.render_fit(max_edge.clamp(16, 1024)).to_srgb8()) +} + +/// Select the first photo shown, so there is one to look at. +pub fn select_first(s: &mut Session) { + if let Some(first) = s.visible_cloned().first() { + s.selection = crate::Selection::single(*first); + } +} + +/// What takes the sample photos out: every demo photo (wherever it is: albums, stacks), the +/// albums they alone filled, and the folders that held only such albums. An album that also holds +/// a photo of the person's own stays, with that photo (and a cover that was a sample becomes its +/// first photo left). Returns the op, how many photos go, and the albums that go. +pub fn remove_ops(c: &Catalog) -> (Op, usize, Vec) { + let samples: Vec = c.photos().filter(|p| matches!(p.source, Source::Demo { .. })).map(|p| p.id).collect(); + let gone: HashSet = samples.iter().copied().collect(); + let filled_by_samples = + |a: &Album| !a.folder && a.smart.is_none() && !a.quick && !a.photos.is_empty() && a.photos.iter().all(|p| gone.contains(p)); + let mut albums: Vec = c.albums().filter(|a| filled_by_samples(a)).map(|a| a.id).collect(); + // a folder goes when everything in it goes (bounded: a folder can't hold itself) + let mut changed = true; + let mut rounds = 0; + while changed && rounds < 64 { + rounds += 1; + let emptied: Vec = c + .albums() + .filter(|f| f.folder && f.photos.is_empty() && !albums.contains(&f.id)) + .filter(|f| { + let mut inside = c.albums().filter(|a| a.parent == Some(f.id)).peekable(); + inside.peek().is_some() && inside.all(|a| albums.contains(&a.id)) + }) + .map(|f| f.id) + .collect(); + changed = !emptied.is_empty(); + albums.extend(emptied); + } + let Op::Batch { mut ops } = c.delete_photos_permanently_ops(&samples) else { + return (Op::Batch { ops: Vec::new() }, 0, Vec::new()); + }; + // an album that stays shows one of its own photos, not a removed sample + for a in c.albums().filter(|a| !albums.contains(&a.id) && a.cover.is_some_and(|p| gone.contains(&p))) { + ops.push(Op::SetAlbumCover { id: a.id, cover: a.photos.iter().copied().find(|p| !gone.contains(p)) }); + } + // inner albums before the folders that hold them + ops.extend(albums.iter().map(|id| Op::RemoveAlbum { id: *id })); + (Op::Batch { ops }, samples.len(), albums) +} + +/// The ops that add the demo photos and albums (ids are taken from the catalog). +pub fn ops(s: &mut Session) -> Vec { let scenes = lightcraft_scenes::demo_library(); let mut ids = Vec::new(); let mut ops = Vec::new(); @@ -99,12 +172,7 @@ pub fn load(s: &mut Session) { album: Album { id, name: name.into(), parent, folder: false, photos, cover, smart: None, quick: false, order: None }, }); } - for op in ops { - let _ = s.catalog.apply(op); - } - if let Some(first) = s.visible_cloned().first() { - s.selection = crate::Selection::single(*first); - } + ops } /// Procedural scenes are deterministic but costly to evaluate: every pixel runs the scene's noise diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8a282ce3e93..965ed6526c7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1166,6 +1166,12 @@ impl Session { self.total.as_ref().map(|t| t.1) } + /// The library holds sample (demo) photos, Recently Deleted included. Asked each frame (the + /// samples banner, the Help menu): the catalog keeps the count, so it costs no scan. + pub fn has_samples(&self) -> bool { + self.catalog.sample_photos() > 0 + } + pub fn visible_cloned(&mut self) -> Vec { self.visible().to_vec() } @@ -1300,6 +1306,8 @@ mod tests_process; #[cfg(test)] mod tests_recheck; #[cfg(test)] +mod tests_samples; +#[cfg(test)] mod tests_segment; #[cfg(test)] mod tests_settings_files; diff --git a/crates/engine/src/tests_samples.rs b/crates/engine/src/tests_samples.rs new file mode 100644 index 00000000000..f3318fddf37 --- /dev/null +++ b/crates/engine/src/tests_samples.rs @@ -0,0 +1,169 @@ +//! Sample photos: a new library starts empty and can take the procedural demo photos on request +//! (`library.addSamples`), and they leave together with the albums they filled +//! (`library.removeSamples`). Both are one undo step. + +use std::path::{Path, PathBuf}; + +use lightcraft_catalog::{Op, Source}; +use serde_json::json; + +use crate::Session; + +fn samples(s: &Session) -> usize { + s.catalog.photos().filter(|p| matches!(p.source, Source::Demo { .. })).count() +} + +fn album(s: &Session, name: &str) -> Option { + s.catalog.albums().find(|a| a.name == name).map(|a| a.id) +} + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-samples-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn png(p: &Path) { + let img = lightcraft_raster::Rgba8::from_fn(16, 12, |x, y| [(x * 9) as u8, (y * 11) as u8, 40, 255]); + let b = + crate::export::encode_image(&img, &crate::export::ExportOptions { format: crate::export::ExportFormat::Png, ..Default::default() }).unwrap(); + std::fs::write(p, b).unwrap(); +} + +#[test] +fn sample_photos_come_into_an_empty_library_as_one_undo_step() { + // Given a new, empty library + let mut s = Session::new(); + assert_eq!(s.catalog.len(), 0); + assert!(s.catalog.never_held_photos() && !s.has_samples()); + // When the person asks for the sample photos + let r = s.execute("library.addSamples", &json!({})).unwrap(); + // Then the demo photos and their albums are in, and one is selected to look at + let n = samples(&s); + assert!(n > 0); + assert_eq!(r["added"], n); + assert!(album(&s, "Travel 2026").is_some() && album(&s, "Portfolio").is_some()); + assert!(s.active().is_some()); + assert!(s.has_samples()); + // and one Undo takes them all back out (the library has held photos now, though) + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.len(), 0); + assert_eq!(s.catalog.albums().count(), 0); + assert!(!s.has_samples() && !s.catalog.never_held_photos()); +} + +#[test] +fn sample_photos_are_added_once() { + let mut s = Session::with_demo(); + let err = s.execute("library.addSamples", &json!({})).unwrap_err().to_string(); + assert!(err.contains("already"), "{err}"); +} + +#[test] +fn removing_the_samples_takes_their_albums_and_keeps_the_persons_own() { + // Given the sample photos, and a photo of the person's own put in the sample album Portfolio + let dir = temp_dir("remove"); + png(&dir.join("own.png")); + let mut s = Session::with_demo().with_fs(); + s.execute("library.import", &json!({"paths": [dir.join("own.png").to_string_lossy()]})).unwrap(); + let own = s.catalog.photos().find(|p| matches!(p.source, Source::File { .. })).map(|p| p.id).unwrap(); + let portfolio = album(&s, "Portfolio").unwrap(); + let mut photos = s.catalog.album(portfolio).unwrap().photos.clone(); + photos.push(own); + s.catalog.apply(Op::SetAlbumPhotos { id: portfolio, photos }).unwrap(); + let albums_before = s.catalog.albums().count(); + // When the samples are removed + let r = s.execute("library.removeSamples", &json!({})).unwrap(); + // Then every sample photo is gone, with the albums only they filled (and the folder that held + // them), and the person's photo and the album it is in stay + assert_eq!(samples(&s), 0); + assert!(!s.has_samples()); + assert_eq!(s.catalog.len(), 1); + assert!(s.catalog.photo(own).is_some()); + assert_eq!(s.catalog.album(portfolio).map(|a| a.photos.clone()), Some(vec![own])); + for gone in ["Travel 2026", "Mountains", "Coastlines", "Deserts", "Night Sky", "Garden"] { + assert!(album(&s, gone).is_none(), "{gone} stays"); + } + assert_eq!(r["albums"], albums_before - 1); + assert_eq!(s.catalog.album(portfolio).and_then(|a| a.cover), Some(own), "the cover was a sample"); + // the sample photos' keywords went with them + assert!(s.catalog.photos().all(|p| p.meta.keywords.is_empty())); + // and one Undo brings them all back + s.execute("edit.undo", &json!({})).unwrap(); + assert!(samples(&s) > 0); + assert_eq!(s.catalog.albums().count(), albums_before); +} + +#[test] +fn removing_the_samples_while_one_of_their_albums_is_shown_goes_back_to_all_photos() { + let dir = temp_dir("source"); + png(&dir.join("own.png")); + let mut s = Session::with_demo().with_fs(); + s.execute("library.import", &json!({"paths": [dir.join("own.png").to_string_lossy()]})).unwrap(); + let mountains = album(&s, "Mountains").unwrap(); + s.source = crate::LibrarySource::Album(mountains); + s.execute("library.removeSamples", &json!({})).unwrap(); + assert_eq!(s.source, crate::LibrarySource::All); + assert!(s.active().is_some(), "the photo left is selected"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_catalog_counts_its_sample_photos_as_they_come_and_go() { + // the count the banner and the Help menu ask for each frame, without scanning the library + let mut s = Session::with_demo(); + let n = samples(&s); + assert_eq!(s.catalog.sample_photos(), n); + // an edit doesn't change it; removing and undoing does, both ways + let id = s.catalog.photos().next().map(|p| p.id).unwrap(); + s.catalog.apply(Op::SetRating { id, rating: 2 }).unwrap(); + assert_eq!(s.catalog.sample_photos(), n); + s.execute("library.removeSamples", &json!({})).unwrap(); + assert_eq!(s.catalog.sample_photos(), 0); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.sample_photos(), n); + // and a catalog read back from its snapshot counts them again + let back = lightcraft_catalog::Catalog::from_snapshot(&s.catalog.to_snapshot()).unwrap(); + assert_eq!(back.sample_photos(), n); + assert_eq!(back.sample_photos_in_library(), n); +} + +#[test] +fn samples_in_recently_deleted_are_counted_but_not_as_in_the_library() { + let mut s = Session::with_demo(); + let n = samples(&s); + let ids: Vec<_> = s.catalog.photos().map(|p| p.id).collect(); + s.selection.ids = ids.clone(); + s.execute("photo.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert_eq!(s.catalog.sample_photos(), n, "still in the library's catalog, to remove or restore"); + assert_eq!(s.catalog.sample_photos_in_library(), 0); + let back = lightcraft_catalog::Catalog::from_snapshot(&s.catalog.to_snapshot()).unwrap(); + assert_eq!(back.sample_photos_in_library(), 0); + // restored, they are back in the library + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.sample_photos_in_library(), n); +} + +#[test] +fn removing_samples_from_a_library_without_them_is_refused() { + let mut s = Session::new(); + let err = s.execute("library.removeSamples", &json!({})).unwrap_err().to_string(); + assert!(err.contains("no sample photos"), "{err}"); +} + +#[test] +fn a_new_library_on_disk_starts_empty_unless_samples_are_asked_for() { + let dir = temp_dir("new"); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("plain"), false).unwrap(); + assert_eq!(s.catalog.len(), 0); + // added samples are saved with the library + s.execute("library.addSamples", &json!({})).unwrap(); + let n = samples(&s); + s.close_library().unwrap(); + drop(s); + let mut again = Session::new().with_fs(); + again.open_library(dir.join("plain"), false).unwrap(); + assert_eq!(samples(&again), n); +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 8c3c97427e3..8d86a75a934 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -249,6 +249,9 @@ "• {assumption}": "• {assumption}", "… and {more} more": "… a dalších {more}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.", + "Open the sample photo “{title}”": "Otevřít ukázkovou fotografii „{title}“", + "Press {key} to compare before and after.": "Stisknutím {key} porovnáte stav před a po.", + "Removed {n} sample photos. Edit → Undo brings them back.": "Odebráno ukázkových fotografií: {n}. Úpravy → Zpět je vrátí.", "Create the keyword “{name}”": "Create the keyword “{name}”", "new, inside {parent}": "new, inside {parent}", "Keywords of {n} selected photos": "Keywords of {n} selected photos", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 1e84313aea0..b3676149ffb 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -1113,6 +1113,18 @@ "No photo has it; the keywords below it go too.": "Není přiřazeno žádné fotografii; odstraní se i podřízená klíčová slova.", "No photo selected": "Není vybrána fotografie", "No photos": "Žádné fotografie", + "Welcome to LightCraft": "Vítejte v LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Začněte s vlastními fotografiemi, nebo se nejprve rozhlédněte s ukázkovými fotografiemi. Nic se nezkopíruje ani nepřesune, pokud to sami nezvolíte.", + "Try Sample Photos": "Vyzkoušet ukázkové fotografie", + "Or try LightCraft on a sample photo": "Nebo vyzkoušejte LightCraft na ukázkové fotografii", + "Add Sample Photos": "Přidat ukázkové fotografie", + "Remove Sample Photos": "Odebrat ukázkové fotografie", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "Toto jsou ukázkové fotografie k vyzkoušení LightCraft. Své vlastní importujte, kdykoli budete připraveni.", + "Your photos are in. The sample photos are still here too.": "Vaše fotografie jsou v knihovně. Ukázkové fotografie tu zůstávají také.", + "Drag any slider: the original never changes.": "Posuňte libovolný posuvník: originál se nikdy nezmění.", + "Keep Them": "Ponechat", + "Hide": "Skrýt", + "or look through a folder without importing it, under Local in the sidebar": "nebo si prohlédněte složku bez importu v části Místní soubory v postranním panelu", "No photos found": "Nebyly nalezeny fotografie", "No photos in this folder": "V této složce nejsou fotografie", "No photos match the active filters": "Žádné fotografie neodpovídají aktivním filtrům", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 42245407d2b..d1403eb9e32 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -63,6 +63,9 @@ "Import failed: {e}": "Import fehlgeschlagen: {e}", "Import warnings ({n}):\n{warnings}": "Importwarnungen ({n}):\n{warnings}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Die XMP-Begleitdateien von {n} Fotos konnten nicht geschrieben werden (ist ihr Ordner offline?). LightCraft versucht es weiter.", + "Open the sample photo “{title}”": "Beispielfoto „{title}“ öffnen", + "Press {key} to compare before and after.": "Drücke {key}, um Vorher und Nachher zu vergleichen.", + "Removed {n} sample photos. Edit → Undo brings them back.": "{n} Beispielfotos entfernt. Bearbeiten → Rückgängig holt sie zurück.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "XMP-Profil \"{profile}\" wurde für {path} nicht angewendet; Farben können von Lightroom abweichen.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Lightroom-Geometrie wurde für {path} nicht beibehalten; {mode} wird neu berechnet.", "Lightroom geometry for {path} was not preserved; saved transform is ignored because Upright is Off.": "Lightroom-Geometrie für {path} wurde nicht beibehalten; gespeicherte Transformation wird ignoriert, weil Upright deaktiviert ist.", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index 000aea2d450..07af5ee4c45 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -979,8 +979,20 @@ "No photo selected": "Kein Foto ausgewählt", "No photos": "Keine Fotos", "Your library is empty": "Deine Bibliothek ist leer", + "Welcome to LightCraft": "Willkommen bei LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Beginne mit deinen eigenen Fotos oder sieh dich zuerst mit einigen Beispielfotos um. Nichts wird kopiert oder verschoben, außer du wählst es.", + "Try Sample Photos": "Beispielfotos ausprobieren", + "Or try LightCraft on a sample photo": "Oder probiere LightCraft an einem Beispielfoto aus", + "Add Sample Photos": "Beispielfotos hinzufügen", + "Remove Sample Photos": "Beispielfotos entfernen", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "Das sind Beispielfotos zum Ausprobieren von LightCraft. Importiere deine eigenen, wann immer du so weit bist.", + "Your photos are in. The sample photos are still here too.": "Deine Fotos sind da. Die Beispielfotos sind noch immer hier.", + "Drag any slider: the original never changes.": "Ziehe an einem beliebigen Regler: Das Original ändert sich nie.", + "Keep Them": "Behalten", + "Hide": "Ausblenden", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Importierte Fotos erscheinen hier. Nichts wird kopiert oder verschoben, außer du wählst es.", "or drop photos and folders into this window": "oder ziehe Fotos und Ordner in dieses Fenster", + "or look through a folder without importing it, under Local in the sidebar": "oder sieh dir einen Ordner an, ohne ihn zu importieren: unter „Lokal“ in der Seitenleiste", "Import photos to get started": "Importiere Fotos, um loszulegen", "or drop photos into this window": "oder ziehe Fotos in dieses Fenster", "No photos found": "Keine Fotos gefunden", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 5ea0e969afa..0fe67caeaad 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -63,6 +63,9 @@ "Import failed: {e}": "Error de importación: {e}", "Import warnings ({n}):\n{warnings}": "Avisos de importación ({n}):\n{warnings}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "No se pudieron escribir los archivos XMP de {n} fotos (¿su carpeta está desconectada?). LightCraft lo sigue intentando.", + "Open the sample photo “{title}”": "Abrir la foto de muestra «{title}»", + "Press {key} to compare before and after.": "Pulsa {key} para comparar el antes y el después.", + "Removed {n} sample photos. Edit → Undo brings them back.": "Se quitaron {n} fotos de muestra. Edición → Deshacer las recupera.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "El perfil XMP \"{profile}\" no se aplicó a {path}; los colores pueden diferir de Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "La geometría de Lightroom no se conservó para {path}; {mode} se recalculará.", "Lightroom geometry for {path} was not preserved; saved transform is ignored because Upright is Off.": "La geometría de Lightroom no se conservó para {path}; la transformación guardada se ignora porque Vertical está desactivado.", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 77ba4c08eab..b2a04499002 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -986,8 +986,20 @@ "No photo selected": "No hay ninguna foto seleccionada", "No photos": "Sin fotos", "Your library is empty": "Tu biblioteca está vacía", + "Welcome to LightCraft": "Te damos la bienvenida a LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Empieza con tus propias fotos o explora primero con un conjunto de fotos de muestra. No se copia ni se mueve nada a menos que lo elijas.", + "Try Sample Photos": "Probar con fotos de muestra", + "Or try LightCraft on a sample photo": "O prueba LightCraft con una foto de muestra", + "Add Sample Photos": "Añadir fotos de muestra", + "Remove Sample Photos": "Quitar fotos de muestra", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "Son fotos de muestra para probar LightCraft. Importa las tuyas cuando quieras.", + "Your photos are in. The sample photos are still here too.": "Tus fotos ya están aquí. Las fotos de muestra también siguen.", + "Drag any slider: the original never changes.": "Arrastra cualquier control deslizante: el original nunca cambia.", + "Keep Them": "Conservarlas", + "Hide": "Ocultar", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Las fotos que importes aparecen aquí. No se copia ni se mueve nada a menos que lo elijas.", "or drop photos and folders into this window": "o arrastra fotos y carpetas a esta ventana", + "or look through a folder without importing it, under Local in the sidebar": "o mira una carpeta sin importarla, en «Local» en la barra lateral", "Import photos to get started": "Importa fotos para empezar", "or drop photos into this window": "o arrastra fotos a esta ventana", "No photos found": "No se encontraron fotos", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 1ecd4c4b226..97466ba3696 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -67,6 +67,9 @@ "Imported {n} preset{}, {f} file{} not readable": "{n} préréglage{} importé(s), {f} fichier{} illisible(s)", "Imported {profiles} profile{} (Profile browser ▸ their groups)": "{profiles} profil{} importé(s) (Navigateur de profils → leurs groupes)", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Les fichiers annexes XMP de {n} photos n'ont pas pu être écrits (leur dossier est-il hors ligne ?). LightCraft continue d'essayer.", + "Open the sample photo “{title}”": "Ouvrir la photo d’exemple « {title} »", + "Press {key} to compare before and after.": "Appuyez sur {key} pour comparer avant et après.", + "Removed {n} sample photos. Edit → Undo brings them back.": "{n} photos d’exemple retirées. Édition → Annuler les rétablit.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Le profil XMP « {profile} » n’a pas été appliqué à {path} ; les couleurs peuvent différer de Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "La géométrie Lightroom de {path} n’a pas été conservée ; {mode} sera recalculé.", "Lightroom geometry for {path} was not preserved; saved transform is ignored because Upright is Off.": "La géométrie Lightroom de {path} n’a pas été conservée ; la transformation enregistrée est ignorée, car Upright est désactivé.", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index fa57e373e38..388ee3da234 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -931,8 +931,20 @@ "No photo selected": "Aucune photo sélectionnée", "No photos": "Aucune photo", "Your library is empty": "Votre bibliothèque est vide", + "Welcome to LightCraft": "Bienvenue dans LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Commencez avec vos propres photos, ou découvrez d’abord l’application avec des photos d’exemple. Rien n’est copié ni déplacé, sauf si vous le choisissez.", + "Try Sample Photos": "Essayer avec des photos d’exemple", + "Or try LightCraft on a sample photo": "Ou essayez LightCraft sur une photo d’exemple", + "Add Sample Photos": "Ajouter les photos d’exemple", + "Remove Sample Photos": "Retirer les photos d’exemple", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "Ce sont des photos d’exemple pour essayer LightCraft. Importez les vôtres quand vous voulez.", + "Your photos are in. The sample photos are still here too.": "Vos photos sont là. Les photos d’exemple y sont toujours.", + "Drag any slider: the original never changes.": "Faites glisser n’importe quel curseur : l’original ne change jamais.", + "Keep Them": "Les garder", + "Hide": "Masquer", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Les photos importées apparaissent ici. Rien n’est copié ni déplacé, sauf si vous le choisissez.", "or drop photos and folders into this window": "ou déposez des photos et des dossiers dans cette fenêtre", + "or look through a folder without importing it, under Local in the sidebar": "ou parcourez un dossier sans l’importer, sous « Local » dans la barre latérale", "Import photos to get started": "Importez des photos pour commencer", "or drop photos into this window": "ou déposez des photos dans cette fenêtre", "No photos found": "Aucune photo trouvée", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 8edab510abd..ff3bf4c6e15 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -268,6 +268,9 @@ "Skipped {problem}": "Skipped {problem}", "Updated {name}": "Updated {name}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.", + "Open the sample photo “{title}”": "Apri la foto di esempio “{title}”", + "Press {key} to compare before and after.": "Premi {key} per confrontare prima e dopo.", + "Removed {n} sample photos. Edit → Undo brings them back.": "Rimosse {n} foto di esempio. Modifica → Annulla le ripristina.", "Apply to “{mask}” on Selected Photos": "Apply to “{mask}” on Selected Photos", "Update “{name}” with Current Settings": "Update “{name}” with Current Settings", "Slideshow exported: {what}": "Slideshow exported: {what}", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 382fb80c9f8..a5e1d298026 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -911,6 +911,18 @@ "No new presets": "Nessun nuovo preset", "No photo selected": "Nessuna foto selezionata", "No photos": "Nessuna foto", + "Welcome to LightCraft": "Benvenuto in LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Inizia con le tue foto, oppure dai prima un'occhiata con una serie di foto di esempio. Niente viene copiato o spostato, a meno che tu non lo scelga.", + "Try Sample Photos": "Prova le foto di esempio", + "Or try LightCraft on a sample photo": "Oppure prova LightCraft su una foto di esempio", + "Add Sample Photos": "Aggiungi foto di esempio", + "Remove Sample Photos": "Rimuovi le foto di esempio", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "Queste sono foto di esempio per provare LightCraft. Importa le tue quando vuoi.", + "Your photos are in. The sample photos are still here too.": "Le tue foto sono arrivate. Ci sono ancora anche le foto di esempio.", + "Drag any slider: the original never changes.": "Trascina un cursore qualsiasi: l'originale non cambia mai.", + "Keep Them": "Tienile", + "Hide": "Nascondi", + "or look through a folder without importing it, under Local in the sidebar": "oppure sfoglia una cartella senza importarla, in Locale nella barra laterale", "No photos found": "Nessuna foto trovata", "No photos in this folder": "Nessuna foto in questa cartella", "No photos match the active filters": "Nessuna foto corrisponde ai filtri attivi", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 616c150cfdc..e84919a9a68 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -46,8 +46,10 @@ "Move {what} to Recently Deleted?": "{what}を「最近削除した写真」に移動しますか?", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n}枚を「{1}」に移動しました。編集 → 取り消す で元に戻せます。{0:.0}", "Named ({named_n})": "名前付き({named_n})", + "Open the sample photo “{title}”": "サンプル写真「{title}」を開く", "Paste into {n} photo{} — only settings that were copied are pasted": "{n}枚に貼り付け{:.0}(コピーされた設定だけを適用)", "Preset: {name}": "プリセット:{name}", + "Press {key} to compare before and after.": "{key} を押すと補正前と補正後を比較できます。", "Preview only — editing the camera's embedded JPEG ({})": "プレビューのみ:カメラ内蔵のJPEGを編集中({})", "Preview only — {}": "プレビューのみ:{}", "Profile: {}": "プロファイル:{}", @@ -60,6 +62,7 @@ "Redo {}": "やり直す:{}", "Remove “{}” from Favorites": "「{}」をお気に入りから削除", "Removed from {}": "{} から削除しました", + "Removed {n} sample photos. Edit → Undo brings them back.": "サンプル写真を{n}枚削除しました。編集 → 取り消すで元に戻せます。", "Rename {n} Photos…": "{n}枚の写真の名前を変更…", "Rename “{name}”": "「{name}」の名前を変更", "Rendering on the CPU: {why}": "CPUで描画:{why}", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 2dc80934f5b..77074ec578e 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -982,8 +982,20 @@ "No photo selected": "写真が選択されていません", "No photos": "写真がありません", "Your library is empty": "ライブラリは空です", + "Welcome to LightCraft": "LightCraftへようこそ", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "自分の写真で始めるか、まずサンプル写真で試してみましょう。選択しない限り、コピーや移動は行われません。", + "Try Sample Photos": "サンプル写真で試す", + "Or try LightCraft on a sample photo": "または、サンプル写真で LightCraft を試す", + "Add Sample Photos": "サンプル写真を追加", + "Remove Sample Photos": "サンプル写真を削除", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "LightCraftを試すためのサンプル写真です。準備ができたら自分の写真を読み込みましょう。", + "Your photos are in. The sample photos are still here too.": "写真が読み込まれました。サンプル写真もまだ残っています。", + "Drag any slider: the original never changes.": "どのスライダーでもドラッグしてみましょう。元の写真は変わりません。", + "Keep Them": "残す", + "Hide": "隠す", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "読み込んだ写真はここに表示されます。選択しない限り、コピーや移動は行われません。", "or drop photos and folders into this window": "または写真やフォルダーをこのウィンドウにドロップ", + "or look through a folder without importing it, under Local in the sidebar": "または、読み込まずにフォルダーを見る:サイドバーの「ローカル」から", "Import photos to get started": "写真を読み込んで始めましょう", "or drop photos into this window": "または写真をこのウィンドウにドロップ", "No photos found": "写真が見つかりません", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 9b08b0d5dc4..5b149adf6ce 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -274,6 +274,9 @@ "Slideshow exported: {what}": "Slideshow exported: {what}", "Template preview: {name}": "Template preview: {name}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.", + "Open the sample photo “{title}”": "სანიმუშო ფოტოს „{title}“ გახსნა", + "Press {key} to compare before and after.": "დააჭირეთ {key}-ს „მანამდე“ და „შემდეგ“ შესადარებლად.", + "Removed {n} sample photos. Edit → Undo brings them back.": "წაიშალა {n} სანიმუშო ფოტო. რედაქტირება → გაუქმება მათ დააბრუნებს.", "Update “{name}” with Current Settings": "Update “{name}” with Current Settings", "Updated {name}": "Updated {name}", "new, inside {parent}": "new, inside {parent}", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index bafd7827ce7..441c0f46a94 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -1353,6 +1353,18 @@ "No photo has it; the keywords below it go too.": "არცერთ ფოტოს არ აქვს; მასში ჩადგმული საკვანძო სიტყვებიც წაიშლება.", "No photo selected": "ფოტო არ არის მონიშნული", "No photos": "ფოტოები არ არის", + "Welcome to LightCraft": "კეთილი იყოს თქვენი მობრძანება LightCraft-ში", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "დაიწყეთ საკუთარი ფოტოებით ან ჯერ სანიმუშო ფოტოებით გაეცანით. არაფერი დაკოპირდება ან გადაიტანება, თუ თავად არ აირჩევთ.", + "Try Sample Photos": "სანიმუშო ფოტოების ცდა", + "Or try LightCraft on a sample photo": "ან სცადეთ LightCraft ნიმუშ ფოტოზე", + "Add Sample Photos": "სანიმუშო ფოტოების დამატება", + "Remove Sample Photos": "სანიმუშო ფოტოების მოშორება", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "ეს სანიმუშო ფოტოებია LightCraft-ის გასაცნობად. საკუთარი ფოტოების იმპორტი შეგიძლიათ, როცა მზად იქნებით.", + "Your photos are in. The sample photos are still here too.": "თქვენი ფოტოები დაემატა. სანიმუშო ფოტოებიც ჯერ კიდევ აქ არის.", + "Drag any slider: the original never changes.": "გადაათრიეთ ნებისმიერი სლაიდერი: ორიგინალი არასოდეს იცვლება.", + "Keep Them": "დატოვება", + "Hide": "დამალვა", + "or look through a folder without importing it, under Local in the sidebar": "ან დაათვალიერეთ საქაღალდე იმპორტის გარეშე, გვერდითი ზოლის „ლოკალურ“ განყოფილებაში", "No photos found": "ფოტოები ვერ მოიძებნა", "No photos in this folder": "ამ საქაღალდეში ფოტოები არ არის", "No photos match the active filters": "აქტიურ ფილტრებს არცერთი ფოტო არ შეესაბამება", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 1886098df58..babfad4fcc4 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -280,6 +280,9 @@ " · {n} skipped (could not be rendered)": " · {n} skipped (could not be rendered)", "{n} raws can now be developed from their raw data": "{n} raws can now be developed from their raw data", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.", + "Open the sample photo “{title}”": "Otwórz przykładowe zdjęcie „{title}”", + "Press {key} to compare before and after.": "Naciśnij {key}, aby porównać przed i po.", + "Removed {n} sample photos. Edit → Undo brings them back.": "Usunięto przykładowe zdjęcia ({n}). Edycja → Cofnij je przywróci.", "Create the keyword “{name}”": "Create the keyword “{name}”", "new, inside {parent}": "new, inside {parent}", "Keywords of {n} selected photos": "Keywords of {n} selected photos", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index 7416ce2410f..4adac910047 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -913,6 +913,18 @@ "No new presets": "Brak nowych ustawień predefiniowanych", "No photo selected": "Nie wybrano zdjęcia", "No photos": "Brak zdjęć", + "Welcome to LightCraft": "Witamy w LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Zacznij od własnych zdjęć albo najpierw rozejrzyj się na przykładowych zdjęciach. Nic nie zostanie skopiowane ani przeniesione, chyba że tak wybierzesz.", + "Try Sample Photos": "Wypróbuj przykładowe zdjęcia", + "Or try LightCraft on a sample photo": "Albo wypróbuj LightCraft na przykładowym zdjęciu", + "Add Sample Photos": "Dodaj przykładowe zdjęcia", + "Remove Sample Photos": "Usuń przykładowe zdjęcia", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "To są przykładowe zdjęcia do wypróbowania LightCraft. Zaimportuj własne, kiedy tylko zechcesz.", + "Your photos are in. The sample photos are still here too.": "Twoje zdjęcia już są. Przykładowe zdjęcia też nadal tu są.", + "Drag any slider: the original never changes.": "Przeciągnij dowolny suwak: oryginał nigdy się nie zmienia.", + "Keep Them": "Zachowaj je", + "Hide": "Ukryj", + "or look through a folder without importing it, under Local in the sidebar": "albo przejrzyj folder bez importowania, w sekcji Lokalne na pasku bocznym", "No photos found": "Nie znaleziono zdjęć", "No photos in this folder": "W tym folderze nie ma zdjęć", "No photos match the active filters": "Żadne zdjęcia nie spełniają aktywnych filtrów", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index 2b17909ad39..4252c84964e 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -63,8 +63,10 @@ "Move {what} to Recently Deleted?": "Mover {what} para Excluídos recentemente?", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "{n} foto{0} movida{0} para “{1}”. Editar → Desfazer as traz de volta.", "Named ({named_n})": "Nomeadas ({named_n})", + "Open the sample photo “{title}”": "Abrir a foto de exemplo “{title}”", "Paste into {n} photo{} — only settings that were copied are pasted": "Colar em {n} foto{} — somente os ajustes copiados são colados", "Preset: {name}": "Predefinição: {name}", + "Press {key} to compare before and after.": "Pressione {key} para comparar o antes e o depois.", "Preview only — editing the camera's embedded JPEG ({})": "Somente pré-visualização — editando o JPEG incorporado da câmera ({})", "Preview only — {}": "Somente pré-visualização — {}", "Profile: {}": "Perfil: {}", @@ -80,6 +82,7 @@ "Remove “{name}” and its {count} photo{} from the library?": "Remover “{name}” e {count} foto{} da biblioteca?", "Remove “{}” from Favorites": "Remover “{}” dos favoritos", "Removed from {}": "Removido de {}", + "Removed {n} sample photos. Edit → Undo brings them back.": "{n} fotos de exemplo removidas. Editar → Desfazer as traz de volta.", "Rename {n} Photos…": "Renomear {n} fotos…", "Rename “{name}”": "Renomear “{name}”", "Rendering on the CPU: {why}": "Renderizando na CPU: {why}", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 85a0ae03912..5c6fdd7394e 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -943,8 +943,20 @@ "No photo selected": "Nenhuma foto selecionada", "No photos": "Sem fotos", "Your library is empty": "Sua biblioteca está vazia", + "Welcome to LightCraft": "Boas-vindas ao LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Comece com suas próprias fotos ou explore primeiro com um conjunto de fotos de exemplo. Nada é copiado ou movido, a menos que você escolha.", + "Try Sample Photos": "Experimentar com fotos de exemplo", + "Or try LightCraft on a sample photo": "Ou experimente o LightCraft com uma foto de exemplo", + "Add Sample Photos": "Adicionar fotos de exemplo", + "Remove Sample Photos": "Remover fotos de exemplo", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "Estas são fotos de exemplo para experimentar o LightCraft. Importe as suas quando quiser.", + "Your photos are in. The sample photos are still here too.": "Suas fotos chegaram. As fotos de exemplo ainda estão aqui.", + "Drag any slider: the original never changes.": "Arraste qualquer controle deslizante: o original nunca muda.", + "Keep Them": "Manter", + "Hide": "Ocultar", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "As fotos que você importar aparecem aqui. Nada é copiado ou movido, a menos que você escolha.", "or drop photos and folders into this window": "ou arraste fotos e pastas para esta janela", + "or look through a folder without importing it, under Local in the sidebar": "ou veja uma pasta sem importá-la, em “Local” na barra lateral", "Import photos to get started": "Importe fotos para começar", "or drop photos into this window": "ou arraste fotos para esta janela", "No photos found": "Nenhuma foto encontrada", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 55d5671aa47..e73d21058b0 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -66,6 +66,9 @@ "Import failed: {e}": "Ошибка импорта: {e}", "Import warnings ({n}):\n{warnings}": "Предупреждения импорта ({n}):\n{warnings}", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Не удалось записать XMP-файлы {n} фото (папка недоступна?). LightCraft продолжает попытки.", + "Open the sample photo “{title}”": "Открыть пример фото «{title}»", + "Press {key} to compare before and after.": "Нажмите {key}, чтобы сравнить до и после.", + "Removed {n} sample photos. Edit → Undo brings them back.": "Удалено примеров фото: {n}. Правка → Отменить вернёт их.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Профиль XMP \"{profile}\" не применён к {path}; цвета могут отличаться от Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Геометрия Lightroom для {path} не сохранена; режим {mode} будет пересчитан.", "Lightroom geometry for {path} was not preserved; saved transform is ignored because Upright is Off.": "Геометрия Lightroom для {path} не сохранена; сохранённое преобразование игнорируется, поскольку Upright выключен.", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 5ead5101f5c..0bf878cf457 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -783,8 +783,20 @@ "No photo selected": "Фото не выбрано", "No photos": "Нет фото", "Your library is empty": "Библиотека пуста", + "Welcome to LightCraft": "Добро пожаловать в LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Начните со своих фото или сначала осмотритесь на примерах фото. Ничего не копируется и не перемещается, пока вы сами этого не выберете.", + "Try Sample Photos": "Попробовать на примерах", + "Or try LightCraft on a sample photo": "Или попробуйте LightCraft на примере фото", + "Add Sample Photos": "Добавить примеры фото", + "Remove Sample Photos": "Удалить примеры фото", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "Это примеры фото, чтобы попробовать LightCraft. Импортируйте свои, когда будете готовы.", + "Your photos are in. The sample photos are still here too.": "Ваши фото добавлены. Примеры фото пока тоже здесь.", + "Drag any slider: the original never changes.": "Потяните любой ползунок: оригинал никогда не меняется.", + "Keep Them": "Оставить", + "Hide": "Скрыть", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Импортированные фото появятся здесь. Ничего не копируется и не перемещается, пока вы сами этого не выберете.", "or drop photos and folders into this window": "или перетащите фото и папки в это окно", + "or look through a folder without importing it, under Local in the sidebar": "или просмотрите папку без импорта: в разделе «Локальное» на боковой панели", "Import photos to get started": "Импортируйте фото, чтобы начать", "or drop photos into this window": "или перетащите фото в это окно", "No photos found": "Фото не найдены", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 4cf3dc80bf1..ee20c3d1fe3 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -67,6 +67,9 @@ "Imported {n} preset{}, {f} file{} not readable": "Імпортовано наборів налаштувань: {n}{:.0}, файлів не читається: {f}{:.0}", "Imported {profiles} profile{} (Profile browser ▸ their groups)": "Імпортовано профілів: {profiles}{:.0} (Оглядач профілів → їхні групи)", "The XMP sidecars of {n} photos couldn't be written (is their folder offline?). LightCraft keeps trying.": "Не вдалося записати XMP-файли {n} фото (папка недоступна?). LightCraft продовжує спроби.", + "Open the sample photo “{title}”": "Відкрити зразок фото «{title}»", + "Press {key} to compare before and after.": "Натисніть {key}, щоб порівняти до і після.", + "Removed {n} sample photos. Edit → Undo brings them back.": "Вилучено зразків фото: {n}. Редагування → Скасувати поверне їх.", "XMP profile \"{profile}\" was not applied for {path}; colors may differ from Lightroom.": "Профіль XMP «{profile}» не застосовано до {path}; кольори можуть відрізнятися від Lightroom.", "Lightroom geometry was not preserved for {path}; {mode} will be recalculated.": "Геометрію Lightroom для {path} не збережено; режим {mode} буде перераховано.", "Lightroom geometry for {path} was not preserved; saved transform is ignored because Upright is Off.": "Геометрію Lightroom для {path} не збережено; збережене перетворення ігнорується, оскільки Upright вимкнено.", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index fbdef1c5f7c..a95802bc592 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -1121,8 +1121,20 @@ "No photo selected": "Фото не вибрано", "No photos": "Немає фото", "Your library is empty": "Бібліотека порожня", + "Welcome to LightCraft": "Ласкаво просимо до LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "Почніть із власних фото або спершу роздивіться на зразках фото. Нічого не копіюється й не переміщується, доки ви самі цього не оберете.", + "Try Sample Photos": "Спробувати на зразках", + "Or try LightCraft on a sample photo": "Або спробуйте LightCraft на зразку фото", + "Add Sample Photos": "Додати зразки фото", + "Remove Sample Photos": "Вилучити зразки фото", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "Це зразки фото, щоб спробувати LightCraft. Імпортуйте свої, коли будете готові.", + "Your photos are in. The sample photos are still here too.": "Ваші фото додано. Зразки фото поки теж тут.", + "Drag any slider: the original never changes.": "Потягніть будь-який повзунок: оригінал ніколи не змінюється.", + "Keep Them": "Залишити", + "Hide": "Сховати", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "Імпортовані фото з’являться тут. Нічого не копіюється й не переміщується, доки ви самі цього не оберете.", "or drop photos and folders into this window": "або перетягніть фото й теки в це вікно", + "or look through a folder without importing it, under Local in the sidebar": "або перегляньте теку без імпорту: у розділі «Локальні» на бічній панелі", "Import photos to get started": "Імпортуйте фото, щоб почати", "or drop photos into this window": "або перетягніть фото в це вікно", "No photos found": "Фото не знайдено", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 0d96d2960d9..4ca2d056aea 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -46,8 +46,10 @@ "Move {what} to Recently Deleted?": "将 {what} 移到最近删除?", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "已将 {n} 张照片移到“{1}”{0:.0}。编辑 → 撤销 可移回。", "Named ({named_n})": "已命名({named_n})", + "Open the sample photo “{title}”": "打开示例照片“{title}”", "Paste into {n} photo{} — only settings that were copied are pasted": "粘贴到 {n} 张照片 — 仅粘贴已复制的设置{0:.0}", "Preset: {name}": "预设:{name}", + "Press {key} to compare before and after.": "按 {key} 对比调整前后。", "Preview only — editing the camera's embedded JPEG ({})": "仅预览 — 正在编辑相机内嵌的 JPEG({0})", "Preview only — {}": "仅预览 — {0}", "Profile: {}": "配置文件:{0}", @@ -60,6 +62,7 @@ "Redo {}": "重做:{0}", "Remove “{}” from Favorites": "从收藏夹中移除“{0}”", "Removed from {}": "已从 {} 移除", + "Removed {n} sample photos. Edit → Undo brings them back.": "已移除 {n} 张示例照片。编辑 → 撤销可恢复。", "Rename {n} Photos…": "重命名 {n} 张照片…", "Rename “{name}”": "重命名“{name}”", "Rendering on the CPU: {why}": "正在使用 CPU 渲染:{why}", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 2750dd4c834..a2882866b2e 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -1004,8 +1004,20 @@ "No photo selected": "未选择照片", "No photos": "没有照片", "Your library is empty": "图库是空的", + "Welcome to LightCraft": "欢迎使用 LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "从你自己的照片开始,或先用一组示例照片四处看看。除非你选择,否则不会复制或移动任何文件。", + "Try Sample Photos": "用示例照片试试", + "Or try LightCraft on a sample photo": "或用一张示例照片试试 LightCraft", + "Add Sample Photos": "添加示例照片", + "Remove Sample Photos": "移除示例照片", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "这些是用来试用 LightCraft 的示例照片。准备好后随时导入你自己的照片。", + "Your photos are in. The sample photos are still here too.": "你的照片已导入。示例照片也还在。", + "Drag any slider: the original never changes.": "拖动任意滑块:原片永远不会改变。", + "Keep Them": "保留", + "Hide": "隐藏", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "导入的照片会显示在这里。除非你选择,否则不会复制或移动任何文件。", "or drop photos and folders into this window": "或将照片和文件夹拖放到此窗口", + "or look through a folder without importing it, under Local in the sidebar": "或不导入直接浏览文件夹:在侧边栏的“本地”中", "Import photos to get started": "导入照片以开始使用", "or drop photos into this window": "或将照片拖放到此窗口", "No photos found": "未找到照片", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index 7128165f524..e79755aeaad 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -60,8 +60,10 @@ "Move {what} to Recently Deleted?": "要將{what}移至「最近刪除」嗎?", "Moved {n} photo{} to “{}”. Edit → Undo moves them back.": "已將 {n} 張照片移到「{1}」{0:.0}。編輯 → 復原 可移回。", "Named ({named_n})": "已命名({named_n})", + "Open the sample photo “{title}”": "開啟範例照片「{title}」", "Paste into {n} photo{} — only settings that were copied are pasted": "貼上至 {n} 張照片{:.0} — 只貼上已複製的設定", "Preset: {name}": "預設集:{name}", + "Press {key} to compare before and after.": "按 {key} 比較調整前後。", "Preview only — editing the camera's embedded JPEG ({})": "僅供預覽 — 正在編輯相機內嵌的 JPEG({})", "Preview only — {}": "僅供預覽 — {}", "Profile: {}": "描述檔:{}", @@ -76,6 +78,7 @@ "Redo {}": "重做 {}", "Remove “{}” from Favorites": "將「{}」從喜好項目移除", "Removed from {}": "已從 {} 移除", + "Removed {n} sample photos. Edit → Undo brings them back.": "已移除 {n} 張範例照片。編輯 → 復原可還原。", "Rename {n} Photos…": "重新命名 {n} 張照片…", "Rename “{name}”": "重新命名「{name}」", "Rendering on the CPU: {why}": "使用 CPU 算繪:{why}", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 19c7bc3385b..e652d95f446 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -1004,8 +1004,20 @@ "No photo selected": "尚未選取照片", "No photos": "沒有照片", "Your library is empty": "照片庫是空的", + "Welcome to LightCraft": "歡迎使用 LightCraft", + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to.": "從你自己的照片開始,或先用一組範例照片四處看看。除非你選擇,否則不會複製或移動任何檔案。", + "Try Sample Photos": "用範例照片試試", + "Or try LightCraft on a sample photo": "或用一張範例照片試試 LightCraft", + "Add Sample Photos": "加入範例照片", + "Remove Sample Photos": "移除範例照片", + "These are sample photos, to try LightCraft on. Import your own whenever you're ready.": "這些是用來試用 LightCraft 的範例照片。準備好後隨時匯入你自己的照片。", + "Your photos are in. The sample photos are still here too.": "你的照片已匯入。範例照片也還在。", + "Drag any slider: the original never changes.": "拖動任意滑桿:原始照片永遠不會改變。", + "Keep Them": "保留", + "Hide": "隱藏", "Photos you import show up here. Nothing is copied or moved unless you choose to.": "匯入的照片會顯示在這裡。除非你選擇,否則不會複製或移動任何檔案。", "or drop photos and folders into this window": "或將照片和資料夾拖放到此視窗", + "or look through a folder without importing it, under Local in the sidebar": "或不匯入直接瀏覽資料夾:在側邊欄的「本機」中", "Import photos to get started": "匯入照片以開始使用", "or drop photos into this window": "或將照片拖放到此視窗", "No photos found": "找不到照片", diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index 6178990b0bb..9cc8816e442 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -360,6 +360,7 @@ impl Headless { || self.app.import.is_some() || self.app.export.is_some() || self.app.session.denoise_busy() + || self.app.welcome_samples.as_ref().is_some_and(|s| s.drawing()) || !self.app.tasks.is_empty() || !self.app.synthetic.is_empty() || !self.events.is_empty() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb290bd86ec..236c11b96f3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -150,6 +150,10 @@ mod tests_rename_person; #[cfg(test)] mod tests_sam_setup; #[cfg(test)] +mod tests_samples; +#[cfg(test)] +mod tests_samples_landing; +#[cfg(test)] mod tests_scroll; #[cfg(test)] mod tests_slider_reset; @@ -176,6 +180,10 @@ mod tests_view_cost; #[cfg(test)] mod tests_wb_selector; #[cfg(test)] +mod tests_welcome; +#[cfg(test)] +mod tests_welcome_access; +#[cfg(test)] mod tests_zoom; #[cfg(test)] mod tests_zoom_keys; @@ -476,6 +484,23 @@ pub struct LightcraftApp { /// The library failed to open at launch: the blocking window, then the temporary-session /// banner (issue #100). Cleared once a library opens. pub library_problem: Option, + /// Whether the library held sample photos last frame (`None` before the first): samples that + /// newly appear, however they came (the welcome, Help ▸ Add Sample Photos, an agent), bring + /// back a samples banner closed over earlier ones. + pub samples_present: Option, + /// Whether the empty library's welcome had the window last frame (`None` before the first): + /// becoming empty puts the Tools panel aside ([`panels::empty_library::follow`]). + pub welcome_seen: Option, + /// The welcome's sample thumbnails while they are shown (drawn by a worker as it starts). + pub(crate) welcome_samples: Option, + /// The welcome was drawn this frame (its thumbnails go the frame after it isn't). + pub(crate) welcome_drawn: bool, + /// The new library's welcome has put the keyboard on Import Photos… (once per session). + pub(crate) welcome_focused: bool, + /// The session's commit count when samples came into an empty library and a sample was opened + /// ([`panels::empty_library::land_on_samples`]): until it moves on (a first change), the + /// samples banner invites one. + pub(crate) samples_landed: Option, /// The activity stack shows every task, not just the first few ("+N more" was clicked). pub activity_expanded: bool, } @@ -555,6 +580,12 @@ impl LightcraftApp { screen_profile: None, screen_profile_read: None, library_problem: None, + samples_present: None, + welcome_seen: None, + welcome_samples: None, + welcome_drawn: false, + welcome_focused: false, + samples_landed: None, activity_expanded: false, model_setup: Default::default(), } @@ -617,7 +648,13 @@ impl LightcraftApp { } else { params }; + // samples coming into an empty library, however they are asked for, land on one in Detail + // (the welcome showing: not a Local folder or Recently Deleted of an otherwise empty library) + let landing = id == "library.addSamples" && panels::empty_library::shown(&self.session); let r = self.session.execute(id, ¶ms).map_err(CommandError::from); + if r.is_ok() && landing { + panels::empty_library::land_on_samples(self); + } if r.is_ok() && matches!(id, "crop.aspect" | "crop.rotateAspect") { self.ui.crop_default_aspect = if id == "crop.aspect" && params.get("aspect").and_then(Value::as_str) == Some("original") { Some(serde_json::json!("original")) @@ -1403,6 +1440,8 @@ impl LightcraftApp { return; } self.shown_library = Some(generation); + // the invitation to edit a sample belongs to the library the samples landed in + self.samples_landed = None; if let Some(l) = self.session.library.as_ref().filter(|l| l.on_disk) { let path = l.dir.to_string_lossy().into_owned(); panels::settings::remember_library(&mut self.ui.settings.recent_libraries, &path); @@ -1432,6 +1471,7 @@ impl LightcraftApp { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } self.library_changed(&ctx); + panels::empty_library::follow(self); // panels set it again this frame while the pointer rests on a preset or profile self.hover_preview = None; self.ai_mask_detail(&ctx); @@ -1454,6 +1494,7 @@ impl LightcraftApp { // right panels and left panel run to the bottom; the bottom bar sits between them). panels::topbar::show(self, ui); panels::library_problem::banner(self, ui); + panels::samples::banner(self, ui); panels::strip::show(self, ui); // filled: the gaps the dock leaves between its panes show chrome, not the dark clear colour let chrome = theme::Tokens::get(&ctx).chrome; @@ -1474,7 +1515,8 @@ impl LightcraftApp { panels::keyword_list::drag_feedback(self, &ctx); panels::toast(self, &ctx); self.widgets = widgets::take_registry(&ctx); - self.text_focus = ctx.egui_wants_keyboard_input(); + // a focused plain button (the welcome's) isn't a text field the person is typing in + self.text_focus = ctx.egui_wants_keyboard_input() && !crate::widgets::plain_button_has_focus(&ctx); self.end_frame(&ctx, t0); } } diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rs index 62cbe896821..3d6c3dc1959 100644 --- a/crates/ui-egui/src/panels/bottombar.rs +++ b/crates/ui-egui/src/panels/bottombar.rs @@ -85,6 +85,10 @@ const PILL_W: f32 = 208.0; /// The rating/flag pill and copy/paste settings, between `from` and `to` (the side groups): the /// copy buttons go first when there is no room (they are in the Edit menu too), then the pill. fn centre(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, from: f32, to: f32) { + // nothing to rate, flag or copy settings from until the library has photos + if super::empty_library::shown(&app.session) { + return; + } let t = Tokens::get(ui.ctx()); let has_clip = app.session.clipboard.is_some(); let label = crate::i18n::tr(if has_clip { "Paste Edit Settings" } else { "Copy Edit Settings" }); @@ -483,7 +487,8 @@ mod tests { fn rating_and_flag_buttons_keep_padding_inside_the_pill() { for scale in [1.0, 2.0] { for room in [240.0, 500.0] { - let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + // photos to rate: an empty library has no pill (the welcome has the window) + let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); let mut view = HeadlessView::new(); for frame in 0..3 { let raw = HeadlessView::raw_input(vec2(700.0, 40.0), scale, frame as f64 / 60.0, vec![]); diff --git a/crates/ui-egui/src/panels/empty_library.rs b/crates/ui-egui/src/panels/empty_library.rs index d420ee1a053..3d0ba28ebd2 100644 --- a/crates/ui-egui/src/panels/empty_library.rs +++ b/crates/ui-egui/src/panels/empty_library.rs @@ -1,13 +1,17 @@ //! A library with no photos yet: what the grid and the Detail view show instead of a dead end, -//! with Import Photos… and Import Lightroom Catalog… as buttons, and the view it opens on. +//! with Import Photos… and Import Lightroom Catalog… as buttons and a row of sample photos to try +//! LightCraft on, and the view it opens on. A library just created asks this as its welcome: it +//! starts empty. While it is empty the welcome has the window: the Tools panel steps aside until +//! photos arrive. -use egui::Rect; +use egui::{Rect, Sense, pos2, vec2}; use serde_json::json; use super::EmptyAction; use crate::LightcraftApp; use crate::shortcuts::Keymap; -use crate::state::ViewMode; +use crate::state::{RightPanel, ViewMode}; +use crate::theme::Tokens; /// The library holds no photos: none, or only ones in Recently Deleted or browsed under Local. pub fn is_empty(session: &lightcraft_engine::Session) -> bool { @@ -34,43 +38,311 @@ pub fn open_on_empty_library(app: &mut LightcraftApp) { } } -/// The line under the buttons: dropping works anywhere in the window, and the shortcut is the -/// one Import Photos… is bound to now, written as menus write it. -pub fn hint(keymap: &Keymap, mac: bool) -> String { - // the browser build reads dropped files, not folders +/// The lines under the buttons: dropping works anywhere in the window, with the shortcut Import +/// Photos… is bound to now (written as menus write it); and, on the desktop while Local is in +/// sight (`local`), that a folder can be looked through in place there without importing it (the +/// way in for a library too large to import at once). +pub fn hint(keymap: &Keymap, mac: bool, local: bool) -> String { + // the browser build reads dropped files, not folders, and has no Local let drop = if cfg!(target_arch = "wasm32") { crate::i18n::tr("or drop photos into this window") } else { crate::i18n::tr("or drop photos and folders into this window") }; - match crate::shortcuts::shortcut_of(keymap, "file.addPhotos") { + let first = match crate::shortcuts::shortcut_of(keymap, "file.addPhotos") { Some(sc) => format!("{drop} · {}", crate::menubar::shortcut_text(sc, mac)), None => drop.to_string(), + }; + if cfg!(target_arch = "wasm32") || !local { + first + } else { + format!("{first}\n{}", crate::i18n::tr("or look through a folder without importing it, under Local in the sidebar")) } } +/// "Welcome to LightCraft" for a library just created (it never held a photo), else "Your +/// library is empty". A temporary session (the library couldn't be opened) is never welcomed. +pub fn title(session: &lightcraft_engine::Session, temporary: bool) -> &'static str { + if welcomes(session, temporary) { "Welcome to LightCraft" } else { "Your library is empty" } +} + +fn welcomes(session: &lightcraft_engine::Session, temporary: bool) -> bool { + !temporary && session.catalog.never_held_photos() +} + +const SAMPLES: EmptyAction = EmptyAction { command: "library.addSamples", label: "Try Sample Photos", widget: "button:emptySamples" }; const IMPORT_PHOTOS: EmptyAction = EmptyAction { command: "file.addPhotos", label: "Import Photos…", widget: "button:emptyImportPhotos" }; const IMPORT_LIGHTROOM: EmptyAction = EmptyAction { command: "file.importLightroom", label: "Import Lightroom Catalog…", widget: "button:emptyImportLightroom" }; -/// The empty library's message and buttons, centred in `rect`. A click runs the command as its -/// menu item does; a refusal shows as a toast. +/// Each frame: when the welcome comes on screen (the library becomes or opens empty) the Tools +/// panel steps aside, so the welcome is the one thing asking for attention, and the panel it was +/// is remembered (in `ui.json` too, so quitting while empty doesn't lose it). Once the welcome +/// goes (photos arrive, or a folder under Local or Recently Deleted is shown, whose photos can be +/// edited) it comes back as it was: an editing tool (Crop, Masking…) as the Edit panel, as the +/// photo it was used on is gone. Only the welcome coming puts it aside: a panel the person opens +/// meanwhile is theirs, and so is closing it again. +pub fn follow(app: &mut LightcraftApp) { + // the welcome wasn't drawn last frame (another view, a filter's message, photos in): its + // sample thumbnails go, and their worker stops at its next one + if !std::mem::take(&mut app.welcome_drawn) { + app.welcome_samples = None; + } + let empty = shown(&app.session); + if empty { + if app.welcome_seen != Some(true) { + if app.ui.right != RightPanel::None { + app.ui.right_before_welcome = Some(app.ui.right); + app.ui.right = RightPanel::None; + } + } else if app.ui.right != RightPanel::None { + // opened by the person while the welcome shows: theirs from now on + app.ui.right_before_welcome = None; + } + } else { + if let Some(right) = app.ui.right_before_welcome.take() + && app.ui.right == RightPanel::None + { + app.ui.right = if right.is_edit_tool() { RightPanel::Edit } else { right }; + } + } + app.welcome_seen = Some(empty); +} + +/// The welcome's sample photos: their scenes, and their thumbnails as they arrive from the worker +/// that draws them (they take a moment each, never on the UI thread). +pub struct SampleStrip { + tiles: Vec, + rx: Option>, +} + +struct Tile { + scene: u32, + title: String, + texture: Option, +} + +/// The long side the thumbnails are drawn at: sharp at 2× on the widest tile. +const THUMB_EDGE: usize = 320; +const TILE_GAP: f32 = 10.0; +const TILE_MIN_W: f32 = 96.0; +const TILE_MAX_W: f32 = 150.0; +const CAPTION_H: f32 = 26.0; + +impl SampleStrip { + /// Start drawing the thumbnails (desktop: a worker thread; the browser has none to spare, and + /// keeps the Try Sample Photos button instead). + fn start() -> SampleStrip { + let scenes = lightcraft_engine::demo::welcome_scenes(); + let tiles = scenes.iter().map(|(scene, title)| Tile { scene: *scene, title: title.clone(), texture: None }).collect(); + let (tx, rx) = std::sync::mpsc::channel(); + let ids: Vec = scenes.iter().map(|(id, _)| *id).collect(); + let spawned = std::thread::Builder::new().name("welcome-samples".into()).spawn(move || { + for id in ids { + let Some(img) = lightcraft_engine::demo::scene_preview(id, THUMB_EDGE) else { continue }; + // the welcome went away (photos came in): nobody to draw them for + if tx.send((id, img)).is_err() { + return; + } + } + }); + if let Err(e) = spawned { + log::warn!("welcome sample thumbnails: {e}"); + } + SampleStrip { tiles, rx: Some(rx) } + } + + /// The worker is still drawing thumbnails. + pub(crate) fn drawing(&self) -> bool { + self.rx.is_some() + } + + /// At least one thumbnail has arrived (tests wait for it). + #[cfg(test)] + pub(crate) fn has_thumbnail(&self) -> bool { + self.tiles.iter().any(|t| t.texture.is_some()) + } + + /// Thumbnails that arrived become textures; the frame after the last, the worker is done. + fn receive(&mut self, ctx: &egui::Context) { + let Some(rx) = &self.rx else { return }; + loop { + match rx.try_recv() { + Ok((scene, img)) => { + let bytes = img.as_bytes(); + // egui insists the pixels fill the size: skip one that doesn't (never expected) + if bytes.len() != img.width.saturating_mul(img.height).saturating_mul(4) { + continue; + } + let image = egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], &bytes); + if let Some(tile) = self.tiles.iter_mut().find(|t| t.scene == scene) { + tile.texture = Some(ctx.load_texture(format!("welcome-sample-{scene}"), image, egui::TextureOptions::LINEAR)); + } + } + // still drawing (about a tenth of a second for all five): keep frames coming until + // the last arrives, so none shows as a placeholder longer than it must (and a + // screenshot that waits for the window to settle waits for them) + Err(std::sync::mpsc::TryRecvError::Empty) => { + ctx.request_repaint(); + return; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.rx = None; + return; + } + } + } + } +} + +/// How many thumbnails fit in `width` (five, down to three) and how wide each is; `None` when not +/// three: the column is too narrow, and a button offers the samples instead. +fn strip_layout(width: f32) -> Option<(usize, f32)> { + (3..=5).rev().find(|n| *n as f32 * TILE_MIN_W + (*n as f32 - 1.0) * TILE_GAP <= width).map(|n| { + let w = ((width - (n as f32 - 1.0) * TILE_GAP) / n as f32).min(TILE_MAX_W); + (n, w) + }) +} + +/// The sample thumbnails' height in a column `width` wide (0 when they don't fit). +fn strip_height(width: f32) -> f32 { + strip_layout(width).map_or(0.0, |(_, w)| CAPTION_H + w * 2.0 / 3.0) +} + +/// Samples just came into an empty library (the welcome's button or thumbnails, Help ▸ Add +/// Sample Photos, an agent): open the first of the welcome's in Detail, ready to edit, so every +/// way in lands in the same place; and note the session's commit count, so the samples banner +/// invites a first change until one is made. +pub fn land_on_samples(app: &mut LightcraftApp) { + let first = lightcraft_engine::demo::welcome_scenes().first().map(|(id, _)| *id); + if let Some(scene) = first { + select_sample(app, scene); + } + // the sliders beside it: the banner invites dragging one + app.ui.right = RightPanel::Edit; + app.samples_landed = Some(app.session.commits()); +} + +/// Select the sample photo of `scene` and show it in Detail. +fn select_sample(app: &mut LightcraftApp, scene: u32) { + let photo = app.session.catalog.photos().find(|p| matches!(p.source, lightcraft_catalog::Source::Demo { scene: s } if s == scene)).map(|p| p.id); + if let Some(id) = photo { + app.session.selection = lightcraft_engine::Selection::single(id); + } + app.ui.view = ViewMode::Detail; +} + +/// Add the samples and open the one clicked in Detail, ready to edit (the Tools panel comes back +/// with the photos). +fn open_sample(app: &mut LightcraftApp, ctx: &egui::Context, scene: u32) { + if let Err(e) = app.run("library.addSamples", json!({})) { + app.toast_error(ctx, e); + return; + } + // (adding them landed on the first: this one was clicked) + select_sample(app, scene); +} + +/// The row of sample thumbnails in `area`, under a caption. Returns the scene clicked. +fn strip(strip: &mut SampleStrip, ui: &mut egui::Ui, area: Rect) -> Option { + let t = Tokens::get(ui.ctx()); + let (n, w) = strip_layout(area.width())?; + let n = n.min(strip.tiles.len()); + if n == 0 { + return None; + } + strip.receive(ui.ctx()); + let p = ui.painter().clone(); + let caption = crate::i18n::tr("Or try LightCraft on a sample photo"); + let caption_rect = p.text(pos2(area.center().x, area.top() + 8.0), egui::Align2::CENTER_CENTER, caption, t.font(12.0), t.text_label); + super::readable(ui, caption_rect, "welcome-caption", caption, false); + let h = w * 2.0 / 3.0; + let row_w = n as f32 * w + (n as f32 - 1.0) * TILE_GAP; + let mut x = area.center().x - row_w / 2.0; + let mut clicked = None; + for tile in strip.tiles.iter().take(n) { + let r = Rect::from_min_size(pos2(x, area.top() + CAPTION_H), vec2(w, h)); + x += w + TILE_GAP; + let resp = ui.interact(r, ui.id().with(("welcome-sample", tile.scene)), Sense::click()); + let label = crate::i18n::tr_format!("Open the sample photo “{title}”", title = tile.title); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label.clone())); + crate::widgets::register(ui.ctx(), format!("button:sample:{}", tile.scene), r); + crate::widgets::plain_button(ui.ctx(), resp.id); + match &tile.texture { + Some(tex) => { + egui::Image::new((tex.id(), r.size())).corner_radius(6.0).paint_at(ui, r); + } + // drawing: a quiet placeholder of the same size, so nothing jumps when it arrives + None => { + p.rect_filled(r, 6.0, t.inset); + } + } + if resp.hovered() || resp.has_focus() { + let width = if resp.has_focus() { 2.0 } else { 1.5 }; + p.rect_stroke(r, 6.0, egui::Stroke::new(width, t.accent), egui::StrokeKind::Outside); + } + let resp = resp.on_hover_text(&tile.title).on_hover_cursor(egui::CursorIcon::PointingHand); + if resp.clicked() { + clicked = Some(tile.scene); + } + } + clicked +} + +/// The empty library's message and buttons, centred in `rect`: Import Photos…, Import Lightroom +/// Catalog… (not in the browser), and the sample photos as a row of thumbnails (as a button where +/// the row doesn't fit, or in the browser). A click runs the command as its menu item does; a +/// refusal shows as a toast. pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, rect: Rect) { - // the browser build can't read a Lightroom catalog from disk: only offer what works there - let actions: &[EmptyAction] = if cfg!(target_arch = "wasm32") { &[IMPORT_PHOTOS] } else { &[IMPORT_PHOTOS, IMPORT_LIGHTROOM] }; + let temporary = app.library_problem.is_some(); + // samples in Recently Deleted are still in the library: adding them again would be refused; + // nothing done in a temporary session is saved: samples there would only be lost + let samples = !app.session.has_samples() && !temporary; + let wrap = (rect.width() - 48.0).max(80.0); let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; - let hint = hint(&app.ui.settings.keymap, mac); - let clicked = super::empty_state( - ui, - rect, - "Your library is empty", - "Photos you import show up here. Nothing is copied or moved unless you choose to.", - actions, - Some(&hint), - ); + let local = app.ui.left_panel && app.ui.sidebar.shown().any(|s| s == crate::sidebar::SidebarSection::Local); + let hint = hint(&app.ui.settings.keymap, mac, local); + let title = title(&app.session, temporary); + let body = if welcomes(&app.session, temporary) { + "Start with photos of your own, or look around with a set of sample photos first. Nothing is copied or moved unless you choose to." + } else { + "Photos you import show up here. Nothing is copied or moved unless you choose to." + }; + // the row needs room both ways: a short view (Detail above its filmstrip, under the samples + // banner), or a long language wrapping the message, offers the button instead of pushing the + // welcome past its edges. Measured with the two buttons the row goes with. + let message = super::empty_state_height(ui, rect, title, body, &[IMPORT_PHOTOS, IMPORT_LIGHTROOM], Some(&hint)); + let room = rect.height() >= message + super::EMPTY_EXTRA_GAP + strip_height(wrap) + 16.0; + let row = samples && !cfg!(target_arch = "wasm32") && strip_layout(wrap).is_some() && room; + app.welcome_drawn = true; + if !row && let Some(samples_row) = app.welcome_samples.as_mut() { + // the row is out of room for now (a resize): keep what was drawn for when it's back, and + // take what the worker sends meanwhile, so it finishes rather than waits + samples_row.receive(ui.ctx()); + } + // the browser build can't read a Lightroom catalog from disk: only offer what works there + let actions: &[EmptyAction] = match (cfg!(target_arch = "wasm32"), samples && !row) { + (true, true) => &[IMPORT_PHOTOS, SAMPLES], + (true, false) => &[IMPORT_PHOTOS], + (false, true) => &[IMPORT_PHOTOS, IMPORT_LIGHTROOM, SAMPLES], + (false, false) => &[IMPORT_PHOTOS, IMPORT_LIGHTROOM], + }; + let extra = if row { strip_height(wrap) } else { 0.0 }; + // a new library's welcome puts the keyboard on Import Photos… once, so Enter or Space starts + let focus = welcomes(&app.session, temporary) && !std::mem::replace(&mut app.welcome_focused, true); + let (clicked, below) = super::empty_state(ui, rect, title, body, actions, Some(&hint), extra, focus); if let Some(command) = clicked && let Err(e) = app.run(command, json!({})) { app.toast_error(ui.ctx(), e); } + if row { + let mut samples_row = app.welcome_samples.take().unwrap_or_else(SampleStrip::start); + let scene = strip(&mut samples_row, ui, below); + app.welcome_samples = Some(samples_row); + if let Some(scene) = scene { + app.welcome_samples = None; + open_sample(app, ui.ctx(), scene); + } + } } diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index c6365b784c7..4c14095e5ed 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -193,7 +193,9 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { } else if app.session.source == lightcraft_engine::LibrarySource::Folder { super::empty_message(ui, ui.max_rect(), "No photos in this folder", "Turn on Include subfolders, or pick another folder under Local"); } else if super::empty_library::shown(&app.session) { - super::empty_library::show(app, ui, ui.max_rect()); + // below the header: centred in the space it has, and never over the title above it + let below = ui.available_rect_before_wrap(); + super::empty_library::show(app, ui, below); } else { super::empty_message(ui, ui.max_rect(), "No photos", "Import photos with File → Import Photos… (Cmd+Shift+I), or drop them here"); } diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index 2fcb36663c8..f79340ad00f 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -28,6 +28,7 @@ pub mod presets; pub mod profiles; pub mod right; pub mod rules_editor; +pub mod samples; pub mod second; pub mod settings; pub mod slide_layout; @@ -118,10 +119,90 @@ pub struct EmptyAction { pub widget: &'static str, } +/// Painted text a screen reader can read: a node over `rect` with the words, a heading when +/// `heading` (the welcome's title), plain text otherwise. Hover only: clicks pass through. +pub(crate) fn readable(ui: &egui::Ui, rect: Rect, salt: &str, text: &str, heading: bool) { + let resp = ui.interact(rect, ui.id().with(("readable", salt)), egui::Sense::hover()); + // egui's way for text: the words as the node's value (as every other label in the app) + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, text)); + if heading { + // a heading is read by its name: the words go there instead, not twice + ui.ctx().accesskit_node_builder(resp.id, |node| { + node.set_role(egui::accesskit::Role::Heading); + node.set_label(text.to_string()); + node.clear_value(); + }); + } +} + +/// One dim line, centred: a panel's quiet empty state beside a louder one elsewhere (the Tools +/// panel next to the empty library's welcome), so the window has one headline. +pub fn empty_note(ui: &egui::Ui, rect: Rect, text: &str) { + let t = Tokens::get(ui.ctx()); + let mut job = egui::text::LayoutJob::simple(crate::i18n::tr(text).to_string(), t.font(13.0), t.text_dim, (rect.width() - 32.0).max(60.0)); + job.halign = egui::Align::Center; + let g = ui.painter().layout_job(job); + let at = pos2(rect.center().x, rect.center().y - g.size().y / 2.0); + readable(ui, g.rect.translate(at.to_vec2()), "empty-note", g.text(), false); + ui.painter().galley(at, g, t.text_dim); +} + +/// The space an empty state leaves under its hint for more of it (the welcome's sample photos): +/// `height` tall, counted when the block is centred. +pub const EMPTY_EXTRA_GAP: f32 = 28.0; + +/// An empty state's `i`th action as a button: the first is the primary one. +fn empty_button(i: usize, a: &EmptyAction) -> crate::button::Button<'static> { + let b = crate::button::Button::new(a.label).widget(a.widget); + if i == 0 { b.primary() } else { b.secondary() } +} + +/// [`empty_state`]'s layout, shared with [`empty_state_height`] so the two can't drift. +const EMPTY_BUTTON_H: f32 = crate::button::Size::Medium.height(); +const EMPTY_BUTTON_GAP: f32 = 8.0; +const EMPTY_TITLE_GAP: f32 = 6.0; +const EMPTY_BUTTONS_GAP: f32 = 20.0; +const EMPTY_HINT_GAP: f32 = 12.0; + +/// The height [`empty_state`] takes for this message, buttons and hint in `rect` (without the +/// extra room below): what a caller checks before asking for that room. +pub fn empty_state_height(ui: &egui::Ui, rect: Rect, title: &str, body: &str, actions: &[EmptyAction], hint: Option<&str>) -> f32 { + let t = Tokens::get(ui.ctx()); + let wrap = (rect.width() - 48.0).max(80.0); + let height = |text: &str, font: egui::FontId| ui.painter().layout(text.to_string(), font, t.text, wrap).size().y; + let widths: Vec = actions.iter().enumerate().map(|(i, a)| empty_button(i, a).desired_size(ui).x).collect(); + let row_w = widths.iter().sum::() + EMPTY_BUTTON_GAP * widths.len().saturating_sub(1) as f32; + let buttons_h = match (actions.len(), row_w <= wrap) { + (0, _) => 0.0, + (_, true) => EMPTY_BUTTON_H, + (n, false) => n as f32 * EMPTY_BUTTON_H + (n - 1) as f32 * EMPTY_BUTTON_GAP, + }; + let gap_above_buttons = if actions.is_empty() { 0.0 } else { EMPTY_BUTTONS_GAP }; + let hint_h = hint.map_or(0.0, |h| EMPTY_HINT_GAP + height(h, t.font(12.0))); + height(crate::i18n::tr(title), t.semibold(18.0)) + + EMPTY_TITLE_GAP + + height(crate::i18n::tr(body), t.font(13.0)) + + gap_above_buttons + + buttons_h + + hint_h +} + /// [`empty_message`] with the next step under it: a row of buttons (the first is the primary -/// one, filled with the accent) and an optional dimmed hint line below them. The block is -/// centred in `rect` as one. Returns the command of the button clicked this frame. -pub fn empty_state(ui: &mut egui::Ui, rect: Rect, title: &str, body: &str, actions: &[EmptyAction], hint: Option<&str>) -> Option<&'static str> { +/// one, filled with the accent), an optional dimmed hint line below them, and `extra` points of +/// room below that for more (0 for none). The block is centred in `rect` as one. Its words are +/// readable by screen readers (the title as a heading), a focused button shows a ring, and +/// `focus_primary` gives the primary button the keyboard focus. Returns the command of the button +/// clicked this frame, and the room left for the extra (as wide as the text may run). +pub fn empty_state( + ui: &mut egui::Ui, + rect: Rect, + title: &str, + body: &str, + actions: &[EmptyAction], + hint: Option<&str>, + extra: f32, + focus_primary: bool, +) -> (Option<&'static str>, Rect) { let t = Tokens::get(ui.ctx()); let wrap = (rect.width() - 48.0).max(80.0); let centred = |ui: &egui::Ui, text: &str, font: egui::FontId, color: egui::Color32| { @@ -133,10 +214,9 @@ pub fn empty_state(ui: &mut egui::Ui, rect: Rect, title: &str, body: &str, actio let body = centred(ui, crate::i18n::tr(body), t.font(13.0), t.text_dim); let hint = hint.map(|h| centred(ui, h, t.font(12.0), t.text_dim)); // the buttons' widths, and whether they fit side by side (else one above the other) - const BUTTON_H: f32 = 30.0; - const GAP: f32 = 8.0; - let widths: Vec = - actions.iter().map(|a| ui.painter().layout_no_wrap(crate::i18n::tr(a.label).to_string(), t.semibold(13.0), t.text).size().x + 32.0).collect(); + const BUTTON_H: f32 = EMPTY_BUTTON_H; + const GAP: f32 = EMPTY_BUTTON_GAP; + let widths: Vec = actions.iter().enumerate().map(|(i, a)| empty_button(i, a).desired_size(ui).x).collect(); let row_w = widths.iter().sum::() + GAP * widths.len().saturating_sub(1) as f32; let side_by_side = row_w <= wrap; let buttons_h = match (actions.len(), side_by_side) { @@ -144,15 +224,21 @@ pub fn empty_state(ui: &mut egui::Ui, rect: Rect, title: &str, body: &str, actio (_, true) => BUTTON_H, (n, false) => n as f32 * BUTTON_H + (n - 1) as f32 * GAP, }; - let gap_above_buttons = if actions.is_empty() { 0.0 } else { 20.0 }; - let hint_h = hint.as_ref().map_or(0.0, |g| 12.0 + g.size().y); - let block = title.size().y + 6.0 + body.size().y + gap_above_buttons + buttons_h + hint_h; + let gap_above_buttons = if actions.is_empty() { 0.0 } else { EMPTY_BUTTONS_GAP }; + let hint_h = hint.as_ref().map_or(0.0, |g| EMPTY_HINT_GAP + g.size().y); + let extra_h = if extra > 0.0 { EMPTY_EXTRA_GAP + extra } else { 0.0 }; + let block = title.size().y + EMPTY_TITLE_GAP + body.size().y + gap_above_buttons + buttons_h + hint_h + extra_h; let top = rect.center().y - block / 2.0; let p = ui.painter().clone(); - let body_top = top + title.size().y + 6.0; + let body_top = top + title.size().y + EMPTY_TITLE_GAP; let buttons_top = body_top + body.size().y + gap_above_buttons; - p.galley(pos2(rect.center().x, top), title, t.text_label); - p.galley(pos2(rect.center().x, body_top), body, t.text_dim); + let title_at = pos2(rect.center().x, top); + crate::widgets::register(ui.ctx(), "text:emptyTitle", title.rect.translate(title_at.to_vec2())); + let body_at = pos2(rect.center().x, body_top); + readable(ui, title.rect.translate(title_at.to_vec2()), "empty-title", title.text(), true); + readable(ui, body.rect.translate(body_at.to_vec2()), "empty-body", body.text(), false); + p.galley(title_at, title, t.text_label); + p.galley(body_at, body, t.text_dim); let mut clicked = None; let mut x = rect.center().x - row_w / 2.0; for (i, (a, w)) in actions.iter().zip(&widths).enumerate() { @@ -164,17 +250,21 @@ pub fn empty_state(ui: &mut egui::Ui, rect: Rect, title: &str, body: &str, actio let w = widths.iter().copied().fold(0.0, f32::max).min(wrap); Rect::from_min_size(pos2(rect.center().x - w / 2.0, buttons_top + i as f32 * (BUTTON_H + GAP)), vec2(w, BUTTON_H)) }; - let label = egui::RichText::new(crate::i18n::tr(a.label)).font(t.semibold(13.0)); - let button = - if i == 0 { egui::Button::new(label.color(egui::Color32::WHITE)).fill(t.accent) } else { egui::Button::new(label.color(t.text)) }; - let resp = ui.put(r, button); - crate::widgets::register(ui.ctx(), a.widget, resp.rect); + // (the button shows a ring where the keyboard is, as the sample thumbnails do) + let resp = empty_button(i, a).show_at(ui, r); + crate::widgets::plain_button(ui.ctx(), resp.id); + if i == 0 && focus_primary { + resp.request_focus(); + } if resp.clicked() { clicked = Some(a.command); } } if let Some(g) = hint { - p.galley(pos2(rect.center().x, buttons_top + buttons_h + 12.0), g, t.text_dim); + let at = pos2(rect.center().x, buttons_top + buttons_h + EMPTY_HINT_GAP); + readable(ui, g.rect.translate(at.to_vec2()), "empty-hint", g.text(), false); + p.galley(at, g, t.text_dim); } - clicked + let extra_top = buttons_top + buttons_h + hint_h + EMPTY_EXTRA_GAP; + (clicked, Rect::from_min_size(pos2(rect.center().x - wrap / 2.0, extra_top), vec2(wrap, extra.max(0.0)))) } diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 5373308102b..6b62da964af 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -34,7 +34,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let r = ui.max_rect(); // every tab (Edit, Info, Versions…) says it: nothing to show until photos come in if super::empty_library::shown(&app.session) { - super::empty_message(ui, r, "No photos yet", "Import photos to get started"); + // one quiet line: the welcome beside it is the headline + super::empty_note(ui, r, "Import photos to get started"); } else { super::empty_message(ui, r, "No photo selected", "Select a photo to edit"); } diff --git a/crates/ui-egui/src/panels/samples.rs b/crates/ui-egui/src/panels/samples.rs new file mode 100644 index 00000000000..74d835c74bd --- /dev/null +++ b/crates/ui-egui/src/panels/samples.rs @@ -0,0 +1,106 @@ +//! The banner under the top bar while the library holds the sample photos: it says what they +//! are, and offers the next step. With only samples: Import Photos… or Remove Samples. Once photos +//! of the person's own are in: Remove Samples or Keep Them. Closed for good with Hide / Keep Them +//! (until samples are added again). + +use egui::RichText; +use lightcraft_catalog::Source; +use serde_json::json; + +use crate::LightcraftApp; +use crate::theme::Tokens; +use crate::widgets::register; + +enum Click { + Import, + Remove, + Hide, +} + +/// The library holds photos of the person's own beside the samples (stops at the first one: +/// samples are a couple of dozen). +fn own_photos(app: &LightcraftApp) -> bool { + app.session.catalog.photos().any(|p| p.in_library() && !matches!(p.source, Source::Demo { .. })) +} + +/// What the banner says now, or `None` while it isn't shown: hidden, no sample in the library +/// (all in Recently Deleted: the grid says the library is empty), or an in-memory demo session (a +/// demo by design). On a sample open in Detail before the first change since the samples came, +/// it invites that change, with the key Compare Before and After is bound to. +pub fn message(app: &LightcraftApp, mac: bool) -> Option { + if app.ui.samples_banner_hidden || app.session.catalog.sample_photos_in_library() == 0 || app.session.library.is_none() { + return None; + } + if own_photos(app) { + return Some(crate::i18n::tr("Your photos are in. The sample photos are still here too.").to_string()); + } + let on_a_sample = app.ui.view == crate::state::ViewMode::Detail + && app.session.active().and_then(|id| app.session.catalog.photo(id)).is_some_and(|p| matches!(p.source, Source::Demo { .. })); + if on_a_sample && app.samples_landed == Some(app.session.commits()) { + let first = crate::i18n::tr("Drag any slider: the original never changes."); + return Some(match crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "view.beforeAfter") { + Some(sc) => { + let key = crate::menubar::shortcut_text(sc, mac); + format!("{first} {}", crate::i18n::tr_format!("Press {key} to compare before and after.", key = key)) + } + None => first.to_string(), + }); + } + Some(crate::i18n::tr("These are sample photos, to try LightCraft on. Import your own whenever you're ready.").to_string()) +} + +pub fn banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { + // cached by the photo set, not by every edit (see `Session::has_samples`) + let present = app.session.has_samples(); + // samples that newly appear bring the banner back, however they were added + if present && app.samples_present == Some(false) { + app.ui.samples_banner_hidden = false; + } + app.samples_present = Some(present); + let Some(text) = message(app, ui.ctx().os() == egui::os::OperatingSystem::Mac) else { return }; + let own = own_photos(app); + let t = Tokens::get(ui.ctx()); + let mut click = None; + let resp = egui::Panel::top("samples-banner") + .exact_size(34.0) + .frame(egui::Frame::NONE.fill(t.inset).inner_margin(egui::Margin::symmetric(12, 0))) + .show(ui, |ui| { + // the buttons first, from the right edge, so a long translation shortens the message + // (whole on hover) instead of pushing them out of the window + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + use crate::button::Button; + let (label, widget) = if own { ("Keep Them", "button:samplesKeep") } else { ("Hide", "button:samplesHide") }; + if Button::new(label).ghost().small().widget(widget).show(ui).clicked() { + click = Some(Click::Hide); + } + if Button::new("Remove Sample Photos").secondary().small().widget("button:samplesRemove").show(ui).clicked() { + click = Some(Click::Remove); + } + if !own && Button::new("Import Photos…").primary().small().widget("button:samplesImport").show(ui).clicked() { + click = Some(Click::Import); + } + ui.add_space(8.0); + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.add(egui::Label::new(RichText::new(text).font(t.font(12.5)).color(t.text)).truncate()); + }); + }); + }); + register(ui.ctx(), "banner:samples", resp.response.rect); + match click { + Some(Click::Import) => { + if let Err(e) = app.run("file.addPhotos", json!({})) { + app.toast_error(ui.ctx(), e); + } + } + Some(Click::Remove) => match app.run("library.removeSamples", json!({})) { + Ok(r) => { + let n = r["removed"].as_u64().unwrap_or(0); + let text = crate::i18n::tr_format!("Removed {n} sample photos. Edit → Undo brings them back.", n = n); + app.toast(ui.ctx(), text); + } + Err(e) => app.toast_error(ui.ctx(), e), + }, + Some(Click::Hide) => app.ui.samples_banner_hidden = true, + None => {} + } +} diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index b9d1874a157..53b01df8cc9 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -326,11 +326,12 @@ fn keyboard_owned(app: &LightcraftApp, ctx: &egui::Context) -> bool { [Key::ArrowLeft, Key::ArrowRight, Key::ArrowUp, Key::ArrowDown, Key::Enter, Key::Space].iter().any(|key| input.key_pressed(*key)) }); } - let chrome = app - .ui - .docking - .as_ref() - .is_some_and(|workspace| craft_ui::docking::DockArea::new(egui::Id::new("lightcraft-docking")).chrome_has_focus(ctx, &workspace.layout)); + // a plain button (the welcome's) keeps what works it; the rest are shortcuts, as on dock chrome + let chrome = + crate::widgets::plain_button_has_focus(ctx) + || app.ui.docking.as_ref().is_some_and(|workspace| { + craft_ui::docking::DockArea::new(egui::Id::new("lightcraft-docking")).chrome_has_focus(ctx, &workspace.layout) + }); if !chrome { return true; } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8c8cc0d413..ed8355ddd23 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -641,7 +641,13 @@ pub struct UiState { pub unsaved_seen: bool, pub view: ViewMode, pub left_panel: bool, + /// The person closed the banner over the sample photos (Hide / Keep Them); adding the samples + /// again shows it again. + pub samples_banner_hidden: bool, pub right: RightPanel, + /// The Tools panel the empty library's welcome put aside, to bring back once photos arrive + /// (kept here so quitting while the library is empty doesn't lose it). + pub right_before_welcome: Option, /// Widths of the left sidebar and of the right panel in points (dragging their inner edge /// resizes them; within [`LEFT_WIDTH`] / [`RIGHT_WIDTH`]). pub left_width: f32, @@ -1271,6 +1277,8 @@ impl Default for UiState { luminance_map_restore: None, view: ViewMode::Detail, left_panel: false, + samples_banner_hidden: false, + right_before_welcome: None, left_width: LEFT_WIDTH.default, right_width: RIGHT_WIDTH.default, right: RightPanel::Edit, diff --git a/crates/ui-egui/src/tests_empty_library.rs b/crates/ui-egui/src/tests_empty_library.rs index 2207875b9eb..6f2816edd49 100644 --- a/crates/ui-egui/src/tests_empty_library.rs +++ b/crates/ui-egui/src/tests_empty_library.rs @@ -131,15 +131,18 @@ fn the_top_bar_imports_in_every_library() { #[test] fn the_hint_shows_the_shortcut_as_bound() { + let local = "\nor look through a folder without importing it, under Local in the sidebar"; let mut keymap = crate::state::AppSettings::default().keymap; - assert_eq!(empty_library::hint(&keymap, true), "or drop photos and folders into this window · ⌘⇧I"); - assert_eq!(empty_library::hint(&keymap, false), "or drop photos and folders into this window · Ctrl+Shift+I"); + assert_eq!(empty_library::hint(&keymap, true, true), format!("or drop photos and folders into this window · ⌘⇧I{local}")); + assert_eq!(empty_library::hint(&keymap, false, true), format!("or drop photos and folders into this window · Ctrl+Shift+I{local}")); + // without Local in sight (sidebar or section hidden), no line pointing at it + assert_eq!(empty_library::hint(&keymap, true, false), "or drop photos and folders into this window · ⌘⇧I"); // a remapped shortcut is the one shown crate::shortcuts::assign(&mut keymap, "file.addPhotos", Some("Cmd+Alt+I")).unwrap(); - assert_eq!(empty_library::hint(&keymap, true), "or drop photos and folders into this window · ⌘⌥I"); + assert_eq!(empty_library::hint(&keymap, true, false), "or drop photos and folders into this window · ⌘⌥I"); // and none at all leaves the key out crate::shortcuts::assign(&mut keymap, "file.addPhotos", None).unwrap(); - assert_eq!(empty_library::hint(&keymap, true), "or drop photos and folders into this window"); + assert_eq!(empty_library::hint(&keymap, true, false), "or drop photos and folders into this window"); } #[test] diff --git a/crates/ui-egui/src/tests_samples.rs b/crates/ui-egui/src/tests_samples.rs new file mode 100644 index 00000000000..00c4dd03804 --- /dev/null +++ b/crates/ui-egui/src/tests_samples.rs @@ -0,0 +1,213 @@ +//! A new library asks how to begin: its first screen offers Import Photos…, Import Lightroom +//! Catalog… and the sample photos. While sample photos are in the library a banner says so and +//! offers to import or to remove them; once photos of the person's own are in, it asks whether to +//! remove the samples or keep them. + +use std::path::Path; +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::empty_library; +use crate::state::ViewMode; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +fn headless(session: lightcraft_engine::Session) -> Headless { + let mut a = LightcraftApp::new(session, Services::default()); + a.ui.view = ViewMode::PhotoGrid; + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + h +} + +/// The first of the welcome's sample thumbnails, once drawn (a worker draws them). +fn first_sample(h: &mut Headless) -> String { + h.step_until(T, |h| h.app.widgets.iter().any(|(w, _)| w.starts_with("button:sample:"))); + h.app.widgets.iter().find(|(w, _)| w.starts_with("button:sample:")).map(|(w, _)| w.clone()).unwrap_or_else(|| panic!("no sample thumbnails")) +} + +fn click(h: &mut Headless, id: &str) { + assert_eq!(h.request("ui.clickWidget", json!({"id": id}), T)["ok"], true, "{id}"); + h.step(); + h.step(); +} + +/// A new library on disk (the banner is for a library, not an in-memory demo session), with the +/// sample photos if asked. +fn library(tag: &str, samples: bool) -> lightcraft_engine::Session { + let dir = std::env::temp_dir().join(format!("lc-ui-samples-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = lightcraft_engine::Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + if samples { + s.execute("library.addSamples", &json!({})).unwrap(); + } + s +} + +/// A library with the sample photos and one photo of the person's own. +fn samples_and_own(tag: &str) -> lightcraft_engine::Session { + let mut s = library(tag, true); + let dir = std::env::temp_dir().join(format!("lc-ui-samples-{tag}-{}", std::process::id())); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 120, 160, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + let own = dir.join("own.png"); + std::fs::write(&own, png).unwrap(); + s.execute("library.import", &json!({"paths": [Path::new(&own).to_string_lossy()]})).unwrap(); + s +} + +#[test] +fn a_new_library_welcomes_and_offers_the_sample_photos() { + // Given a library just created + let s = library("welcome", false); + assert_eq!(empty_library::title(&s, false), "Welcome to LightCraft"); + assert_eq!(empty_library::title(&s, true), "Your library is empty", "a temporary session isn't welcomed"); + let mut h = headless(s); + assert!(has(&h, "button:emptyImportPhotos")); + // When the person chooses a sample photo + let sample = first_sample(&mut h); + click(&mut h, &sample); + // Then they are in the library, one is selected, and the banner says what they are + assert!(h.app.session.has_samples()); + assert!(h.app.session.active().is_some()); + assert!(has(&h, "banner:samples")); + assert!(!h.app.widgets.iter().any(|(w, _)| w.starts_with("button:sample:"))); +} + +#[test] +fn an_emptied_library_is_not_welcomed_again() { + let mut s = lightcraft_engine::Session::with_demo(); + s.execute("library.removeSamples", &json!({})).unwrap(); + assert_eq!(empty_library::title(&s, false), "Your library is empty"); +} + +#[test] +fn the_banner_over_the_samples_offers_import_and_removal() { + let mut h = headless(library("banner", true)); + for b in ["banner:samples", "button:samplesImport", "button:samplesRemove", "button:samplesHide"] { + assert!(has(&h, b), "{b}"); + } + // Remove Samples: the photos and their albums go, and the empty library leads to Import + click(&mut h, "button:samplesRemove"); + assert!(!h.app.session.has_samples()); + assert!(!has(&h, "banner:samples")); + assert!(has(&h, "button:emptyImportPhotos")); +} + +#[test] +fn once_the_persons_photos_are_in_the_banner_asks_to_remove_or_keep_the_samples() { + let mut h = headless(samples_and_own("keep")); + assert!(has(&h, "button:samplesRemove")); + assert!(has(&h, "button:samplesKeep")); + assert!(!has(&h, "button:samplesImport"), "import is done"); + // Keep Them: the banner goes, for good + click(&mut h, "button:samplesKeep"); + assert!(h.app.ui.samples_banner_hidden); + assert!(!has(&h, "banner:samples")); + assert!(h.app.session.has_samples()); +} + +#[test] +fn removing_the_samples_keeps_the_persons_photo_and_says_so() { + let mut h = headless(samples_and_own("remove")); + click(&mut h, "button:samplesRemove"); + assert!(!h.app.session.has_samples()); + assert_eq!(h.app.session.catalog.len(), 1); + assert!(!has(&h, "banner:samples")); +} + +#[test] +fn an_in_memory_demo_session_has_no_banner() { + // `--memory`, the showcase scripts and the CLI's `--demo` are demos by design + let h = headless(lightcraft_engine::Session::with_demo()); + assert!(h.app.session.has_samples()); + assert!(!has(&h, "banner:samples")); +} + +#[test] +fn adding_the_samples_again_brings_the_banner_back() { + let mut a = LightcraftApp::new(library("again", false), Services::default()); + a.ui.view = ViewMode::PhotoGrid; + a.ui.samples_banner_hidden = true; + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + let sample = first_sample(&mut h); + click(&mut h, &sample); + assert!(!h.app.ui.samples_banner_hidden); + assert!(has(&h, "banner:samples")); +} + +#[test] +fn samples_in_recently_deleted_are_not_offered_again() { + // adding them would be refused: they are still in the library + let mut s = lightcraft_engine::Session::with_demo(); + let ids: Vec = s.catalog.photos().map(|p| p.id.0).collect(); + s.selection.ids = s.catalog.photos().map(|p| p.id).collect(); + s.execute("photo.delete", &json!({"ids": ids})).unwrap(); + let h = headless(s); + assert!(has(&h, "button:emptyImportPhotos")); + assert!(!has(&h, "button:emptySamples")); +} + +#[test] +fn samples_in_recently_deleted_dont_keep_the_banner_saying_they_are_here() { + // the grid says the library is empty: a banner saying "these are sample photos" with a second + // Import button contradicted it + let mut s = library("trashed", true); + let ids: Vec = s.catalog.photos().map(|p| p.id.0).collect(); + s.selection.ids = s.catalog.photos().map(|p| p.id).collect(); + s.execute("photo.delete", &json!({"ids": ids})).unwrap(); + let h = headless(s); + assert!(h.app.session.has_samples(), "still removable from the Help menu"); + assert!(!has(&h, "banner:samples")); + assert!(!has(&h, "button:samplesImport")); + assert!(has(&h, "button:emptyImportPhotos"), "one Import, the empty state's"); +} + +#[test] +fn samples_added_from_the_help_menu_bring_the_banner_back() { + let mut a = LightcraftApp::new(library("help", false), Services::default()); + a.ui.view = ViewMode::PhotoGrid; + a.ui.samples_banner_hidden = true; + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + // (the first frame only waits for the fonts) + h.step(); + h.step(); + assert_eq!(h.app.samples_present, Some(false)); + h.app.run("library.addSamples", json!({})).unwrap(); + h.step(); + h.step(); + assert!(!h.app.ui.samples_banner_hidden); + assert!(has(&h, "banner:samples")); +} + +#[test] +fn the_banners_buttons_stay_in_a_narrow_window_with_a_long_message() { + // the longest translations (Ukrainian, Russian) are what pushed them out; the message gives way + for (lang, own) in [("uk", false), ("ru", true)] { + let s = if own { samples_and_own(&format!("narrow-{lang}")) } else { library(&format!("narrow-{lang}"), true) }; + let mut a = LightcraftApp::new(s, Services::default()); + a.ui.view = ViewMode::PhotoGrid; + let mut h = Headless::new(a, [640.0, 640.0], 1.0); + assert_eq!(h.request("ui.set", json!({"language": lang}), T)["ok"], true); + h.step(); + h.step(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 640.0)); + for b in ["button:samplesRemove", if own { "button:samplesKeep" } else { "button:samplesHide" }] { + let r = h.app.widgets.iter().find(|(w, _)| w == b).map(|(_, r)| *r).unwrap_or_else(|| panic!("{b}")); + assert!(screen.contains_rect(r), "{lang} {b} {r:?} is outside the window"); + } + assert_eq!(h.request("ui.set", json!({"language": "en"}), T)["ok"], true); + } +} diff --git a/crates/ui-egui/src/tests_samples_landing.rs b/crates/ui-egui/src/tests_samples_landing.rs new file mode 100644 index 00000000000..563a273da22 --- /dev/null +++ b/crates/ui-egui/src/tests_samples_landing.rs @@ -0,0 +1,125 @@ +//! Every way into the sample photos lands in the same place: the welcome's thumbnails, its Try +//! Sample Photos button, Help ▸ Add Sample Photos and agents open a sample in Detail, ready to +//! edit. There, until the first change, the banner invites one. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::panels::samples; +use crate::state::ViewMode; +use crate::{LightcraftApp, Services}; + +fn library(tag: &str) -> lightcraft_engine::Session { + let dir = std::env::temp_dir().join(format!("lc-ui-landing-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = lightcraft_engine::Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + s +} + +fn headless(session: lightcraft_engine::Session) -> Headless { + let mut a = LightcraftApp::new(session, Services::default()); + a.ui.view = ViewMode::PhotoGrid; + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + h +} + +fn active_scene(h: &Headless) -> Option { + let id = h.app.session.active()?; + match h.app.session.catalog.photo(id)?.source { + lightcraft_catalog::Source::Demo { scene } => Some(scene), + _ => None, + } +} + +#[test] +fn samples_added_from_the_menu_land_in_detail_like_a_thumbnail_does() { + // Given an empty library's welcome + let mut h = headless(library("menu")); + // When the samples come by Help ▸ Add Sample Photos (or the welcome's button, or an agent) + h.app.run("library.addSamples", json!({})).unwrap(); + h.step(); + h.step(); + // Then the first of the welcome's samples is open in Detail + assert_eq!(h.app.ui.view, ViewMode::Detail); + let first = lightcraft_engine::demo::welcome_scenes().first().map(|(id, _)| *id); + assert_eq!(active_scene(&h), first); +} + +#[test] +fn samples_added_to_a_library_with_photos_leave_the_view_alone() { + // (only the welcome's empty library is taken somewhere: a library in use stays as it is) + // a photo of the person's own keeps the library from being empty + let dir = std::env::temp_dir().join(format!("lc-ui-landing-photo-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 120, 160, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join("own.png"), png).unwrap(); + let mut s = library("own"); + s.execute("library.import", &json!({"paths": [dir.join("own.png").to_string_lossy()]})).unwrap(); + let mut h = headless(s); + assert!(!crate::panels::empty_library::is_empty(&h.app.session)); + h.app.run("library.addSamples", json!({})).unwrap(); + h.step(); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_banner_invites_the_first_edit_until_one_is_made() { + let mut h = headless(library("invite")); + h.app.run("library.addSamples", json!({})).unwrap(); + h.step(); + h.step(); + // in Detail on a sample, nothing changed yet: an invitation to edit, with the compare key + let text = samples::message(&h.app, true).unwrap_or_default(); + assert!(text.starts_with("Drag any slider"), "{text}"); + assert!(text.contains("Y"), "the key Compare Before and After is bound to: {text}"); + // after a first change, the banner says what it says elsewhere + let r = h.request( + "engine.execute", + json!({"command": "develop.set", "params": {"control": "light.exposure", "value": 0.5}}), + Duration::from_secs(20), + ); + assert_eq!(r["ok"], true, "{r}"); + h.step(); + let text = samples::message(&h.app, true).unwrap_or_default(); + assert!(text.starts_with("These are sample photos"), "{text}"); +} + +#[test] +fn the_grid_of_samples_keeps_the_usual_message() { + let mut h = headless(library("grid")); + h.app.run("library.addSamples", json!({})).unwrap(); + h.app.ui.view = ViewMode::PhotoGrid; + h.step(); + let text = samples::message(&h.app, true).unwrap_or_default(); + assert!(text.starts_with("These are sample photos"), "{text}"); +} + +#[test] +fn landing_opens_the_edit_panel_with_its_sliders() { + // even when the panel put aside for the welcome was another, or none + let mut h = headless(library("panel")); + h.app.ui.right_before_welcome = Some(crate::state::RightPanel::Info); + h.app.run("library.addSamples", json!({})).unwrap(); + h.step(); + h.step(); + assert_eq!(h.app.ui.right, crate::state::RightPanel::Edit); +} + +#[test] +fn samples_added_while_a_local_folder_is_shown_leave_the_view_alone() { + // the library has no photos of its own, but the welcome isn't what is on screen + let mut h = headless(library("folder")); + h.app.session.source = lightcraft_engine::LibrarySource::Folder; + h.step(); + h.app.run("library.addSamples", json!({})).unwrap(); + h.step(); + assert_eq!(h.app.ui.view, ViewMode::PhotoGrid); +} diff --git a/crates/ui-egui/src/tests_welcome.rs b/crates/ui-egui/src/tests_welcome.rs new file mode 100644 index 00000000000..e06011f864b --- /dev/null +++ b/crates/ui-egui/src/tests_welcome.rs @@ -0,0 +1,237 @@ +//! The welcome owns the window while the library is empty: the Tools panel steps aside (and comes +//! back as it was once photos arrive), the bottom bar's rating and flags hide, and a row of sample +//! photos under the buttons opens the samples on the one clicked. + +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::{RightPanel, ViewMode}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn has(h: &Headless, id: &str) -> bool { + h.app.widgets.iter().any(|(w, _)| w == id) +} + +/// A new library on disk (the welcome's thumbnails are offered over a library, as the samples +/// banner is). +fn library(tag: &str) -> lightcraft_engine::Session { + let dir = std::env::temp_dir().join(format!("lc-ui-welcome-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = lightcraft_engine::Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + s +} + +fn headless(session: lightcraft_engine::Session, size: [f32; 2]) -> Headless { + let mut a = LightcraftApp::new(session, Services::default()); + a.ui.view = ViewMode::PhotoGrid; + a.ui.right = RightPanel::Edit; + let mut h = Headless::new(a, size, 1.0); + h.step(); + h.step(); + h +} + +/// Steps until a sample thumbnail has arrived from the worker that draws them (the tiles are +/// there from the first frame, as placeholders). +fn thumbnails_shown(h: &mut Headless) -> bool { + let arrived = |h: &Headless| h.app.welcome_samples.as_ref().is_some_and(|s| s.has_thumbnail()); + h.step_until(T, |h| arrived(h)); + arrived(h) && h.app.widgets.iter().any(|(w, _)| w.starts_with("button:sample:")) +} + +#[test] +fn an_empty_library_puts_the_tools_panel_aside_until_photos_arrive() { + // Given an empty library opened with the Edit panel out + let mut h = headless(library("aside"), [1300.0, 900.0]); + // Then the welcome has the window: the panel is put aside, remembered + assert_eq!(h.app.ui.right, RightPanel::None); + assert_eq!(h.app.ui.right_before_welcome, Some(RightPanel::Edit)); + // When photos arrive, it is back as it was + h.app.run("library.addSamples", json!({})).unwrap(); + h.step(); + h.step(); + assert_eq!(h.app.ui.right, RightPanel::Edit); + assert_eq!(h.app.ui.right_before_welcome, None); +} + +#[test] +fn a_panel_opened_while_the_library_is_empty_stays_open() { + let mut h = headless(library("open"), [1300.0, 900.0]); + assert_eq!(h.app.ui.right, RightPanel::None); + h.app.run("panel.info", json!({})).unwrap(); + h.step(); + h.step(); + assert_eq!(h.app.ui.right, RightPanel::Info, "only becoming empty puts it aside"); +} + +#[test] +fn the_panel_comes_back_after_a_restart_while_the_library_was_empty() { + // quit while empty: ui.json held the panel put aside; the library has photos by the next launch + let mut a = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); + a.ui.right = RightPanel::None; + a.ui.right_before_welcome = Some(RightPanel::Info); + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + assert_eq!(h.app.ui.right, RightPanel::Info); +} + +#[test] +fn an_editing_tool_put_aside_comes_back_as_the_edit_panel() { + // the photo it was used on is gone: Masking on a newly arrived photo would be a surprise + let mut a = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default()); + a.ui.right = RightPanel::None; + a.ui.right_before_welcome = Some(RightPanel::Masking); + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + assert_eq!(h.app.ui.right, RightPanel::Edit); +} + +#[test] +fn a_panel_opened_and_closed_during_the_welcome_stays_closed() { + let mut h = headless(library("closed"), [1300.0, 900.0]); + h.app.run("panel.info", json!({})).unwrap(); + h.step(); + h.step(); + h.app.ui.right = RightPanel::None; + h.step(); + // photos of the person's own arrive (samples instead open the Edit panel, to edit one) + let dir = std::env::temp_dir().join(format!("lc-ui-welcome-closed-photo-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[90, 120, 160, 255]; 64] }; + let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::write(dir.join("own.png"), png).unwrap(); + h.app.session.execute("library.import", &json!({"paths": [dir.join("own.png").to_string_lossy()]})).unwrap(); + h.step(); + h.step(); + assert_eq!(h.app.ui.right, RightPanel::None, "closing it was the person's choice"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_thumbnails_go_with_the_welcome_and_the_window_settles() { + // photos arriving while the thumbnails are still drawing: nothing keeps waiting for them + let mut h = headless(library("settle"), [1600.0, 1000.0]); + assert!(h.app.welcome_samples.is_some()); + h.app.run("library.addSamples", json!({})).unwrap(); + h.step(); + h.step(); + assert!(h.app.welcome_samples.is_none()); + assert!(h.settle(T), "nothing left busy"); +} + +#[test] +fn the_thumbnails_go_when_another_view_replaces_the_welcome() { + // the library is still empty, but People (or Compare, or a filter's message) is on screen + let mut h = headless(library("people"), [1600.0, 1000.0]); + assert!(h.app.welcome_samples.is_some()); + h.app.ui.view = ViewMode::People; + h.step(); + h.step(); + assert!(h.app.welcome_samples.is_none()); + assert!(h.settle(T), "nothing left busy"); +} + +#[test] +fn a_row_out_of_room_for_a_moment_keeps_its_thumbnails() { + // a resize past the threshold and back: no new worker, no placeholders flashing back + let mut h = headless(library("resize"), [1600.0, 1000.0]); + assert!(thumbnails_shown(&mut h)); + assert_eq!(h.request("ui.resize", json!({"width": 1600, "height": 440}), T)["ok"], true); + h.step(); + h.step(); + assert!(h.app.welcome_samples.as_ref().is_some_and(|s| s.has_thumbnail()), "kept while the row is out of room"); + assert_eq!(h.request("ui.resize", json!({"width": 1600, "height": 1000}), T)["ok"], true); + h.step(); + assert!(h.app.welcome_samples.as_ref().is_some_and(|s| s.has_thumbnail())); +} + +#[test] +fn a_short_view_offers_the_button_instead_of_the_row() { + // a wide but short window: the welcome's view is too low for the row under the message + let mut h = headless(library("short"), [1300.0, 380.0]); + h.step(); + assert!(has(&h, "button:emptySamples")); + assert!(!h.app.widgets.iter().any(|(w, _)| w.starts_with("button:sample:"))); +} + +#[test] +fn the_bottom_bar_offers_no_rating_or_flags_with_nothing_to_rate() { + let h = headless(library("bottom"), [1300.0, 900.0]); + assert!(!has(&h, "star:bottom:1")); + assert!(!has(&h, "flag:pick")); + let h = headless(lightcraft_engine::Session::with_demo(), [1300.0, 900.0]); + assert!(has(&h, "star:bottom:1")); +} + +#[test] +fn the_welcome_shows_sample_photos_that_open_the_one_clicked() { + // Given the welcome of a new library + let mut h = headless(library("strip"), [1600.0, 1000.0]); + assert!(thumbnails_shown(&mut h), "the sample thumbnails render and show"); + assert!(!has(&h, "button:emptySamples"), "the row replaces the button"); + // (a later one than the first, which adding the samples opens anyway) + let id = h.app.widgets.iter().filter(|(w, _)| w.starts_with("button:sample:")).nth(2).map(|(w, _)| w.clone()).unwrap(); + let scene: u32 = id.trim_start_matches("button:sample:").parse().unwrap(); + // When one is clicked + assert_eq!(h.request("ui.clickWidget", json!({"id": id}), T)["ok"], true); + h.step(); + h.step(); + // Then the samples are in, and that photo is open in Detail, ready to edit + assert!(h.app.session.has_samples()); + let active = h.app.session.active().and_then(|id| h.app.session.catalog.photo(id).cloned()).unwrap(); + assert!(matches!(active.source, lightcraft_catalog::Source::Demo { scene: s } if s == scene)); + assert_eq!(h.app.ui.view, ViewMode::Detail); + assert_eq!(h.app.ui.right, RightPanel::Edit, "the panel put aside is back to edit with"); +} + +#[test] +fn a_column_too_narrow_for_the_row_offers_the_button() { + // a small window with the sidebar out, as an empty library opens: under three thumbnails wide + let mut a = LightcraftApp::new(library("narrow"), Services::default()); + a.ui.view = ViewMode::PhotoGrid; + a.ui.left_panel = true; + let mut h = Headless::new(a, [560.0, 600.0], 1.0); + h.step(); + h.step(); + h.step(); + assert!(has(&h, "button:emptySamples")); + assert!(!h.app.widgets.iter().any(|(w, _)| w.starts_with("button:sample:"))); +} + +#[test] +fn a_temporary_session_offers_no_samples() { + // nothing done there is saved: samples would only be lost + let mut a = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default()); + a.ui.view = ViewMode::PhotoGrid; + a.library_problem = Some(crate::panels::library_problem::LibraryProblem { + dismissed: true, + ..crate::panels::library_problem::LibraryProblem::new("/nowhere", "test") + }); + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + h.step(); + assert!(has(&h, "button:emptyImportPhotos")); + assert!(!has(&h, "button:emptySamples")); + assert!(!h.app.widgets.iter().any(|(w, _)| w.starts_with("button:sample:"))); +} + +#[test] +fn the_welcome_keeps_clear_of_the_grid_header() { + // a short window: the welcome sits below "All Photos", never over it + for size in [[1300.0, 440.0], [1300.0, 900.0]] { + let h = headless(library(&format!("header-{}", size[1])), size); + let title = h.app.widgets.iter().find(|(w, _)| w == "text:emptyTitle").map(|(_, r)| *r).unwrap(); + // the header is 44 points under the 42-point top bar + assert!(title.top() >= 42.0 + 44.0, "{size:?}: the title starts at {}", title.top()); + } +} diff --git a/crates/ui-egui/src/tests_welcome_access.rs b/crates/ui-egui/src/tests_welcome_access.rs new file mode 100644 index 00000000000..2f5770a873c --- /dev/null +++ b/crates/ui-egui/src/tests_welcome_access.rs @@ -0,0 +1,167 @@ +//! The welcome reaches everyone: a screen reader hears its words (the title as a heading), the +//! keyboard starts on Import Photos… in a new library with a ring showing where it is, and dim +//! text reads at WCAG AA (4.5:1) in every theme. + +use std::cell::Cell; +use std::rc::Rc; +use std::time::Duration; + +use egui::{Rect, pos2, vec2}; +use serde_json::json; + +use crate::headless::Headless; +use crate::state::ViewMode; +use crate::theme::{ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +/// (role, name, value) of every node a frame of `draw` gives screen readers. +fn nodes(draw: impl Fn(&mut egui::Ui)) -> Vec<(String, String, String)> { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let mut found = Vec::new(); + for _ in 0..3 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| draw(ui)); + out.textures_delta.clear(); + if let Some(update) = out.platform_output.accesskit_update.take() { + found = update + .nodes + .iter() + .map(|(_, n)| (format!("{:?}", n.role()), n.label().unwrap_or_default().to_string(), n.value().unwrap_or_default().to_string())) + .collect(); + } + } + found +} + +#[test] +fn a_screen_reader_hears_the_welcome_not_just_its_buttons() { + let actions = [crate::panels::EmptyAction { command: "file.addPhotos", label: "Import Photos…", widget: "button:emptyImportPhotos" }]; + let found = nodes(|ui| { + let r = ui.max_rect(); + let _ = crate::panels::empty_state( + ui, + r, + "Welcome to LightCraft", + "Start with photos of your own.", + &actions, + Some("or drop photos and folders into this window"), + 0.0, + false, + ); + crate::panels::empty_note(ui, Rect::from_min_size(pos2(0.0, 0.0), vec2(300.0, 100.0)), "Import photos to get started"); + }); + let has = |role: &str, words: &str| found.iter().any(|(r, l, v)| r == role && (l == words || v == words)); + // each text is read once: a heading by its name, other text by its value + assert!(found.iter().all(|(_, l, v)| l.is_empty() || v.is_empty()), "words read twice: {found:?}"); + assert!(has("Heading", "Welcome to LightCraft"), "the title, as a heading: {found:?}"); + assert!(has("Label", "Start with photos of your own."), "the body: {found:?}"); + assert!(has("Label", "or drop photos and folders into this window"), "the hint: {found:?}"); + assert!(has("Button", "Import Photos…"), "{found:?}"); + assert!(has("Label", "Import photos to get started"), "the right panel's note: {found:?}"); +} + +fn library(tag: &str) -> lightcraft_engine::Session { + let dir = std::env::temp_dir().join(format!("lc-ui-access-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = lightcraft_engine::Session::new().with_fs(); + s.open_library(dir.join("lib"), false).unwrap(); + s +} + +#[test] +fn the_keyboard_starts_on_import_photos_in_a_new_library() { + // Given a new library's welcome, with a picker that counts being asked + let mut a = LightcraftApp::new(library("focus"), Services::default()); + a.ui.view = ViewMode::PhotoGrid; + let asked = Rc::new(Cell::new(0)); + let seen = asked.clone(); + a.services.pick_files = Some(Box::new(move || { + seen.set(seen.get() + 1); + Vec::new() + })); + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + h.step(); + // When Enter is pressed, with no click before it + assert_eq!(h.request("ui.key", json!({"key": "Enter"}), T)["ok"], true); + h.step(); + h.step(); + // Then Import Photos… asked for the photos + assert_eq!(asked.get(), 1, "the keyboard was on Import Photos…"); +} + +/// A new library's welcome, with a picker that counts being asked. +fn welcome_counting_picks(tag: &str) -> (Headless, Rc>) { + let mut a = LightcraftApp::new(library(tag), Services::default()); + a.ui.view = ViewMode::PhotoGrid; + let asked = Rc::new(Cell::new(0)); + let seen = asked.clone(); + a.services.pick_files = Some(Box::new(move || { + seen.set(seen.get() + 1); + Vec::new() + })); + let mut h = Headless::new(a, [1300.0, 900.0], 1.0); + h.step(); + h.step(); + h.step(); + (h, asked) +} + +#[test] +fn the_keyboard_is_put_on_import_photos_once() { + // a person who moved it away keeps it away: Esc lets go, and Enter then starts nothing + let (mut h, asked) = welcome_counting_picks("once"); + assert_eq!(h.request("ui.key", json!({"key": "Escape"}), T)["ok"], true); + h.step(); + h.step(); + h.step(); + assert_eq!(h.request("ui.key", json!({"key": "Enter"}), T)["ok"], true); + h.step(); + h.step(); + assert_eq!(asked.get(), 0, "focus wasn't put back"); +} + +#[test] +fn shortcuts_still_work_with_the_keyboard_on_the_welcome() { + // the welcome's focus keeps Enter and Space; Import Photos…'s own shortcut, and the rest, act + let (mut h, asked) = welcome_counting_picks("shortcut"); + assert!(crate::widgets::plain_button_has_focus(&h.view.ctx), "the keyboard is on the welcome first"); + assert_eq!(h.request("ui.key", json!({"key": "I", "cmd": true, "shift": true}), T)["ok"], true); + h.step(); + h.step(); + assert_eq!(asked.get(), 1, "Cmd/Ctrl+Shift+I opened Import Photos…"); + assert!(!h.app.text_focus, "a focused button isn't a text field"); +} + +/// WCAG 2 contrast of two colours. +fn contrast(a: egui::Color32, b: egui::Color32) -> f32 { + let lum = |c: egui::Color32| { + let ch = |v: u8| { + let v = v as f32 / 255.0; + if v <= 0.03928 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * ch(c.r()) + 0.7152 * ch(c.g()) + 0.0722 * ch(c.b()) + }; + let (x, y) = (lum(a), lum(b)); + (x.max(y) + 0.05) / (x.min(y) + 0.05) +} + +#[test] +fn dim_text_reads_at_aa_on_every_surface_of_every_theme() { + // the welcome's body and hint, the right panel's note, the sidebar's counts: 12–13 pt + for kind in ThemeKind::ALL { + let t = Tokens::for_kind(kind); + for (surface, colour) in [("chrome", t.chrome), ("canvas", t.canvas), ("grid", t.grid_bg)] { + let c = contrast(t.text_dim, colour); + assert!(c >= 4.5, "{kind:?} text_dim on {surface}: {c:.2}:1"); + } + // and it stays dimmer than the labels it sits under + assert!(contrast(t.text_label, t.grid_bg) > contrast(t.text_dim, t.grid_bg), "{kind:?}"); + } +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 57ee987d1d0..ef7097f82f4 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -136,7 +136,8 @@ impl Default for Tokens { tool_active: Color32::from_rgb(0x3f, 0x3f, 0x3f), text: Color32::from_rgb(0xe2, 0xe2, 0xe2), text_label: Color32::from_rgb(0xbc, 0xbc, 0xbc), - text_dim: Color32::from_rgb(0x8e, 0x8e, 0x8e), + // 4.5:1 or more on chrome, canvas and the grid (WCAG AA for the 12–13 pt it sets) + text_dim: Color32::from_rgb(0x94, 0x94, 0x94), text_disabled: Color32::from_rgb(0x5c, 0x5c, 0x5c), icon: Color32::from_rgb(0x9a, 0x9a, 0x9a), track: Color32::from_rgb(0x5a, 0x5a, 0x5a), @@ -200,7 +201,7 @@ impl Tokens { tool_active: rgb(0xcacaca), text: rgb(0x1c1c1c), text_label: rgb(0x383838), - text_dim: rgb(0x6a6a6a), + text_dim: rgb(0x585858), text_disabled: rgb(0xa2a2a2), icon: rgb(0x555555), track: rgb(0xa8a8a8), @@ -230,7 +231,7 @@ impl Tokens { tool_active: rgb(0xe2e2e2), text: rgb(0x161616), text_label: rgb(0x343434), - text_dim: rgb(0x707070), + text_dim: rgb(0x6b6b6b), text_disabled: rgb(0xababab), icon: rgb(0x585858), track: rgb(0xbdbdbd), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index a00bca4b214..22843282116 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -941,6 +941,37 @@ mod access_tests { } } +/// The plain buttons drawn last pass and this one (the welcome's, its sample thumbnails): with the +/// keyboard on one, only the keys that work it stay with it, and the rest reach shortcuts. +#[derive(Clone, Default)] +struct PlainButtons { + pass: u64, + ids: Vec, + last: Vec, +} + +/// `id` is a plain button: focused, it keeps Enter, Space, Tab, Esc and the arrows, nothing else. +pub(crate) fn plain_button(ctx: &egui::Context, id: egui::Id) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| { + let b = d.get_temp_mut_or_default::(egui::Id::new("plain-buttons")); + if b.pass != pass { + b.last = std::mem::take(&mut b.ids); + b.pass = pass; + } + b.ids.push(id); + }); +} + +/// The keyboard is on a plain button ([`plain_button`]) drawn this pass or the one before: ids from +/// passes longer ago (the welcome gone) say nothing about a widget that has one now. +pub(crate) fn plain_button_has_focus(ctx: &egui::Context) -> bool { + let Some(focused) = ctx.memory(|m| m.focused()) else { return false }; + let pass = ctx.cumulative_pass_nr(); + ctx.data(|d| d.get_temp::(egui::Id::new("plain-buttons"))) + .is_some_and(|b| (b.pass.saturating_add(1) >= pass && b.ids.contains(&focused)) || (b.pass == pass && b.last.contains(&focused))) +} + /// Names a widget for screen readers (`name` replaces what egui gave it): for a plain egui field /// whose caption is a separate label beside it. pub(crate) fn screen_reader_name(ctx: &egui::Context, id: egui::Id, name: &str) { diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 95dcd2aefcb..cf52bd7a06b 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -475,7 +475,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-SIDEBAR-REORDER | Reorder left-sidebar sections | P2 | ✅ | `cmd:view.sidebarMoveSection`, `crates/ui-egui/src/sidebar.rs` (`move_before`, `move_by`), `crates/ui-egui/src/panels/left.rs` (`section_drag`, `section_drop_before`, `section_drag_feedback`), `crates/ui-egui/src/tests_panels.rs` | drag a section by its header: its name follows the pointer, a line (`sidebarSectionDrop`) shows the gap it would go to (above the section whose upper half the pointer is over, or below the last), releasing over the sidebar moves it there, Esc or releasing elsewhere leaves it; the sidebar scrolls when the drag nears its top or bottom edge, also over a pinned header (a section picked up by the pinned header scrolls once the pointer has left it). A press on a header's button is never a section drag. A click on the header still folds the section, and an album dragged onto the Albums header is still an album drag. The header's menu has Move Up / Move Down (`sidebarMenu:moveUp` / `moveDown`), one shown section at a time, stepping over hidden ones, disabled at the ends. `view.sidebarMoveSection` `{section, direction: up\|down}` or `{section, before:
\|null}` (null: last) answers `{moved, order}`. The order is kept with the UI state (`sidebar`). Recently Deleted is listed with My Photos (below Picks / Missing Photos), not after the sections. Not here: dragging My Photos, or rows from one section into another | | LR-BEHAV-SIDEBAR-STICKY | Pinned section header and section look | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`pinned_header`, `section_header`, `empty_hint`), `crates/ui-egui/src/tests_panels.rs` | while the rows of an open section are in view but its header has scrolled away, a copy of the header (`sidebarSectionPinned:`, with the section's buttons and menu) stays at the top of the sidebar; the next section's header pushes it out; folding from it brings the section's own header into view. Rows scrolled beneath the pinned header are covered by it: an album or photos dropped on the pinned Albums header go to the top level / nowhere, never to the row under it; folding from it keeps the sideways scroll. Sections are told apart by a hairline in the gap above each; the fold chevron sits in the gutter, in the column of the rows' triangles (`sidebarSectionChevron:`); a header highlights under the pointer; a folded section shows how many top-level rows it holds (`sidebarSectionCount:`, with Show Photo Counts); a count of 0 is fainter. Not here: a height of its own per section (one scroll area serves the whole sidebar), a count for Recently Added, Local's Browse Folder… as a header button | | LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests_panels.rs` | drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed | -| LR-BEHAV-EMPTY-STATES | Empty states | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`empty_message`, `empty_state`), `crates/ui-egui/src/panels/empty_library.rs`, `cmd:file.addPhotos`, `cmd:file.importLightroom`, `crates/ui-egui/src/tests_empty_library.rs` | each view says why it is empty (no photo selected, filters, an empty folder). A library with no photos (none, or only deleted or browsed ones) opens on the Photo Grid (Square Grid stays) with the sidebar, and the grid and Detail view (not while a folder is browsed under Local) offer Import Photos… (primary) and Import Lightroom Catalog… (desktop) as buttons, with a line saying photos and folders can be dropped into the window and the key Import Photos… is bound to now; the right-hand panel says to import photos first. The top bar has an Import button beside Export in every library. No drop-target highlight while files are dragged over the window yet, and a drop imports without the review the menu opens | +| LR-BEHAV-EMPTY-STATES | Empty states | P1 | ✅ | `crates/ui-egui/src/panels/mod.rs` (`empty_message`, `empty_state`), `crates/ui-egui/src/panels/empty_library.rs`, `crates/ui-egui/src/panels/samples.rs`, `crates/engine/src/demo.rs`, `cmd:file.addPhotos`, `cmd:file.importLightroom`, `cmd:library.addSamples`, `cmd:library.removeSamples`, `crates/ui-egui/src/tests_empty_library.rs`, `crates/ui-egui/src/tests_samples.rs` | each view says why it is empty (no photo selected, filters, an empty folder). A library with no photos (none, or only deleted or browsed ones) opens on the Photo Grid (Square Grid stays) with the sidebar, and the grid and Detail view (not while a folder is browsed under Local) offer Import Photos… (primary) and Import Lightroom Catalog… (desktop) as buttons, with a line saying photos and folders can be dropped into the window and the key Import Photos… is bound to now; the right-hand panel says to import photos first. A new desktop library starts empty and welcomes with Import Photos…, Import Lightroom Catalog… and a row of sample photos (one click adds them and opens that one in Detail, as every other way of adding them to an empty library opens the first, with a banner inviting the first edit; a Try Sample Photos button where the row doesn't fit and on the web); while the library is empty the Tools panel steps aside (back as it was with the first photos, an editing tool as Edit) and the bottom bar's rating and flags wait; while sample photos are in, a banner offers Import / Remove Sample Photos, or Remove / Keep Them once photos of your own are in (removal takes the albums only samples filled, one undo step). The welcome's words are readable by screen readers (the title as a heading), a new library's welcome puts the keyboard on Import Photos… with a focus ring, its hint mentions looking through a folder under Local without importing, and dim text meets 4.5:1 on the panels, canvas and grid in every theme. The top bar has an Import button beside Export in every library. No drop-target highlight while files are dragged over the window yet, and a drop imports without the review the menu opens | | LR-BEHAV-TOOLTIPS | Tooltips with shortcuts | P0 | ✅ | `crates/ui-egui/src/panels/bottombar.rs` | | | LR-BEHAV-TEXTFIELD | Text fields behave alike | P1 | 🟡 | `crates/ui-egui/src/text_field.rs`, `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/panels/right.rs` (`meta_field`), `crates/ui-egui/src/panels/dialogs.rs`, `crates/ui-egui/src/panels/unnamed.rs` | one shared field: right-click Cut / Copy / Paste / Select All (no Paste in the browser), Esc gives back the text from before the edit, Return / leaving / Esc reported to the caller, optional select-on-focus; agents use `ui.clipboard` (MCP `clipboard`) and `ui.inspect` → `copied`. Used by Search Photos, slider values, the Info panel's metadata fields (multi-line captions), the one-field dialogs (New / Rename Album, New Smart Album, Rename / Merge Keywords, text prompts) and the unnamed faces' name field so far; the other text fields (most dialogs, import, settings, masking, keywords …) still use egui's own and have no menu | | LR-BEHAV-HEADLESS | Headless UI snapshots | P2 | ✅ | `apps/lightcraft-cli/src/main.rs`, `crates/ui-egui/src/headless.rs`, `docs/control-protocol.md` | `snapshot` rasterizes the UI and defaults photo development to the CPU before the first frame, without adapter discovery; scaled dimensions are validated before allocation, and UI zoom preserves the requested physical viewport; JSON-lines control scripts are supported | diff --git a/docs/whats-new.md b/docs/whats-new.md index 97e1367a89c..ef6210a2088 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -137,7 +137,8 @@ ### Reliability ### One kind of button -- Dialogs' buttons and About's Discord link are drawn by one button component: primary (filled with the accent), +- Dialogs' buttons, About's Discord link, the empty library's welcome and the samples banner are drawn by one button + component: primary (filled with the accent), secondary, danger (filled red) and ghost, in three sizes, with an icon or without, and an icon alone (named for screen readers). Each darkens a little when hovered and more when pressed, shows a ring where the keyboard is, and its text reads at 4.5:1 or more on its fill in every theme. Dialog buttons are 30 points tall, like the welcome's. @@ -151,6 +152,41 @@ further ⇧-clicks carry on from the last point, as in Lightroom. Change the brush size, feather or flow before the ⇧-click and the line tapers from the old values to the new ones. The whole line is one undo step. `mask.brushStroke {connect: true}` does the same for agents. +### Every way to the samples leads to the editor +- However the sample photos come into an empty library (a thumbnail, the welcome's Try Sample Photos button, Help ▸ + Add Sample Photos, an agent), they open on a sample in Detail with the Edit panel, ready to edit; a thumbnail opens + the one clicked. A library that already has photos stays where it was. +- There, until the first change, the banner invites one: "Drag any slider: the original never changes. Press Y to + compare before and after." (the key Compare Before and After is bound to). + +### The welcome reads for everyone +- Screen readers now hear the empty library's welcome, not only its buttons: the title (as a heading), what it says, + the hint and the sample row's caption, and the right panel's note beside it. +- A new library's welcome puts the keyboard on Import Photos…, so Enter or Space starts; the welcome's buttons show an + accent ring where the keyboard is. +- Dimmed text (captions, hints, counts, the right panel's notes) is a shade stronger in every theme, most in the light + ones, so it reads at WCAG AA (4.5:1) on the panels, the canvas and the grid: Charcoal and Midnight #949494, Silver + #585858, Paper #6b6b6b. +- The welcome also says that a folder can be looked through without importing it, under Local in the sidebar (the + desktop app). + +### The welcome has the window +- While the library is empty, the welcome is the one thing asking for attention: the Tools panel steps aside (it comes + back as it was once photos arrive, an editing tool such as Crop as the Edit panel; opening it meanwhile keeps it + open), and the bottom bar's rating, flags and + Copy Edit Settings wait until there is a photo to use them on. +- Under the welcome's buttons, a row of five sample photos: click one to add the samples and open it in Detail with the + Edit panel, ready to edit. Where the row doesn't fit, and in the web build, Try Sample Photos is a button as before. + +### A new library asks how to begin +- A new library made by the desktop app now starts empty instead of quietly filling with the 24 procedural demo + photos. Its first screen, "Welcome to LightCraft", offers Import Photos…, Import Lightroom Catalog… and Try Sample + Photos. `--memory` still starts with the demo photos (`--no-demo` for none), as do `lightcraft-cli --demo` and the + web build. +- While sample photos are in a library, a banner says so and offers Import Photos… and Remove Sample Photos; once + photos of your own are in, it offers Remove Sample Photos or Keep Them. Removing them takes the sample photos and + the albums only they filled (an album holding a photo of yours stays, with it), in one step Edit ▸ Undo reverses. + Help ▸ Add Sample Photos and Help ▸ Remove Sample Photos do the same at any time. ### Hard-edged Heal and Clone spots - A spot with Feather at 0 no longer draws black pixels exactly on its radius. This also fixes spots at 0% Opacity