LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Skip offscreen Local rows and share hidden-folder checks
dotCooCood826e79fa201
diff --cc apps/lightcraft-web/src/web.rsindex 31fe2cb0a,6e9e85596..bd5215e4d--- a/apps/lightcraft-web/src/web.rs+++ b/apps/lightcraft-web/src/web.rs@@@ -175,6 -175,6 +175,7 @@@ fn services(originals: Originals, backelet (backup_backend, backup_files) = (backend.clone(), files);let restore_backend = backend.clone();Services {++ local_places: None,picker: None,pick_display_profile: None,screen_profile: None,diff --cc apps/lightcraft/src/session.rsindex 000000000,ce3ab95b7..b886b472fmode 000000,100644..100644--- a/apps/lightcraft/src/session.rs+++ b/apps/lightcraft/src/session.rs@@@ -1,0 -1,297 +1,298 @@@+ #[cfg(any(target_os = "freebsd", target_os = "linux"))]+ use super::platform::DIALOG_PARENT;+ use super::platform::{explorer_select_command, file_dialog, windows_open_url_command};+ use super::prefs::display_profile_dir;+ use super::*;++ /// The platform services; `cc` is the window the file dialogs belong to (its `egui_ctx` repaints+ /// when a dialog closes), and `log_file` is for Help ▸ Open Log Folder.+ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path>) -> Services {+ let ctx = cc.egui_ctx.clone();+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]+ let _ = DIALOG_PARENT.set(rfd::FileDialog::new().set_parent(cc));+ Services {++ local_places: None,+ // Commands' file dialogs run on their own thread (#191): a dialog on the UI thread+ // stopped the window answering the compositor, which then reported the app as hung.+ picker: Some(Box::new(move |req: lightcraft_ui_egui::pick::PickRequest| {+ use lightcraft_ui_egui::pick::PickKind;+ let (tx, rx) = std::sync::mpsc::channel();+ let repaint = ctx.clone();+ std::thread::Builder::new()+ .name("file-dialog".into())+ .spawn(move || {+ let mut d = file_dialog();+ if let Some(t) = &req.title {+ d = d.set_title(t);+ }+ if let Some((name, exts)) = &req.filter {+ d = d.add_filter_nocase(name.clone(), exts);+ }+ if let Some(n) = &req.file_name {+ d = d.set_file_name(n);+ }+ let s = |p: std::path::PathBuf| p.to_string_lossy().to_string();+ let paths: Vec<String> = match req.kind {+ PickKind::Files => d.pick_files().unwrap_or_default().into_iter().map(s).collect(),+ PickKind::File => d.pick_file().map(s).into_iter().collect(),+ PickKind::Folder => d.pick_folder().map(s).into_iter().collect(),+ PickKind::Save => d.save_file().map(s).into_iter().collect(),+ };+ // the app may have quit meanwhile: nobody to tell+ let _ = tx.send(paths);+ repaint.request_repaint();+ })+ .map_err(|e| format!("could not start the file dialog: {e}"))?;+ Ok(rx)+ })),+ log_file: log_file.map(|p| p.display().to_string()),+ pick_lightroom_catalog: Some(Box::new(|| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Import Lightroom Catalog"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat"])+ .pick_file()+ .map(|p| p.to_string_lossy().to_string())+ })),+ pick_folder: Some(Box::new(|| {+ file_dialog().set_title(lightcraft_ui_egui::i18n::tr("Open Library")).pick_folder().map(|p| p.to_string_lossy().to_string())+ })),+ #[cfg(target_os = "linux")]+ open_model_folder: Some(std::sync::Arc::new(|path: &str| {+ std::process::Command::new("xdg-open")+ .arg(path)+ .status()+ .map_err(|e| e.to_string())+ .and_then(|s| if s.success() { Ok(()) } else { Err(format!("opening folder failed: {s}")) })+ })),+ open_with: Some(Box::new(editors::open_with)),+ open_all_with: Some(Box::new(editors::open_all_with)),+ check_editor: Some(Box::new(editors::check)),+ open_url: Some(Box::new(|url: &str| {+ if !url.starts_with("https://") {+ return Err("only https links are opened".into());+ }+ let status = if cfg!(target_os = "macos") {+ std::process::Command::new("open").arg(url).status()+ } else if cfg!(target_os = "windows") {+ windows_open_url_command(url).status()+ } else {+ std::process::Command::new("xdg-open").arg(url).status()+ };+ status.map(|_| ()).map_err(|e| e.to_string())+ })),+ reveal: Some(Box::new(|path: &str| {+ let status = if cfg!(target_os = "macos") {+ std::process::Command::new("open").args(["-R", path]).status()+ } else if cfg!(target_os = "windows") {+ explorer_select_command(path).status()+ } else {+ let dir = std::path::Path::new(path).parent().map(|d| d.to_string_lossy().to_string()).unwrap_or_else(|| ".".into());+ std::process::Command::new("xdg-open").arg(dir).status()+ };+ status+ .map_err(|e| e.to_string())+ .and_then(|s| if s.success() || cfg!(target_os = "windows") { Ok(()) } else { Err(format!("reveal failed: {s}")) })+ })),+ pick_files: Some(Box::new(|| {+ file_dialog()+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Photos"), lightcraft_engine::import::EXTENSIONS)+ .pick_files()+ .unwrap_or_default()+ .into_iter()+ .map(|p| p.to_string_lossy().to_string())+ .collect()+ })),+ pick_denoise_model: Some(Box::new(|| {+ file_dialog()+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("ONNX model"), &["onnx"])+ .pick_file()+ .map(|p| vec![p.to_string_lossy().into_owned()])+ .unwrap_or_default()+ })),+ pick_preset_files: Some(Box::new(|| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Import Presets"))+ .add_filter_nocase(+ lightcraft_ui_egui::i18n::tr("Presets & Profiles"),+ &["lcpreset", "xmp", "lrtemplate", "zip", "dng", "lmp", "mplumpack", "cube"],+ )+ .pick_files()+ .unwrap_or_default()+ .into_iter()+ .map(|p| p.to_string_lossy().to_string())+ .collect()+ })),+ pick_model_file: Some(Box::new(|| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Add a Face Recognition Model"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Face models (ONNX)"), &["onnx"])+ .pick_file()+ .map(|p| vec![p.to_string_lossy().to_string()])+ .unwrap_or_default()+ })),+ pick_tracklog: Some(Box::new(|| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Auto-Tag from Tracklog"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("GPS Track Log"), &["gpx"])+ .pick_file()+ .map(|p| vec![p.to_string_lossy().to_string()])+ .unwrap_or_default()+ })),+ // macOS doesn't colour-manage the window: previews follow the screen's profile (#787)+ #[cfg(target_os = "macos")]+ screen_profile: Some(Box::new(screen_profile::icc)),+ // Linux: the profile the desktop assigns in colord, read off the UI thread+ #[cfg(target_os = "linux")]+ screen_profile: Some(colord::service()),+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]+ screen_profile: None,+ pick_display_profile: Some(Box::new(|| {+ let mut d = file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Choose Monitor Profile"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("ICC Profiles"), &["icc", "icm"]);+ if let Some(dir) = display_profile_dir() {+ d = d.set_directory(dir);+ }+ d.pick_file().map(|p| vec![p.to_string_lossy().to_string()]).unwrap_or_default()+ })),+ save_preset_file: Some(Box::new(|name: &str| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Export Presets"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("LightCraft Preset"), &["lcpreset"])+ .set_file_name(name)+ .save_file()+ .map(|p| p.to_string_lossy().to_string())+ })),+ pick_keyword_list: Some(Box::new(|| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Import Keywords"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Keyword Lists"), &["txt", "utf8"])+ .pick_file()+ .map(|p| vec![p.to_string_lossy().to_string()])+ .unwrap_or_default()+ })),+ save_keyword_list: Some(Box::new(|name: &str| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Export Keywords"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Keyword Lists"), &["txt"])+ .set_file_name(name)+ .save_file()+ .map(|p| p.to_string_lossy().to_string())+ })),+ pick_curve_preset_files: Some(Box::new(|| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Import Point Curve Presets"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Point Curve Presets"), &["lccurve", "json"])+ .pick_files()+ .unwrap_or_default()+ .into_iter()+ .map(|p| p.to_string_lossy().to_string())+ .collect()+ })),+ save_curve_preset_file: Some(Box::new(|name: &str| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Export Point Curve Presets"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Point Curve Presets"), &["lccurve"])+ .set_file_name(name)+ .save_file()+ .map(|p| p.to_string_lossy().to_string())+ })),+ pick_slideshow_templates: Some(Box::new(|| {+ rfd::FileDialog::new()+ .set_title(lightcraft_ui_egui::i18n::tr("Import Slideshow Templates"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Slideshow Templates"), &["json"])+ .pick_files()+ .unwrap_or_default()+ .into_iter()+ .map(|p| p.to_string_lossy().to_string())+ .collect()+ })),+ save_slideshow_template: Some(Box::new(|name: &str| {+ rfd::FileDialog::new()+ .set_title(lightcraft_ui_egui::i18n::tr("Export Slideshow Template"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Slideshow Templates"), &["json"])+ .set_file_name(name)+ .save_file()+ .map(|p| p.to_string_lossy().to_string())+ })),+ pick_print_templates: Some(Box::new(|| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Import Print Templates"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Print Templates"), &[lightcraft_engine::print::template::FILE_EXT])+ .pick_files()+ .unwrap_or_default()+ .into_iter()+ .map(|p| p.to_string_lossy().to_string())+ .collect()+ })),+ save_print_template: Some(Box::new(|name: &str| {+ file_dialog()+ .set_title(lightcraft_ui_egui::i18n::tr("Export Print Template"))+ .add_filter_nocase(lightcraft_ui_egui::i18n::tr("Print Templates"), &[lightcraft_engine::print::template::FILE_EXT])+ .set_file_name(name)+ .save_file()+ .map(|p| p.to_string_lossy().to_string())+ })),+ // atomic (temp file + sync + rename): a failed write never leaves a truncated file+ write_shared: Some(std::sync::Arc::new(lightcraft_engine::export::write_file)),+ write: Some(Box::new(lightcraft_engine::export::write_file)),+ write_new: Some(Box::new(lightcraft_engine::export::write_file_new)),+ png: Some(Box::new(|img: &lightcraft_raster::Rgba8| {+ lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default()+ })),+ // the library is a folder on disk: backed up with the user's other files+ backup_library: None,+ restore_library: None,+ system_theme: appearance::service(),+ }+ }++ /// The library session with the folders face models (`<config>/models`) and slideshow templates+ /// (`<config>/slideshow-templates`) are kept in. With [`Launch::Ask`] no library is opened yet:+ /// the window lists the recent ones.+ pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) -> (Session, Option<LibraryProblem>) {+ let (mut s, problem) = match launch {+ Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_system_clock(), None),+ Launch::Open { dir, .. } => open_library_session(in_memory, dir.clone(), seed_demo),+ };+ s.face_models_dir = lightcraft_engine::config::default_face_models_dir();+ s.slide_templates_dir = lightcraft_engine::config::config_dir().map(|d| d.join(lightcraft_engine::slide_template::DIR_NAME));+ // Control requests are answered on the UI thread: Add to Apple Photos must not wait there+ s.apple_photos_background = true;+ (s, problem)+ }++ /// The persistent library session, or with `--memory` an in-memory one (demo photos).+ ///+ /// If the library can't be opened the session is empty and in memory — never seeded with the+ /// demo photos, never written anywhere — and the problem is returned: the window then says so+ /// and offers Try Again / Choose Another Library… / Continue Without Saving / Quit (issue #100).+ fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, seed_demo: bool) -> (Session, Option<LibraryProblem>) {+ if in_memory {+ return (if seed_demo { Session::with_demo() } else { Session::new() }.with_fs().with_default_denoise_models().with_system_clock(), None);+ }+ let unopened = || Session::new().with_fs().with_default_denoise_models().with_system_clock();+ let Some(dir) = dir else {+ log::warn!("no library location (set --library or LIGHTCRAFT_LIBRARY)");+ return (unopened(), Some(LibraryProblem::new("", "There is no home folder to keep the library in. Choose a folder for it.")));+ };+ 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) {+ Ok(r) => {+ let (replayed, torn) = (r.replayed, r.torn_bytes);+ log::info!(+ "library {}: {} photos, {replayed} log records replayed{} ({:.1} ms)",+ dir.display(),+ s.catalog.len(),+ if torn > 0 { ", torn tail repaired" } else { "" },+ t0.elapsed().as_secs_f64() * 1000.0+ );+ (s, None)+ }+ Err(e) => {+ log::error!("can't open library {}: {e}", dir.display());+ (unopened(), Some(LibraryProblem::new(dir.to_string_lossy(), e.to_string())))+ }+ }+ }diff --cc crates/engine/src/cmd/browse.rsindex 6f3f88963,6f3f88963..b24246592--- a/crates/engine/src/cmd/browse.rs+++ b/crates/engine/src/cmd/browse.rs@@@ -35,8 -35,8 +35,9 @@@ fn browse(s: &mut Session, p: &Value) -let mut v: Vec<String> = std::fs::read_dir(&dir).map_err(|e| bad(C, format!("{path}: {e}")))?.flatten()++ .filter(|e| !crate::walk::is_hidden_entry(e)).map(|e| e.path())-- .filter(|f| f.is_file() && is_supported(f) && !f.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')))++ .filter(|f| f.is_file() && is_supported(f)).map(|f| f.to_string_lossy().to_string()).collect();v.sort();diff --cc crates/engine/src/walk.rsindex 12dbadbd6,12dbadbd6..98290130e--- a/crates/engine/src/walk.rs+++ b/crates/engine/src/walk.rs@@@ -43,8 -43,8 +43,37 @@@ pub struct Walkedpub entries: usize,}--fn hidden(p: &Path) -> bool {-- p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.'))++/// Whether the entry has a dot-prefixed name or a Windows or macOS hidden attribute.++pub fn is_hidden_entry(entry: &std::fs::DirEntry) -> bool {++ hidden_with_metadata(&entry.path(), || entry.metadata())++}++++/// Whether the path has a dot-prefixed name or a Windows or macOS hidden attribute.++pub fn is_hidden_path(path: &Path) -> bool {++ hidden_with_metadata(path, || std::fs::symlink_metadata(path))++}++++fn hidden_with_metadata(path: &Path, metadata: impl FnOnce() -> std::io::Result<std::fs::Metadata>) -> bool {++ if path.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')) {++ return true;++ }++ #[cfg(windows)]++ {++ use std::os::windows::fs::MetadataExt;++ const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;++ metadata().is_ok_and(|m| m.file_attributes() & FILE_ATTRIBUTE_HIDDEN != 0)++ }++ #[cfg(target_os = "macos")]++ {++ use std::os::darwin::fs::MetadataExt;++ const UF_HIDDEN: u32 = 0x0000_8000;++ metadata().is_ok_and(|m| m.st_flags() & UF_HIDDEN != 0)++ }++ #[cfg(not(any(windows, target_os = "macos")))]++ {++ let _ = metadata;++ false++ }}/// What a folder's listing says an entry is.@@@ -120,7 -120,7 +149,7 @@@ fn walk(root: &Path, skip: Option<&Pathlet p = e.path();// (a hidden entry's kind is only asked for when the listing is wanted; every other// entry's is asked once)-- let is_hidden = hidden(&p);++ let is_hidden = is_hidden_entry(&e);if is_hidden && listed.is_none() {continue;}@@@ -178,6 -178,6 +207,34 @@@ mod testsd}++ #[test]++ fn hidden_names_and_platform_attributes_are_excluded_from_walks() {++ let root = tmp("hidden-attributes");++ for folder in [".dot", "Hidden"] {++ std::fs::create_dir_all(root.join(folder)).unwrap();++ std::fs::write(root.join(folder).join("inside.jpg"), b"x").unwrap();++ }++ for file in ["Shown.jpg", ".dot.jpg", "hidden.jpg"] {++ std::fs::write(root.join(file), b"x").unwrap();++ }++ for name in ["Hidden", "hidden.jpg"] {++ #[cfg(windows)]++ assert!(std::process::Command::new("attrib").arg("+h").arg(root.join(name)).status().unwrap().success());++ #[cfg(target_os = "macos")]++ assert!(std::process::Command::new("chflags").arg("hidden").arg(root.join(name)).status().unwrap().success());++ assert_eq!(is_hidden_path(&root.join(name)), cfg!(any(windows, target_os = "macos")));++ }++ let mut found = files_in(&root, None, Limits::default(), |_| true).files;++ found.sort();++ let mut expected = vec![root.join("Shown.jpg")];++ if !cfg!(any(windows, target_os = "macos")) {++ expected.extend([root.join("Hidden/inside.jpg"), root.join("hidden.jpg")]);++ }++ expected.sort();++ assert_eq!(found, expected);++ std::fs::remove_dir_all(root).unwrap();++ }++/// Given a folder with files, a folder inside it, a hidden file and a link, when it is walked/// with its listings noted, then the walk finds what it finds without them, and each folder's/// listing holds every entry by name with its kind (hidden ones too, a link as neither file nordiff --cc crates/ui-egui/src/dialogs/import/scan.rsindex 000000000,ee237fd5a..a930af00cmode 000000,100644..100644--- a/crates/ui-egui/src/dialogs/import/scan.rs+++ b/crates/ui-egui/src/dialogs/import/scan.rs@@@ -1,0 -1,272 +1,269 @@@+ use super::task::ImportTask;+ use super::*;++ /// A folder scan running on a worker thread (a network share can take minutes to read; the+ /// window must keep answering meanwhile).+ pub struct ScanTask {+ progress: std::sync::Arc<ScanProgress>,+ rx: std::sync::mpsc::Receiver<ScanOutput>,+ /// Open the review with "copy into the library" checked (a camera / card).+ pub copy: bool,+ /// Open the review with this album chosen (an album's context menu ▸ Import…).+ pub album: Option<u64>,+ /// Browsing a folder (Local): the photos are read in place instead of opening the review.+ pub(super) browse: bool,+ /// What is being scanned (the review's source).+ sources: Vec<String>,+ /// The scan's row in the activity stack (its ✕ and `activity.cancel` set `progress.cancel`).+ guard: lightcraft_engine::activity::TaskGuard,+ }++ /// The activity row of a scan: the review's ("Scanning folder") or the Local view's ("Reading folder").+ fn scan_guard(app: &LightcraftApp, progress: &ScanProgress, browse: bool) -> lightcraft_engine::activity::TaskGuard {+ let label = if browse { "Reading folder" } else { "Scanning folder" };+ app.session.activity.start("scan", label, lightcraft_engine::activity::Cancel::Flag(progress.cancel.clone()))+ }++ /// An import and a Synchronize Folder never run at once: each readies its files against the+ /// library as it was when it started, so both could add the same file.+ pub(crate) fn busy_synchronizing(app: &LightcraftApp) -> Result<(), String> {+ if app.sync_run.is_some() { Err(crate::i18n::tr("A folder is being synchronized").to_string()) } else { Ok(()) }+ }++ /// Settings → Import → "Show the import review when a camera or card is connected", called with+ /// each device scan while it's on. The first look only notes the cards already in. A card that+ /// shows up after that opens Import from Device once nothing else is open, and a card that is+ /// taken out and put back in asks again.+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) fn cards_seen(app: &mut LightcraftApp, now: Vec<lightcraft_engine::devices::Device>) {+ let Some(known) = app.ui.known_cards.as_mut() else {+ app.ui.known_cards = Some(now.into_iter().map(|d| d.root).collect());+ return;+ };+ known.retain(|root| now.iter().any(|d| d.root == *root));+ let Some(card) = now.into_iter().find(|d| !known.contains(&d.root)) else { return };+ // busy: ask when the window is free (the card isn't noted until then)+ if app.import.is_some() || app.scan.is_some() || app.sync_run.is_some() || app.lightroom.is_some() || app.ui.dialog.is_some() {+ return;+ }+ known.push(card.root);+ if let Err(e) = app.run("file.addFromDevice", json!({"path": card.path})) {+ log::warn!("import from {}: {e}", card.name);+ }+ }++ /// Scan `paths` in the background, then open the review dialog (see [`poll_scan`]).+ pub fn open(app: &mut LightcraftApp, paths: Vec<String>) -> Result<Value, String> {+ if app.scan.is_some() {+ return Err("a scan is already running".into());+ }+ if app.review_pending.is_some() {+ return Err("an import review is waiting for the open dialog to close".into());+ }+ let sources = paths.clone();+ let (input, paths) = ScanInput::new(&mut app.session, &paths);+ let progress = std::sync::Arc::new(ScanProgress::default());+ let (tx, rx) = std::sync::mpsc::channel();+ let p = progress.clone();+ let job = move || {+ let _ = tx.send(scan_with(input, &paths, &p));+ };+ #[cfg(not(target_arch = "wasm32"))]+ std::thread::spawn(job);+ #[cfg(target_arch = "wasm32")]+ job();+ let guard = scan_guard(app, &progress, false);+ app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse: false, sources, guard });+ Ok(json!({"scanning": true}))+ }++ /// Show a folder's photos in the Local view (`library.browse` from the UI): the view switches at+ /// once, the folder is listed and read on a worker thread (a network share can take minutes),+ /// and the photos then join the view in small batches under a progress window. A browse already+ /// running is replaced; the import review's scan is not.+ pub fn browse(app: &mut LightcraftApp, path: &str, subfolders: Option<bool>) -> Result<Value, String> {+ let dir = std::path::absolute(std::path::Path::new(path)).map_err(|e| e.to_string())?;+ if !dir.is_dir() {+ return Err(format!("{path}: not a folder"));+ }+ if app.scan.as_ref().is_some_and(|t| !t.browse) || app.import.as_ref().is_some_and(|t| !t.browse) {+ return Err("an import is running".into());+ }+ let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string();+ let subfolders = subfolders.unwrap_or_else(|| app.session.browse.as_ref().is_some_and(|b| b.subfolders));+ let running = app.scan.as_ref().is_some_and(|t| t.browse) || app.import.as_ref().is_some_and(|t| t.browse);+ if running && app.session.browse.as_ref().is_some_and(|b| b.path == dir_s && b.subfolders == subfolders) {+ // already reading this folder: clicking it again must not restart the progress+ app.session.source = lightcraft_engine::LibrarySource::Folder;+ app.session.keep_active_in_view();+ return Ok(json!({"path": dir_s, "subfolders": subfolders, "scanning": true}));+ }+ if let Some(t) = app.scan.take() {+ t.progress.cancel.store(true, Ordering::Relaxed);+ }+ app.import = None;+ app.session.browse = Some(lightcraft_engine::Browse { path: dir_s.clone(), subfolders });+ app.session.source = lightcraft_engine::LibrarySource::Folder;+ // the photos the library already knows from this folder show at once: keep or pick the active one+ app.session.keep_active_in_view();+ let (input, _) = ScanInput::new(&mut app.session, std::slice::from_ref(&dir_s));+ let progress = std::sync::Arc::new(ScanProgress::default());+ let (tx, rx) = std::sync::mpsc::channel();+ let p = progress.clone();+ let root = dir_s.clone();+ let job = move || {+ let files: Vec<String> = if subfolders {+ lightcraft_engine::import::expand(&[root], None)+ } else {+ let mut v: Vec<String> = std::fs::read_dir(&root)+ .map(|rd| {+ rd.flatten()++ .filter(|e| !lightcraft_engine::walk::is_hidden_entry(e))+ .map(|e| e.path())- .filter(|f| {- f.is_file()- && lightcraft_engine::import::is_supported(f)- && !f.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.'))- })++ .filter(|f| f.is_file() && lightcraft_engine::import::is_supported(f))+ .map(|f| f.to_string_lossy().to_string())+ .collect()+ })+ .unwrap_or_default();+ v.sort();+ v+ };+ let _ = tx.send(scan_with(input, &files, &p));+ };+ #[cfg(not(target_arch = "wasm32"))]+ std::thread::spawn(job);+ #[cfg(target_arch = "wasm32")]+ job();+ let guard = scan_guard(app, &progress, true);+ app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse: true, sources: Vec::new(), guard });+ app.renderer.forget_imports();+ Ok(json!({"path": dir_s, "subfolders": subfolders, "scanning": true}))+ }++ /// Collect a finished scan and open the review (called every frame).+ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) {+ show_pending_review(app, ctx);+ let Some(task) = app.scan.as_ref() else { return };+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ let out = match task.rx.try_recv() {+ Ok(o) => o,+ Err(std::sync::mpsc::TryRecvError::Empty) => {+ if task.guard.is_cancelled() {+ // ✕: the worker stops at its next file; don't wait for it (a NAS read can take a while)+ app.scan = None;+ return;+ }+ let (total, done) = (task.progress.total.load(Ordering::Relaxed), task.progress.done.load(Ordering::Relaxed));+ task.guard.progress(done as u64, total as u64);+ // while the folders are listed the total isn't known: say what is happening instead+ task.guard.detail(if total == 0 { crate::i18n::tr("Looking for photos…") } else { "" });+ return;+ }+ Err(_) => {+ app.scan = None;+ app.toast(ctx, crate::i18n::tr("Scan failed"));+ return;+ }+ };+ let Some(task) = app.scan.take() else { return };+ if task.progress.cancel.load(Ordering::Relaxed) {+ return;+ }+ app.session.import_probes = out.probes;+ if task.browse {+ // the folder and the ones its photos are in count as browsed now, as `library.browse` records them, so+ // their untouched Local photos aren't forgotten while the folder is in use+ if let Some(root) = app.session.browse.as_ref().map(|b| b.path.clone()) {+ let shown: Vec<String> = out.candidates.iter().map(|c| c.path.clone()).collect();+ app.session.note_browsed(&root, &shown);+ }+ // records of files gone from the folder (deleted or moved by another app) that nothing was changed on go,+ // as `library.browse` forgets them (issue #1392)+ if let Some(b) = app.session.browse.clone() {+ let listed: Vec<String> = out.candidates.iter().map(|c| c.path.clone()).collect();+ app.session.forget_gone_from(&b.path, b.subfolders, &listed);+ }+ // what the library doesn't know yet joins the Local view+ let queue: Vec<String> =+ out.candidates.iter().filter(|c| c.duplicate != Some("path".into()) && c.error.is_none()).map(|c| c.path.clone()).collect();+ if !queue.is_empty() {+ let undo0 = app.session.undo.len();+ let total = queue.len();+ let _ = total;+ app.import = Some(ImportTask::new(queue, json!({"mode": "add", "local": true}), undo0, true));+ }+ return;+ }+ if out.candidates.is_empty() {+ app.toast(ctx, crate::i18n::tr("No photos found"));+ return;+ }+ app.renderer.forget_imports();+ let mut d = ImportDialog::new(out.candidates);+ let trashed = d+ .candidates+ .iter()+ .map(|c| {+ c.duplicate.is_some()+ && c.existing.is_some_and(|id| app.session.catalog.photo(lightcraft_catalog::PhotoId(id)).is_some_and(|p| p.deleted))+ })+ .collect();+ d.set_trashed(trashed);+ d.copy = task.copy;+ // only an album the review offers (it may have been deleted while the scan ran)+ d.album = task.album.filter(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_some_and(|a| !a.folder && !a.is_smart()));+ d.sources = task.sources;+ d.library = Some(app.session.library_generation());+ app.review_pending = Some(crate::state::Dialog::Import { opts: Box::new(d) });+ show_pending_review(app, ctx);+ }++ /// Open the review of a finished scan once no other dialog is open (a face model's licence, Settings…+ /// opened while the scan ran stays), checked again shortly while it waits. A review whose library was+ /// closed meanwhile (Settings can open another) is dropped.+ fn show_pending_review(app: &mut LightcraftApp, ctx: &egui::Context) {+ if app.review_pending.is_none() {+ return;+ }+ if let Some(crate::state::Dialog::Import { opts }) = &app.review_pending+ && !opts.in_library(app)+ {+ app.review_pending = None;+ return;+ }+ if app.ui.dialog.is_none() {+ app.ui.dialog = app.review_pending.take();+ } else {+ ctx.request_repaint_after(std::time::Duration::from_millis(100));+ }+ }++ /// Tests: a review scan that never ends while the returned value lives, so a drop meets it running.+ #[cfg(test)]+ pub(crate) fn stall_scan(app: &mut LightcraftApp) -> Box<dyn std::any::Any> {+ stall_scan_of(app, false)+ }++ /// Tests: the same, for a Local folder browse scan (`browse`) instead of the review's scan.+ #[cfg(test)]+ pub(crate) fn stall_scan_of(app: &mut LightcraftApp, browse: bool) -> Box<dyn std::any::Any> {+ let progress = std::sync::Arc::new(ScanProgress::default());+ let (tx, rx) = std::sync::mpsc::channel::<ScanOutput>();+ let guard = scan_guard(app, &progress, false);+ app.scan = Some(ScanTask { progress, rx, copy: false, album: None, browse, sources: Vec::new(), guard });+ Box::new(tx)+ }++ /// Whether an import or any scan (the review's, or a Local folder browse) is running, or a finished scan's+ /// review waits for a dialog to close, which a drop of photos must not replace: `open` refuses while a scan+ /// runs, and a browse that finishes replaces `app.import`.+ pub fn running(app: &LightcraftApp) -> bool {+ app.import.is_some() || app.scan.is_some() || app.review_pending.is_some()+ }++ impl ScanTask {+ /// `{done, total}` for `ui.inspect` (total is 0 while the folders are still being listed).+ pub fn status(&self) -> Value {+ json!({"done": self.progress.done.load(Ordering::Relaxed), "total": self.progress.total.load(Ordering::Relaxed)})+ }+ }diff --cc crates/ui-egui/src/panels/left/folders.rsindex 000000000,b9aa33037..95915b740mode 000000,100644..100644--- a/crates/ui-egui/src/panels/left/folders.rs+++ b/crates/ui-egui/src/panels/left/folders.rs@@@ -1,0 -1,661 +1,663 @@@+ use super::albums::pointer_over_row;+ use super::local::{same_folder, subfolders};+ use super::rows::{INDENT_STEP, LIBFOLDER_REVEALED, out_of_sight, row, row_sensed, set_tree_open, tree_open, tree_toggle};+ use super::*;++ /// A folder on disk with a disclosure triangle: click browses it, the triangle lists its+ /// subfolders. In the tree that holds the folder being browsed (`reveal`), the folders on the+ /// way down to it open whenever the browsed folder changes, so it shows highlighted in place.+ /// `transient`: a top-level row listed for this session only (it offers Keep in Local).+ /// `place`: the top-level folder this tree hangs from. A folder can be listed in more than one+ /// tree (Pictures on its own and inside Home): each row opens and closes by itself, and their+ /// triangles have ids of their own, else the copy drawn last takes the other's clicks (#1093).+ #[allow(clippy::too_many_arguments)]+ pub(super) fn folder_tree(+ app: &mut LightcraftApp,+ ui: &mut egui::Ui,+ place: &str,+ name: &str,+ path: &str,+ indent: f32,+ current: Option<&str>,+ reveal: bool,+ transient: bool,+ ) {+ let open_id = egui::Id::unique(("folder-open", place.to_string(), path.to_string()));+ let sel = current.is_some_and(|c| same_folder(c, path));+ let on_the_way = !sel && current.is_some_and(|c| lightcraft_catalog::query::folder_within(c, path));+ let mut open = tree_open(ui, open_id, false);+ if reveal && on_the_way {+ // opened once per browsed folder: collapsing it again afterwards sticks+ let revealed_id = egui::Id::unique(("folder-revealed", place.to_string(), path.to_string()));+ let target = current.map(str::to_string);+ if ui.data(|d| d.get_temp::<Option<String>>(revealed_id)) != Some(target.clone()) {+ open = true;+ set_tree_open(ui, open_id, true);+ ui.data_mut(|d| d.insert_temp(revealed_id, target));+ }+ }- // at the tree's own indent, as in Albums and Folders: the triangle sits in the gutter and the- // icon lines up with the rows above- let resp = row(app, ui, &format!("local:{path}"), Icon::Folder, name, None, sel, indent).on_hover_text(path);- let tr = tree_toggle(ui, &resp, indent, open_id, &mut open, format!("folderToggle:{path}"));- if !tr.clicked()- && resp.clicked()- && let Err(e) = app.run("library.browse", json!({"path": path}))- {- app.toast(ui.ctx(), e);- }- crate::widgets::context_menu(&resp, |ui| {- // the library actions of the Folders tree, when this folder (or one inside it) holds library photos- let library = app.caches.folder_tree(&app.session.catalog);- let held = library_node_for(&library, path);- if (transient || indent > 0.0)- && ui- .button(crate::i18n::tr(if transient { "Keep in Local" } else { "Add to Local" }))- .on_hover_text(crate::i18n::tr("List this folder in Local from now on"))- .clicked()- {- let _ = app.run("local.addRoot", json!({"path": path}));- ui.close();- }- if indent == 0.0- && ui- .button(crate::i18n::tr("Remove from Local"))- .on_hover_text(crate::i18n::tr("Hides this shortcut only; the folder and its photos stay as they are"))- .clicked()++ if !out_of_sight(app, ui, &format!("local:{path}"), name, None, indent, false) {++ // at the tree's own indent, as in Albums and Folders: the triangle sits in the gutter and the++ // icon lines up with the rows above++ let resp = row(app, ui, &format!("local:{path}"), Icon::Folder, name, None, sel, indent).on_hover_text(path);++ let tr = tree_toggle(ui, &resp, indent, open_id, &mut open, format!("folderToggle:{path}"));++ if !tr.clicked()++ && resp.clicked()++ && let Err(e) = app.run("library.browse", json!({"path": path}))+ {- let _ = app.run("local.hide", json!({"path": path}));- ui.close();- }- if ui.button(crate::i18n::tr("Rename Folder…")).clicked() {- app.ui.dialog = Some(crate::state::Dialog::TextPrompt {- title: crate::i18n::tr_format!("Rename “{name}”", name = name),- hint: "Folder name (renamed on disk; its photos follow)".into(),- value: name.to_string(),- command: "folder.rename".into(),- params: json!({"path": path}),- key: "name".into(),- });++ app.toast(ui.ctx(), e);+ }- if app.services.pick_folder.is_some() && ui.button(crate::i18n::tr("Move Folder To…")).clicked() {- let into = app.services.pick_folder.as_mut().and_then(|f| f());- if let Some(into) = into {- match app.run("folder.move", json!({"path": path, "into": into})) {- Ok(r) => app.toast(ui.ctx(), crate::i18n::tr_format!("Moved; {} photo(s) relinked", r["relinked"])),- Err(e) => app.toast(ui.ctx(), e),++ crate::widgets::context_menu(&resp, |ui| {++ // the library actions of the Folders tree, when this folder (or one inside it) holds library photos++ let library = app.caches.folder_tree(&app.session.catalog);++ let held = library_node_for(&library, path);++ if (transient || indent > 0.0)++ && ui++ .button(crate::i18n::tr(if transient { "Keep in Local" } else { "Add to Local" }))++ .on_hover_text(crate::i18n::tr("List this folder in Local from now on"))++ .clicked()++ {++ let _ = app.run("local.addRoot", json!({"path": path}));++ ui.close();++ }++ if indent == 0.0++ && ui++ .button(crate::i18n::tr("Remove from Local"))++ .on_hover_text(crate::i18n::tr("Hides this shortcut only; the folder and its photos stay as they are"))++ .clicked()++ {++ let _ = app.run("local.hide", json!({"path": path}));++ ui.close();++ }++ if ui.button(crate::i18n::tr("Rename Folder…")).clicked() {++ app.ui.dialog = Some(crate::state::Dialog::TextPrompt {++ title: crate::i18n::tr_format!("Rename “{name}”", name = name),++ hint: "Folder name (renamed on disk; its photos follow)".into(),++ value: name.to_string(),++ command: "folder.rename".into(),++ params: json!({"path": path}),++ key: "name".into(),++ });++ }++ if app.services.pick_folder.is_some() && ui.button(crate::i18n::tr("Move Folder To…")).clicked() {++ let into = app.services.pick_folder.as_mut().and_then(|f| f());++ if let Some(into) = into {++ match app.run("folder.move", json!({"path": path, "into": into})) {++ Ok(r) => app.toast(ui.ctx(), crate::i18n::tr_format!("Moved; {} photo(s) relinked", r["relinked"])),++ Err(e) => app.toast(ui.ctx(), e),++ }+ }+ }- }- if app.services.reveal.is_some()- && ui.button(crate::i18n::tr(crate::menus::reveal_label())).clicked()- && let Some(f) = app.services.reveal.as_mut()- {- let _ = f(path);- }- if let Some(held) = &held {- synchronize_item(app, ui, &held.0, &held.1);- }- });++ if app.services.reveal.is_some()++ && ui.button(crate::i18n::tr(crate::menus::reveal_label())).clicked()++ && let Some(f) = app.services.reveal.as_mut()++ {++ let _ = f(path);++ }++ if let Some(held) = &held {++ synchronize_item(app, ui, &held.0, &held.1);++ }++ });++ }+ if open && indent < INDENT_STEP * 8.0 {- for (n, p) in subfolders(ui, path) {- folder_tree(app, ui, place, &n, &p, indent + INDENT_STEP, current, reveal, false);++ for (n, p) in subfolders(ui, path).iter() {++ folder_tree(app, ui, place, n, p, indent + INDENT_STEP, current, reveal, false);+ }+ }+ }++ pub(super) fn folder_menu(app: &mut LightcraftApp, resp: &egui::Response, a: &Album) {+ crate::widgets::context_menu(resp, |ui| {+ if a.folder {+ // the same commands as File ▸ New…, aimed at this folder+ crate::widgets::menu_button(ui, crate::i18n::tr("New"), |ui| {+ for (label, command) in [+ ("Create Album…", "dialog.newAlbum"),+ ("Create Smart Album…", "dialog.smartAlbum"),+ ("Create Smart Album from Filter…", "dialog.newSmartAlbum"),+ ("Create Folder…", "dialog.newFolder"),+ ] {+ if ui.button(crate::i18n::tr(label)).clicked() {+ let _ = app.run(command, json!({"parent": a.id.0}));+ ui.close();+ }+ }+ });+ if app.session.catalog.album_children_are_ordered(Some(a.id))+ && ui.button(crate::i18n::tr("Sort Contents A–Z")).on_hover_text(crate::i18n::tr("Go back to listing them by name")).clicked()+ {+ let _ = app.run("album.sort", json!({"parent": a.id.0}));+ ui.close();+ }+ ui.separator();+ }+ if !a.folder && !a.is_smart() {+ let local_only = crate::panels::grid::local_only(app, &app.session.selected());+ let b = ui+ .add_enabled(!local_only, egui::Button::new(crate::i18n::tr("Add Selected Photos")))+ .on_disabled_hover_text(crate::panels::grid::albums_hint());+ if b.clicked() {+ match app.run("album.addPhotos", json!({"id": a.id.0})) {+ Ok(r) => crate::panels::grid::toast_skipped(app, ui.ctx(), &r),+ Err(e) => app.toast(ui.ctx(), e),+ }+ }+ // File ▸ Import's ways in; the import review opens with this album chosen+ let menu = crate::widgets::menu_button(ui, crate::i18n::tr("Import"), |ui| {+ let mut entry = |ui: &mut egui::Ui, label: String, widget: String, command: &str, params: serde_json::Value| {+ let r = ui.button(label);+ crate::widgets::register(ui, widget, r.rect);+ if r.clicked() {+ if let Err(e) = app.run(command, params) {+ app.toast(ui.ctx(), e);+ }+ ui.close();+ }+ };+ for (label, command, widget) in [+ ("Import Photos…", "file.addPhotos", "button:albumImportPhotos"),+ ("Import from Folder…", "file.addFolder", "button:albumImportFolder"),+ ] {+ entry(ui, crate::i18n::tr(label).into(), widget.into(), command, json!({"album": a.id.0}));+ }+ // like File ▸ Import from Device: one entry per camera or card found+ let device = crate::widgets::menu_button(ui, crate::i18n::tr("Import from Device"), |ui| {+ let devices = lightcraft_engine::devices::devices();+ if devices.is_empty() {+ ui.add_enabled(false, egui::Button::new(crate::i18n::tr("No Camera or Card Found")));+ }+ for (i, d) in devices.into_iter().enumerate() {+ let params = json!({"path": d.path, "album": a.id.0});+ entry(ui, format!("{}…", d.name), format!("button:albumImportDevice:{i}"), "file.addFromDevice", params);+ }+ });+ crate::widgets::register(ui, "button:albumImportDevice", device.response.rect);+ });+ crate::widgets::register(ui, "button:albumImport", menu.response.rect);+ }+ if !a.folder && !a.is_smart() {+ let is_target = app.session.target_album == Some(a.id) || (app.session.target_album.is_none() && a.quick);+ if !is_target && ui.button(crate::i18n::tr("Set as Target Album (B adds to it)")).clicked() {+ let _ = app.run("album.setTarget", json!({"id": if a.quick { serde_json::Value::Null } else { json!(a.id.0) }}));+ }+ if is_target && !a.quick && ui.button(crate::i18n::tr("Stop Using as Target Album")).clicked() {+ let _ = app.run("album.setTarget", json!({"id": null}));+ }+ }+ if a.quick && ui.button(crate::i18n::tr("Clear Quick Collection")).clicked() {+ let _ = app.run("album.clearQuick", json!({}));+ }+ if a.is_smart() && ui.button(crate::i18n::tr("Edit Smart Album…")).clicked() {+ // the same editor as `dialog.smartAlbum` (older smart albums keep their filter fields;+ // it works on the rule set, upgraded)+ let _ = app.run("dialog.smartAlbum", json!({"id": a.id.0}));+ }+ if a.is_smart() && ui.button(crate::i18n::tr("Update Rules from Current Filter")).clicked() {+ // refused when the view would make the album test itself: say why+ if let Err(e) = app.run("album.setRules", json!({"id": a.id.0, "fromView": true})) {+ app.toast(ui.ctx(), e);+ }+ }+ if !a.folder {+ // export: show the album, select its photos, then the dialog / a preset+ let show_all = |app: &mut LightcraftApp| {+ let _ = app.run("library.source", json!({"kind": "album", "id": a.id.0}));+ let _ = app.run("library.selectAll", json!({}));+ };+ let has_photos = app.session.catalog.album_count(a.id) > 0;+ if ui.add_enabled(has_photos, egui::Button::new(crate::i18n::tr("Export Album…"))).clicked() {+ show_all(app);+ let _ = app.run("dialog.export", json!({}));+ }+ ui.add_enabled_ui(has_photos, |ui| {+ crate::widgets::menu_button(ui, crate::i18n::tr("Export Album with Preset"), |ui| {+ for (p, _) in app.session.all_export_presets() {+ if ui.button(&p.name).clicked() {+ show_all(app);+ if let Err(e) = app.run("app.export", json!({"preset": p.name, "background": true})) {+ app.toast(ui.ctx(), e);+ }+ }+ }+ });+ });+ ui.separator();+ }+ // move into another folder (not into itself or one of its own subfolders)+ let mut folders: Vec<(u64, String)> =+ app.session.catalog.albums().filter(|f| f.folder && !is_within(app, f.id, a.id)).map(|f| (f.id.0, f.name.clone())).collect();+ folders.sort_by_key(|(_, n)| n.to_lowercase());+ crate::widgets::menu_button(ui, crate::i18n::tr("Move to"), |ui| {+ if ui.add_enabled(a.parent.is_some(), egui::Button::new(crate::i18n::tr("Top Level"))).clicked() {+ let _ = app.run("album.move", json!({"id": a.id.0, "parent": null}));+ }+ for (fid, name) in &folders {+ if ui.add_enabled(a.parent.map(|p| p.0) != Some(*fid), egui::Button::new(name)).clicked() {+ let _ = app.run("album.move", json!({"id": a.id.0, "parent": fid}));+ }+ }+ });+ if ui.button(crate::i18n::tr("Rename…")).clicked() {+ app.ui.dialog = Some(crate::state::Dialog::RenameAlbum { id: a.id.0, name: a.name.clone() });+ }+ let delete = ui.button(crate::i18n::tr("Delete"));+ register(ui, format!("albumDelete:{}", a.id.0), delete.rect);+ let delete =+ delete.on_hover_text(crate::i18n::tr("Photos stay in All Photos. Deleting a folder also deletes its albums. You can undo this."));+ if delete.clicked() {+ if let Err(e) = app.run("album.delete", json!({"id": a.id.0})) {+ app.toast(ui.ctx(), e);+ }+ ui.close();+ }+ });+ }++ /// Whether `id` is `ancestor` or lies inside it.+ pub(super) fn is_within(app: &LightcraftApp, id: lightcraft_catalog::AlbumId, ancestor: lightcraft_catalog::AlbumId) -> bool {+ let mut cur = Some(id);+ let mut guard = 0;+ while let Some(c) = cur {+ if c == ancestor {+ return true;+ }+ cur = app.session.catalog.album(c).and_then(|x| x.parent);+ guard += 1;+ if guard > 64 {+ break;+ }+ }+ false+ }++ // "Folders" (drawn in `show`): where on disk the library's photos were imported from, with photo counts (see+ // `lightcraft_catalog::folders`). A click makes that folder the source, like an album or a Local+ // folder: its photos and those of the folders inside it fill the grid. The triangle opens a+ // level. Only folders holding imported photos are listed; every folder on disk is under Local.++ /// Whenever the shown folder changes (a click, an agent, a rename or its undo), open the rows+ /// above it so it is on screen; folding one by hand afterwards sticks until the choice changes.+ pub(super) fn reveal_chosen(app: &LightcraftApp, ui: &egui::Ui, tree: &[FolderNode]) {+ let shown = app.session.library_folder.clone().filter(|_| app.session.source == LibrarySource::LibraryFolder);+ let chosen = shown.filter(|c| !lightcraft_catalog::query::folder_key(c).is_empty());+ let seen = egui::Id::unique(LIBFOLDER_REVEALED);+ let now = chosen.as_deref().map(lightcraft_catalog::query::folder_key);+ if ui.data(|d| d.get_temp::<Option<String>>(seen)) == Some(now.clone()) {+ return;+ }+ ui.data_mut(|d| d.insert_temp(seen, now));+ let Some(chosen) = chosen else { return };+ fn open_above(ui: &egui::Ui, nodes: &[FolderNode], chosen: &str) {+ for n in nodes {+ if lightcraft_catalog::query::folder_within(chosen, &n.path) && !same_folder(chosen, &n.path) {+ let key = lightcraft_catalog::query::folder_key(&n.path);+ ui.data_mut(|d| d.insert_temp(egui::Id::unique(("libfolder-open", key)), true));+ open_above(ui, &n.children, chosen);+ }+ }+ }+ open_above(ui, tree, &chosen);+ }++ /// The Folders row that stands for folder `dir`, however it is spelled. `None` when no row is that+ /// folder.+ pub(crate) fn folder_row_of<'a>(tree: &'a [FolderNode], dir: &str) -> Option<&'a FolderNode> {+ // only the rows that hold `dir` are opened (the startup disk's holds the other disks' paths+ // too, so more than one may), and the tree is at most `MAX_DEPTH` deep+ tree.iter()+ .filter(|n| lightcraft_catalog::query::folder_within(dir, &n.path))+ .find_map(|n| if same_folder(&n.path, dir) { Some(n) } else { folder_row_of(&n.children, dir) })+ }++ pub(super) fn folder_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, nodes: &[FolderNode], indent: f32) {+ for n in nodes {+ let key = lightcraft_catalog::query::folder_key(&n.path);+ let open_id = egui::Id::unique(("libfolder-open", key.clone()));+ // a disk starts open, and so does a folder that holds nothing itself and leads to one+ // folder (`Users` → `me`): the first row where the library branches is what you look for+ let leads_on = n.own == 0 && n.children.len() == 1;+ let mut open = tree_open(ui, open_id, n.volume || leads_on);+ // a row whose path would cover other disks' photos too only opens and closes+ let name = if n.selectable { n.name.clone() } else { crate::i18n::tr("This Computer").to_string() };+ let id = format!("libfolder:{}", n.path);+ if !out_of_sight(app, ui, &id, &name, Some(n.count), indent, n.label.is_some()) {+ folder_row(app, ui, n, &id, &name, indent, open_id, &mut open);+ }+ if open && !n.children.is_empty() {+ folder_rows(app, ui, &n.children, indent + INDENT_STEP);+ }+ }+ }++ /// One drawn row of [`folder_rows`], shown as `name`; `open_id` and `open` are its triangle's.+ #[allow(clippy::too_many_arguments)]+ fn folder_row(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, id: &str, name: &str, indent: f32, open_id: egui::Id, open: &mut bool) {+ let sel = n.selectable+ && app.session.source == LibrarySource::LibraryFolder+ && app.session.library_folder.as_deref().is_some_and(|f| same_folder(f, &n.path));+ // the label is said with the name, as it is shown beside it+ let spoken = match n.label {+ Some(l) => format!("{name}, {}", crate::i18n::color_label(&app.session.catalog, l)),+ None => name.to_string(),+ };+ let mark = n.label.map(crate::theme::label_color);+ let resp = row_sensed(app, ui, id, Icon::Folder, name, Some(&spoken), Some(n.count), sel, indent, Sense::click(), mark);+ folder_drop_target(app, ui, &resp, n, open_id, open);+ let mut toggled = false;+ if !n.children.is_empty() {+ let tr = tree_toggle(ui, &resp, indent, open_id, open, format!("libraryFolderToggle:{}", n.path));+ toggled = tr.clicked();+ // the triangle sits on the row and takes its clicks: the menu opens from it too+ row_menu(app, &tr, n);+ }+ let tip = if n.children.is_empty() { n.path.clone() } else { format!("{} ({})", n.path, crate::i18n::tr("includes the folders inside it")) };+ let resp = resp.on_hover_text(tip);+ if resp.clicked() && !toggled {+ if n.selectable {+ // a source like an album or a Local folder: it replaces what the grid showed+ let _ = app.run("library.source", json!({"kind": "libraryFolder", "path": n.path}));+ } else {+ *open = !*open;+ set_tree_open(ui, open_id, *open);+ }+ }+ row_menu(app, &resp, n);+ }++ /// How long photos dragged over a closed Folders row wait before it opens, so a folder inside it+ /// can be reached.+ const SPRING_OPEN_SECONDS: f64 = 0.7;++ /// A Folders row while photos are dragged from the grid: a release moves their files there on+ /// disk (`photo.moveToFolder`, one undo step). The row lights up and the dragged label says where+ /// they will go, as the same gesture onto an album only adds them to it. Held over a closed row,+ /// it opens. Photos that can't go there leave it dark (a row covering several disks; Local photos,+ /// not in the library) and a release says why; photos already there say so.+ fn folder_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, n: &FolderNode, open_id: egui::Id, open: &mut bool) {+ let Some(ids) = app.ui.dragging_photos.clone() else { return };+ // only where the row can be seen: not scrolled out of the sidebar or beneath the pinned header+ if !pointer_over_row(ui, resp.rect) {+ return;+ }+ spring_open(ui, n, open_id, open);+ let name = std::path::Path::new(&n.path).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| n.name.clone());+ let photos: Vec<_> = ids.iter().filter_map(|id| app.session.catalog.photo(lightcraft_catalog::PhotoId(*id))).collect();+ let refused = if !n.selectable {+ Some(crate::i18n::tr("This row covers more than one disk: drop on a folder inside it"))+ } else if photos.iter().any(|p| p.local) {+ Some(crate::i18n::tr("Local photos aren't in the library yet: Add to My Photos first, then move them"))+ } else {+ None+ };+ let here = |p: &lightcraft_catalog::Photo| match &p.source {+ lightcraft_catalog::Source::File { path } => std::path::Path::new(path).parent().is_some_and(|d| same_folder(&d.to_string_lossy(), &n.path)),+ _ => false,+ };+ let all_here = !photos.is_empty() && photos.iter().all(|p| here(p));+ let count = photos.len();+ let released = ui.input(|i| i.pointer.any_released());+ let hint = match (&refused, all_here) {+ (Some(_), _) => crate::i18n::tr("Can't be moved here").to_string(),+ (None, true) => crate::i18n::tr_format!("Already in “{}”", name),+ (None, false) => crate::i18n::tr_format!("Move {n} photo{} to “{}”", if count == 1 { "" } else { "s" }, name, n = count),+ };+ crate::panels::grid::drag_hint(ui.ctx(), hint);+ if let Some(why) = refused {+ ui.ctx().set_cursor_icon(egui::CursorIcon::NotAllowed);+ if released {+ app.toast(ui.ctx(), why);+ app.ui.dragging_photos = None;+ }+ return;+ }+ if all_here {+ if released {+ app.ui.dragging_photos = None;+ }+ return;+ }+ let t = Tokens::get(ui.ctx());+ ui.painter().rect_stroke(resp.rect.shrink2(vec2(8.0, 1.0)), 4.0, egui::Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);+ if released {+ app.ui.dragging_photos = None;+ // a drop moves files on disk: asked first (as Lightroom Classic does), unless the person+ // said not to; the menu's Move Selected Photos Here is asked for by name and goes at once+ if app.ui.settings.ask_before_move {+ let library = app.session.library_generation();+ app.ui.dialog = Some(crate::state::Dialog::MovePhotos { ids, folder: n.path.clone(), name, dont_ask: false, library });+ } else {+ move_photos_here(app, ui.ctx(), Some(&ids), &n.path, &name);+ }+ }+ }++ /// Photos dragged over the closed row `n` for [`SPRING_OPEN_SECONDS`] open it (a row with folders+ /// inside it). Restarts on each row the pointer comes to, and when it comes back to one after+ /// leaving it (or after another drag).+ fn spring_open(ui: &egui::Ui, n: &FolderNode, open_id: egui::Id, open: &mut bool) {+ if *open || n.children.is_empty() {+ return;+ }+ let key = egui::Id::unique("folder-spring-open");+ let (now, frame) = (ui.input(|i| i.time), ui.ctx().cumulative_frame_nr());+ // held without a break: over this row last frame too+ let since = match ui.data(|d| d.get_temp::<(String, f64, u64)>(key)) {+ Some((path, since, seen)) if path == n.path && seen.saturating_add(1) >= frame => since,+ _ => now,+ };+ ui.data_mut(|d| d.insert_temp(key, (n.path.clone(), since, frame)));+ if now - since >= SPRING_OPEN_SECONDS {+ *open = true;+ set_tree_open(ui, open_id, true);+ ui.data_mut(|d| d.remove::<(String, f64, u64)>(key));+ } else {+ // keep the clock running while the pointer rests+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));+ }+ }++ /// Move photos (`ids`, else the selection) into the folder `path` on disk (`photo.moveToFolder`).+ /// Photos that leave the view leave the selection, so nothing done next (Delete, an edit) reaches+ /// photos no longer on screen. How many moved, or why none did.+ pub(crate) fn move_photos(app: &mut LightcraftApp, ids: Option<&[u64]>, path: &str) -> Result<u64, String> {+ let mut params = json!({"folder": path});+ if let Some(ids) = ids {+ params["ids"] = json!(ids);+ }+ let r = app.run("photo.moveToFolder", params)?;+ let visible: std::collections::HashSet<lightcraft_catalog::PhotoId> = app.session.visible_cloned().into_iter().collect();+ let sel = &mut app.session.selection;+ sel.ids.retain(|id| visible.contains(id));+ if sel.active.is_some_and(|a| !visible.contains(&a)) {+ sel.active = sel.ids.first().copied();+ }+ Ok(r["moved"].as_u64().unwrap_or(0))+ }++ /// What a move of `n` photos into the folder `name` says: how many moved and that Undo moves them+ /// back, or that they were there already.+ pub(crate) fn moved_text(n: u64, name: &str) -> String {+ if n == 0 {+ crate::i18n::tr_format!("Already in “{}”", name)+ } else {+ crate::i18n::tr_format!("Moved {n} photo{} to “{}”. Edit → Undo moves them back.", if n == 1 { "" } else { "s" }, name, n = n)+ }+ }++ /// [`move_photos`], saying how it went in a toast.+ fn move_photos_here(app: &mut LightcraftApp, ctx: &egui::Context, ids: Option<&[u64]>, path: &str, name: &str) {+ match move_photos(app, ids, path) {+ Ok(n) => app.toast(ctx, moved_text(n, name)),+ Err(e) => app.toast(ctx, e),+ }+ }++ /// The context menu of a Folders row: a folder's own, a disk's (remove it), none for the+ /// startup disk.+ fn row_menu(app: &mut LightcraftApp, resp: &egui::Response, n: &FolderNode) {+ if !n.volume {+ folder_menu_for_library(app, resp, n);+ } else if n.path != "/" {+ crate::widgets::context_menu(resp, |ui| {+ folder_label_menu(app, ui, n);+ locate_missing_item(app, ui, n);+ synchronize_item(app, ui, n, &n.name);+ ui.separator();+ if ui+ .button(crate::i18n::tr("Remove Disk from Library…"))+ .on_hover_text(crate::i18n::tr("Moves every photo imported from this disk to Recently Deleted; no file is touched"))+ .clicked()+ {+ app.ui.dialog = Some(crate::state::Dialog::RemoveFolder { path: n.path.clone(), name: n.name.clone(), count: n.count, disk: true });+ ui.close();+ }+ });+ }+ }++ /// Locate Missing Files… of a Folders row: choose where this folder moved, then let the existing+ /// background finder relink only this folder's photos (including the folders inside it).+ fn locate_missing_item(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode) {+ let r = ui.button(crate::i18n::tr("Locate Missing Files…"));+ register(ui, "folderLocateMissing", r.rect);+ if r.clicked() {+ if let Err(e) = app.run("file.findMissing", json!({"within": n.path})) {+ app.toast(ui.ctx(), e);+ }+ ui.close();+ }+ }++ /// The node Synchronize Folder… of a Local folder `path` works on, with the name its dialog shows:+ /// the Folders row for that very folder, else (a folder above rows) the folder itself, as a folder+ /// holding other folders. `None` when no library photo lies in `path` or inside it. Reads the+ /// cached Folders tree only; the disk is not touched.+ fn library_node_for(tree: &[FolderNode], path: &str) -> Option<(FolderNode, String)> {+ use lightcraft_catalog::query::folder_within;+ fn exact<'a>(tree: &'a [FolderNode], path: &str) -> Option<&'a FolderNode> {+ tree.iter().find_map(|n| if same_folder(&n.path, path) { Some(n) } else { exact(&n.children, path) })+ }+ fn any_inside(tree: &[FolderNode], path: &str) -> bool {+ tree.iter().any(|n| (n.count > 0 && folder_within(&n.path, path)) || any_inside(&n.children, path))+ }+ if let Some(n) = exact(tree, path).filter(|n| n.count > 0) {+ return Some((n.clone(), lightcraft_catalog::folders::folder_label(&n.path)));+ }+ if !any_inside(tree, path) {+ return None;+ }+ let name = std::path::Path::new(path).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());+ let node = FolderNode {+ name: name.clone(),+ path: path.to_string(),+ count: 0,+ own: 0,+ volume: false,+ selectable: false,+ label: None,+ children: Vec::new(),+ };+ Some((node, name))+ }++ /// Synchronize Folder… of a Folders row (widget `folderSynchronize`): opens its dialog, which+ /// scans the folder in the background.+ fn synchronize_item(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode, name: &str) {+ let r = ui+ .button(crate::i18n::tr("Synchronize Folder…"))+ .on_hover_text(crate::i18n::tr("Find photos added to or missing from this folder on disk, and XMP sidecars changed by other apps"));+ crate::widgets::register(ui, "folderSynchronize", r.rect);+ if r.clicked() {+ // a disk, or a folder holding disks, was chosen as such+ if let Err(e) = crate::sync::open(app, &n.path, name, n.volume || !n.selectable) {+ app.toast(ui.ctx(), e);+ }+ ui.close();+ }+ }++ /// Set Color Label ▸ of a Folders row (`folder.label`; the submenu is widget `folderLabelMenu`,+ /// its colours `folderLabel:<colour>`).+ fn folder_label_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNode) {+ let menu = crate::widgets::menu_button(ui, crate::i18n::tr("Set Color Label"), |ui| {+ if let Some(l) = crate::panels::grid::label_items(app, ui, n.label, "folderLabel") {+ if let Err(e) = app.run("folder.label", json!({"path": n.path, "label": crate::panels::grid::label_param(l)})) {+ app.toast(ui.ctx(), e);+ }+ ui.close();+ }+ });+ register(ui, "folderLabelMenu", menu.response.rect);+ }++ /// The context menu of a folder row: the folder's disk actions (the same as Local's, photos+ /// follow) and taking its photos out of the library.+ fn folder_menu_for_library(app: &mut LightcraftApp, resp: &egui::Response, n: &FolderNode) {+ let path = n.path.as_str();+ let name = std::path::Path::new(path).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());+ // what dialogs call it: the last two names, so same-named folders are told apart+ let label = lightcraft_catalog::folders::folder_label(path);+ crate::widgets::context_menu(resp, |ui| {+ if ui.button(crate::i18n::tr("Rename Folder…")).clicked() {+ app.ui.dialog = Some(crate::state::Dialog::TextPrompt {+ title: crate::i18n::tr_format!("Rename “{name}”", name = label),+ hint: "Folder name (renamed on disk; its photos follow)".into(),+ value: name.clone(),+ command: "folder.rename".into(),+ params: json!({"path": path}),+ key: "name".into(),+ });+ ui.close();+ }+ if app.services.pick_folder.is_some() && ui.button(crate::i18n::tr("Move Folder To…")).clicked() {+ let into = app.services.pick_folder.as_mut().and_then(|f| f());+ if let Some(into) = into {+ match app.run("folder.move", json!({"path": path, "into": into})) {+ Ok(r) => app.toast(ui.ctx(), format!("Moved; {} photo(s) relinked", r["relinked"])),+ Err(e) => app.toast(ui.ctx(), e),+ }+ }+ ui.close();+ }+ if ui.button(crate::i18n::tr("New Folder on Disk…")).clicked() {+ app.ui.dialog = Some(crate::state::Dialog::TextPrompt {+ title: crate::i18n::tr_format!("New Folder in “{name}”", name = label),+ hint: "Folder name (created on disk)".into(),+ value: String::new(),+ command: "folder.create".into(),+ params: json!({"parent": path}),+ key: "name".into(),+ });+ ui.close();+ }+ let selected = app.session.selection.ids.len();+ if selected > 0+ && ui+ .button(crate::i18n::tr("Move Selected Photos Here"))+ .on_hover_text(crate::i18n::tr("Moves the files and their XMP sidecars into this folder; never overwrites"))+ .clicked()+ {+ move_photos_here(app, ui.ctx(), None, path, &name);+ ui.close();+ }+ if app.services.reveal.is_some()+ && ui.button(crate::i18n::tr(crate::menus::reveal_label())).clicked()+ && let Some(f) = app.services.reveal.as_mut()+ {+ let _ = f(path);+ ui.close();+ }+ folder_label_menu(app, ui, n);+ locate_missing_item(app, ui, n);+ synchronize_item(app, ui, n, &label);+ ui.separator();+ if ui+ .button(crate::i18n::tr("Remove from Library…"))+ .on_hover_text(crate::i18n::tr("Moves the photos imported from this folder to Recently Deleted; no file is touched"))+ .clicked()+ {+ app.ui.dialog = Some(crate::state::Dialog::RemoveFolder { path: path.to_string(), name: label.clone(), count: n.count, disk: false });+ ui.close();+ }+ });+ }diff --cc crates/ui-egui/src/panels/left/local.rsindex 000000000,0fedcb2b5..e1a62d8eamode 000000,100644..100644--- a/crates/ui-egui/src/panels/left/local.rs+++ b/crates/ui-egui/src/panels/left/local.rs@@@ -1,0 -1,406 +1,520 @@@+ use super::folders::folder_tree;+ use super::rows::row;+ use super::*;++ /// Local's folders as they stand this frame, and the folder being browsed among them.+ pub(super) struct LocalNow {+ pub(super) places: LocalPlaces,+ current: Option<String>,+ /// The places removed from Local, as (name, path), in the order they were hidden.+ hidden: Vec<(String, String)>,+ }++ /// Folders on this computer to browse without adding (Lightroom's Local): Pictures, Desktop,+ /// Downloads, the home folder, the folder being browsed, and the folders kept with Browse+ /// Folder…. Worked out every frame the sidebar shows, drawn or not: the row listed for this+ /// session only (`local_browse_root`) follows the browsing. `None` where there is no Local (web).+ pub(super) fn local_now(app: &mut LightcraftApp, ui: &egui::Ui) -> Option<LocalNow> {+ if !SidebarSection::Local.available() {+ return None;+ }+ let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default();- let mut builtin: Vec<(String, String)> = Vec::new();- if !home.is_empty() {++ let mut builtin = app.services.local_places.clone().unwrap_or_default();++ if app.services.local_places.is_none() && !home.is_empty() {+ for (name, sub) in [("Pictures", "Pictures"), ("Desktop", "Desktop"), ("Downloads", "Downloads"), ("Home", "")] {+ // joined with the platform's separator, like the paths browsing gives back+ let p = if sub.is_empty() { home.clone() } else { std::path::Path::new(&home).join(sub).to_string_lossy().to_string() };+ // (checked off the UI thread: a home folder can be on a network share)+ if fs_cached(ui, "is-dir", &p, 5.0, |p| std::path::Path::new(p).is_dir()) == Some(true) {+ builtin.push((crate::i18n::tr(name).to_string(), p));+ }+ }+ }+ let browsing = app.session.browse.clone().filter(|_| app.session.source == LibrarySource::Folder);+ let current = browsing.as_ref().map(|b| b.path.clone());+ // a hidden built-in place keeps its name (Home, not the user's folder name)+ let name_of = |path: &str| builtin.iter().find(|(_, p)| same_folder(p, path)).map_or_else(|| folder_label(path), |(n, _)| n.clone());+ let hidden = app.ui.hidden_locations.iter().map(|h| (name_of(h), h.clone())).collect();- let places = local_places(builtin, &app.ui.local_roots, current.as_deref(), app.ui.local_browse_root.as_deref(), &app.ui.hidden_locations);- if current.is_some() {++ let unlisted = current.as_deref().and_then(|path| fs_cached(ui, "unlisted-ancestors", path, 2.0, unlisted_ancestors));++ let mut places = local_places_with_unlisted(++ builtin,++ &app.ui.local_roots,++ current.as_deref(),++ app.ui.local_browse_root.as_deref(),++ &app.ui.hidden_locations,++ unlisted.as_deref().unwrap_or(&[]),++ );++ if current.is_some() && unlisted.is_none() {++ places.owner = None;++ }++ if current.is_some() && unlisted.is_some() {+ app.ui.local_browse_root = places.browse_root.clone();+ }+ Some(LocalNow { places, current, hidden })+ }++ /// Local's rows: each place as a folder tree, Browse Folder…, and the way back for hidden places.+ pub(super) fn local_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, now: &LocalNow) {+ let (local, current) = (&now.places, now.current.as_deref());+ for (i, (name, path)) in local.places.iter().enumerate() {+ let transient = local.browse_root.as_deref() == Some(path.as_str());+ let reveal = local.owner == Some(i);+ folder_tree(app, ui, path, name, path, 0.0, current, reveal, transient);+ }+ if app.services.pick_folder.is_some() && row(app, ui, "local:browse", Icon::Plus, crate::i18n::tr("Browse Folder…"), None, false, 0.0).clicked()+ {+ let picked = app.services.pick_folder.as_mut().and_then(|f| f());+ if let Some(path) = picked {+ match app.run("library.browse", json!({"path": path})) {+ // the picked folder stays in Local (and comes back if it was hidden)+ Ok(r) => {+ let dir = r["path"].as_str().unwrap_or(&path).to_string();+ let _ = app.run("local.addRoot", json!({"path": dir}));+ }+ Err(e) => app.toast(ui.ctx(), e),+ }+ }+ }+ // the way back for hidden places: one comes back from the row itself; several are listed, so+ // each comes back on its own, or all at once (issue #2114: the row used to bring every one back)+ let hidden = now.hidden.len();+ if hidden > 0 {+ let label = crate::i18n::tr_format!("Show {hidden} hidden location{}", if hidden == 1 { "" } else { "s" }, hidden = hidden);+ let resp = row(app, ui, "local:restoreHidden", Icon::Folder, &label, None, false, 0.0)+ .on_hover_text(crate::i18n::tr("Put the locations you removed from Local back (no files change)"));+ if let [(_, only)] = now.hidden.as_slice() {+ if resp.clicked() {+ let _ = app.run("local.restoreHidden", json!({"path": only}));+ }+ } else {+ egui::Popup::menu(&resp).show(|ui| hidden_menu(app, ui, &now.hidden));+ }+ }+ }++ /// The list behind "Show N hidden locations": each place by name (its path on hover), then+ /// Restore All.+ fn hidden_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, hidden: &[(String, String)]) {+ for (name, path) in hidden {+ let r = ui.button(name).on_hover_text(path);+ register(ui, format!("local:restoreHidden:{path}"), r.rect);+ if r.clicked() {+ let _ = app.run("local.restoreHidden", json!({"path": path}));+ ui.close();+ }+ }+ ui.separator();+ let r = ui.button(crate::i18n::tr("Restore All"));+ register(ui, "local:restoreHidden:all", r.rect);+ if r.clicked() {+ let _ = app.run("local.restoreHidden", json!({}));+ ui.close();+ }+ }++ /// Whether two paths name the same folder, however they are spelled (separators, trailing+ /// slash, `.`/`..`, drive-letter case; see `lightcraft_catalog::query::folder_key`).+ pub(crate) fn same_folder(a: &str, b: &str) -> bool {+ a == b || lightcraft_catalog::query::folder_key(a) == lightcraft_catalog::query::folder_key(b)+ }++ /// Local's top-level folders and how the folder being browsed sits among them.+ #[derive(Debug, Default, PartialEq)]+ pub(crate) struct LocalPlaces {+ /// (label, path) of each top-level folder, in order.+ pub places: Vec<(String, String)>,+ /// The top-level folder the browsed folder lies in (the innermost one): its tree opens on+ /// the way down to it. None when that way passes through a hidden folder.+ pub owner: Option<usize>,+ /// A folder listed only for this session because the browsed folder is in no saved+ /// location (browsed from a breadcrumb, the CLI…); it stays while browsing below it.+ pub browse_root: Option<String>,+ }++ fn folder_label(path: &str) -> String {+ std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())+ }++ /// Local's top-level folders, in order: the built-in places, the folders kept with Browse+ /// Folder… / Keep in Local (`saved`), then — only when the browsed folder lies in none of those —+ /// a session root for it: the previous one (`browse_root`) while browsing stays below it, else+ /// the browsed folder itself. A folder inside a listed one is shown inside that one's tree (the+ /// root stays; its siblings stay reachable), never as a root of its own. Each folder is listed+ /// once however its path is spelled (the first spelling wins), and hidden ones are left out —+ /// they stay reachable through breadcrumbs and Browse Folder….-pub(crate) fn local_places(++#[cfg(test)]++fn local_places(+ builtin: Vec<(String, String)>,+ saved: &[String],+ browsing: Option<&str>,+ browse_root: Option<&str>,+ hidden: &[String],++) -> LocalPlaces {++ local_places_with_unlisted(builtin, saved, browsing, browse_root, hidden, &[])++}++++fn local_places_with_unlisted(++ builtin: Vec<(String, String)>,++ saved: &[String],++ browsing: Option<&str>,++ browse_root: Option<&str>,++ hidden: &[String],++ unlisted: &[String],+ ) -> LocalPlaces {+ use lightcraft_catalog::query::{folder_key, folder_within};+ let is_hidden = |p: &str| hidden.iter().any(|h| same_folder(h, p));++ let listed_below = |current: &str, root: &str| {++ folder_within(current, root) && !unlisted.iter().any(|h| !same_folder(h, root) && folder_within(current, h) && folder_within(h, root))++ };+ let mut places = builtin;+ for path in saved {+ if !places.iter().any(|(_, p)| same_folder(p, path)) {+ places.push((folder_label(path), path.clone()));+ }+ }+ places.retain(|(_, p)| !is_hidden(p));+ let mut out = LocalPlaces::default();+ if let Some(c) = browsing- && !places.iter().any(|(_, p)| folder_within(c, p))++ && !places.iter().any(|(_, p)| listed_below(c, p))+ {- let root = browse_root.filter(|r| folder_within(c, r)).unwrap_or(c);++ let root = browse_root.filter(|r| listed_below(c, r)).unwrap_or(c);+ if !is_hidden(root) {+ places.push((folder_label(root), root.to_string()));+ out.browse_root = Some(root.to_string());+ }+ }+ if let Some(c) = browsing {+ // A tree never opens on the way down through a hidden folder: hiding a kept folder+ // beneath Home would otherwise reveal it again inside Home's (possibly huge) tree.+ let through_hidden = |p: &str| hidden.iter().any(|h| folder_within(c, h) && folder_within(h, p));+ out.owner = places+ .iter()+ .enumerate()- .filter(|(_, (_, p))| folder_within(c, p) && !through_hidden(p))++ .filter(|(_, (_, p))| listed_below(c, p) && !through_hidden(p))+ .max_by_key(|(_, (_, p))| folder_key(p).len())+ .map(|(i, _)| i);+ }+ out.places = places;+ out+ }+++fn unlisted_ancestors(path: &str) -> Vec<String> {++ std::path::Path::new(path).ancestors().filter(|p| lightcraft_engine::walk::is_hidden_path(p)).map(|p| p.to_string_lossy().to_string()).collect()++}+++ /// The subfolders of `path` (not hidden ones), sorted; listed on a worker thread at most every+ /// 2 s per folder (empty until the first listing).-pub(super) fn subfolders(ui: &egui::Ui, path: &str) -> Vec<(String, String)> {++pub(super) fn subfolders(ui: &egui::Ui, path: &str) -> std::sync::Arc<Vec<(String, String)>> {+ fs_cached(ui, "subfolders", path, 2.0, list_subfolders).unwrap_or_default()+ }+-fn list_subfolders(path: &str) -> Vec<(String, String)> {++fn list_subfolders(path: &str) -> std::sync::Arc<Vec<(String, String)>> {+ let mut v: Vec<(String, String)> = std::fs::read_dir(path)+ .map(|rd| {+ rd.flatten()- .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))- .filter_map(|e| {++ .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !lightcraft_engine::walk::is_hidden_entry(e))++ .map(|e| {+ let name = e.file_name().to_string_lossy().to_string();- (!name.starts_with('.')).then(|| (name, e.path().to_string_lossy().to_string()))++ (name, e.path().to_string_lossy().to_string())+ })+ .collect()+ })+ .unwrap_or_default();+ v.sort_by_key(|(n, _)| n.to_lowercase());- v++ v.into()+ }++ /// How many [`fs_cached`] answers for `ctx` are being worked out right now. Rows appear (and+ /// the sidebar below them moves) when they land, so the headless driver counts them as pending+ /// work and waits for them before acting on widget positions.+ pub(crate) fn fs_cached_running(ctx: &egui::Context) -> usize {+ fs_running_counter(ctx).load(std::sync::atomic::Ordering::Acquire)+ }++ fn fs_running_counter(ctx: &egui::Context) -> std::sync::Arc<std::sync::atomic::AtomicUsize> {+ ctx.data_mut(|d| d.get_temp_mut_or_default::<std::sync::Arc<std::sync::atomic::AtomicUsize>>(egui::Id::unique("fs-cached-running")).clone())+ }++ /// A file-system answer for `path` (`f(path)`), kept per `kind` and path and refreshed on a worker+ /// thread at most every `every` seconds: a folder on a sleeping NAS, a dropped share or a+ /// spinning-up drive never blocks a frame. `None` until the first answer arrives.+ pub(crate) fn fs_cached<T: Clone + Send + 'static>(ui: &egui::Ui, kind: &'static str, path: &str, every: f64, f: fn(&str) -> T) -> Option<T> {+ struct Entry<T> {+ value: Option<T>,+ at: Option<f64>,+ running: bool,+ }+ type Cell<T> = std::sync::Arc<std::sync::Mutex<Entry<T>>>;+ let id = egui::Id::unique(("fs-cached", kind, path.to_string()));+ let now = ui.input(|i| i.time);+ let cell: Cell<T> = match ui.data(|d| d.get_temp::<Cell<T>>(id)) {+ Some(c) => c,+ None => {+ let c: Cell<T> = std::sync::Arc::new(std::sync::Mutex::new(Entry { value: None, at: None, running: false }));+ ui.data_mut(|d| d.insert_temp(id, c.clone()));+ c+ }+ };+ let lock = |c: &Cell<T>| c.lock().unwrap_or_else(std::sync::PoisonError::into_inner).value.clone();+ let start = {+ let mut e = cell.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ let due = !e.running && e.at.is_none_or(|at| now - at >= every || now < at);+ if due {+ e.running = true;+ e.at = Some(now);+ }+ due+ };+ if start {+ use std::sync::atomic::Ordering;+ let running = fs_running_counter(ui.ctx());+ running.fetch_add(1, Ordering::AcqRel);+ let (out, path, repaint, done) = (cell.clone(), path.to_string(), ui.ctx().clone(), running.clone());+ let work = move || {+ let v = f(&path);+ let mut e = out.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ e.value = Some(v);+ e.running = false;+ drop(e);+ // after the answer is stored: a frame that sees the count drop also sees the answer+ done.fetch_sub(1, Ordering::AcqRel);+ repaint.request_repaint();+ };+ #[cfg(not(target_arch = "wasm32"))]+ if std::thread::Builder::new().name("lc-fs-list".into()).spawn(work).is_err() {+ cell.lock().unwrap_or_else(std::sync::PoisonError::into_inner).running = false;+ running.fetch_sub(1, Ordering::AcqRel);+ }+ #[cfg(target_arch = "wasm32")]+ work();+ }+ lock(&cell)+ }++ #[cfg(test)]+ mod tests {+ use super::local_places;+ use crate::widgets::elide_head;+++ #[test]++ fn injected_places_replace_the_machine_home() {++ let places = vec![("Sandbox".to_string(), "/lightcraft-test/home".to_string())];++ let services = crate::Services { local_places: Some(places.clone()), ..Default::default() };++ let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::new(), services);++ let mut view = crate::headless::HeadlessView::new();++ let raw = crate::headless::HeadlessView::raw_input(egui::vec2(300.0, 200.0), 1.0, 0.0, vec![]);++ view.run(raw, |ui| {++ assert_eq!(super::local_now(&mut app, ui).unwrap().places.places, places);++ });++ }++++ #[test]++ fn local_folder_rows_outside_the_viewport_skip_interactive_widgets() {++ let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::new(), crate::Services::default());++ let mut view = crate::headless::HeadlessView::new();++ for frame in 0..3 {++ let raw = crate::headless::HeadlessView::raw_input(egui::vec2(300.0, 160.0), 1.0, frame as f64 / 60.0, vec![]);++ view.run(raw, |ui| {++ egui::ScrollArea::vertical().show(ui, |ui| {++ for index in 0..500 {++ let path = format!("/lightcraft-test/folder-{index:04}");++ super::folder_tree(&mut app, ui, &path, &format!("Folder {index}"), &path, 0.0, None, false, false);++ }++ });++ });++ let widgets = crate::widgets::take_registry(&view.ctx);++ if frame == 2 {++ let rows = widgets.iter().filter(|(id, _)| id.starts_with("source:local:")).count();++ let toggles = widgets.iter().filter(|(id, _)| id.starts_with("folderToggle:")).count();++ assert_eq!(rows, 500, "offscreen rows remain available for scrolling");++ assert!((1..=10).contains(&toggles), "only visible rows build interactive widgets: {toggles}");++ }++ }++ }++++ #[test]++ fn browsing_below_an_unlisted_folder_has_a_session_root() {++ let home = "/home/example";++ let hidden = format!("{home}/.hidden");++ let current = format!("{hidden}/Photos");++ let builtin = || vec![("Home".into(), home.into())];++ let unlisted = vec![hidden];++ let first = super::local_places_with_unlisted(builtin(), &[], Some(¤t), None, &[], &unlisted);++ assert_eq!(first.browse_root.as_deref(), Some(current.as_str()));++ assert_eq!(first.owner, Some(1));++ let child = format!("{current}/Trip");++ let next = super::local_places_with_unlisted(builtin(), &[], Some(&child), first.browse_root.as_deref(), &[], &unlisted);++ assert_eq!(next.browse_root, first.browse_root);++ assert_eq!(next.owner, Some(1));++ let kept = super::local_places_with_unlisted(builtin(), std::slice::from_ref(¤t), Some(&child), None, &[], &unlisted);++ assert_eq!(kept.browse_root, None);++ assert_eq!(kept.owner, Some(1));++ let deeper = format!("{current}/.private");++ let inside = format!("{deeper}/Trip");++ let unlisted = vec![unlisted[0].clone(), deeper];++ let moved = super::local_places_with_unlisted(builtin(), &[], Some(&inside), first.browse_root.as_deref(), &[], &unlisted);++ assert_eq!(moved.browse_root.as_deref(), Some(inside.as_str()));++ assert_eq!(moved.owner, Some(1));++ }++++ #[test]++ fn subfolders_leave_out_hidden_folders() {++ let dir = std::env::temp_dir().join(format!("lc-ui-hidden-subfolders-{}", std::process::id()));++ let _ = std::fs::remove_dir_all(&dir);++ for name in ["Shown", ".dot", "Hidden"] {++ std::fs::create_dir_all(dir.join(name)).unwrap();++ }++ #[cfg(windows)]++ assert!(std::process::Command::new("attrib").arg("+h").arg(dir.join("Hidden")).status().unwrap().success());++ #[cfg(target_os = "macos")]++ assert!(std::process::Command::new("chflags").arg("hidden").arg(dir.join("Hidden")).status().unwrap().success());++ let expected = if cfg!(any(windows, target_os = "macos")) { vec!["Shown"] } else { vec!["Hidden", "Shown"] };++ let listed = super::list_subfolders(&dir.to_string_lossy());++ assert_eq!(listed.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), expected);++ let unlisted = super::unlisted_ancestors(&dir.join(".dot/Photos").to_string_lossy());++ assert!(unlisted.contains(&dir.join(".dot").to_string_lossy().to_string()));++ if cfg!(any(windows, target_os = "macos")) {++ let unlisted = super::unlisted_ancestors(&dir.join("Hidden/Photos").to_string_lossy());++ assert!(unlisted.contains(&dir.join("Hidden").to_string_lossy().to_string()));++ }++ std::fs::remove_dir_all(&dir).unwrap();++ }+++ /// Width = characters, so a limit of 12 is "12 characters".+ fn fit(text: &str, max: usize) -> String {+ elide_head(text, max as f32, |s| s.chars().count() as f32)+ }++ #[test]+ fn a_label_that_fits_is_left_alone() {+ assert_eq!(fit("/Users/me/Pictures", 18), "/Users/me/Pictures");+ }++ #[test]+ fn a_long_path_loses_its_leading_folders_not_its_end() {+ assert_eq!(fit("/Users/me/Pictures/Lightroom", 20), "…/Pictures/Lightroom");+ assert_eq!(fit("/Users/me/Pictures/Lightroom", 12), "…/Lightroom");+ }++ #[test]+ fn a_single_name_too_long_is_cut_at_the_end() {+ assert_eq!(fit("2024-summer-holiday", 8), "2024-su…");+ assert_eq!(fit("2024-summer-holiday", 1), "…");+ assert_eq!(fit("2024-summer-holiday", 0), "…");+ }++ #[test]+ fn multibyte_names_are_cut_on_character_boundaries() {+ assert_eq!(fit("/写真/夏休み旅行の記録", 6), "夏休み旅行…");+ }++ fn names(v: &[(String, String)]) -> Vec<&str> {+ v.iter().map(|(n, _)| n.as_str()).collect()+ }++ /// A built-in location browsed (or picked) under another spelling of its path is the same+ /// row, not a second root — for every built-in, not just named ones.+ #[test]+ fn equivalent_paths_are_one_local_location() {+ for (home, sep) in [("D:\\Example", '\\'), ("D:/Example", '/'), ("/home/example", '/')] {+ let builtin: Vec<(String, String)> =+ ["Pictures", "Desktop", "Downloads"].iter().map(|s| (s.to_string(), format!("{home}{sep}{s}"))).collect();+ for (_, p) in builtin.clone() {+ // the browsed spelling: other separators, a trailing one, a different drive-letter case+ let flipped = p.replace(['/', '\\'], if sep == '/' { "\\" } else { "/" });+ for browsing in [flipped.clone(), format!("{p}{sep}"), p.replacen("D:", "d:", 1)] {+ let l = local_places(builtin.clone(), std::slice::from_ref(&browsing), Some(&browsing), None, &[]);+ assert_eq!(names(&l.places), ["Pictures", "Desktop", "Downloads"], "{p} browsed as {browsing}");+ assert_eq!(l.places[l.owner.unwrap()].1, p, "the built-in row is the one highlighted");+ }+ // hiding under one spelling hides the other+ let l = local_places(builtin.clone(), &[], None, None, std::slice::from_ref(&flipped));+ assert_eq!(l.places.len(), 2, "hidden {flipped}");+ }+ }+ // a different folder is still added+ let l = local_places(vec![("Pictures".into(), "/home/example/Pictures".into())], &[], Some("/home/example/Pictures2"), None, &[]);+ assert_eq!(names(&l.places), ["Pictures", "Pictures2"]);+ }++ /// A folder inside a kept root is shown inside that root's tree: the root stays (its other+ /// subfolders stay reachable) and no second root appears; other kept roots stay too.+ #[test]+ fn browsing_below_a_kept_root_keeps_the_root() {+ let photos = "/data/Photos".to_string();+ let other = "/data/Scans".to_string();+ let saved = [photos.clone(), other.clone()];+ let builtin = || vec![("Home".to_string(), "/home/example".to_string())];+ for browsing in ["/data/Photos/2026/20260101", "/data/Photos/2026", "/data/Photos", "D:\\x"] {+ let l = local_places(builtin(), &saved, Some(browsing), None, &[]);+ let roots: Vec<&str> = l.places.iter().map(|(_, p)| p.as_str()).collect();+ if browsing.starts_with("/data") {+ assert_eq!(roots, ["/home/example", "/data/Photos", "/data/Scans"], "{browsing}");+ assert_eq!(l.owner, Some(1), "the Photos tree opens down to {browsing}");+ assert_eq!(l.browse_root, None);+ } else {+ assert_eq!(roots, ["/home/example", "/data/Photos", "/data/Scans", "D:\\x"], "a folder outside them gets a row");+ }+ }+ // the innermost containing root is the one that opens+ let l = local_places(builtin(), &["/home/example/Pictures".into()], Some("/home/example/Pictures/Trip"), None, &[]);+ assert_eq!(l.owner, Some(1));+ }++ /// A browsed folder outside every kept root gets a session row, which stays while browsing+ /// below it and gives way when browsing moves elsewhere.+ #[test]+ fn session_root_stays_while_browsing_below_it() {+ let l = local_places(Vec::new(), &[], Some("/t/base"), None, &[]);+ assert_eq!(l.browse_root.as_deref(), Some("/t/base"));+ let l = local_places(Vec::new(), &[], Some("/t/base/Trip/Day 1"), l.browse_root.as_deref(), &[]);+ assert_eq!((l.places.len(), l.browse_root.as_deref(), l.owner), (1, Some("/t/base"), Some(0)), "{l:?}");+ let l = local_places(Vec::new(), &[], Some("/elsewhere"), l.browse_root.as_deref(), &[]);+ assert_eq!(l.browse_root.as_deref(), Some("/elsewhere"));+ // hidden: no row at all+ let l = local_places(Vec::new(), &[], Some("/t/base"), None, &["/t/base/".into()]);+ assert!(l.places.is_empty() && l.browse_root.is_none());+ }++ /// A hidden folder inside a listed one (a kept folder beneath Home) is not revealed in that+ /// one's tree while it is browsed, nor are the folders below it; hiding Home itself still+ /// lets Pictures open down to a folder browsed inside it.+ #[test]+ fn hidden_folder_is_not_revealed_in_an_outer_tree() {+ let builtin = || vec![("Pictures".to_string(), "/home/example/Pictures".to_string()), ("Home".to_string(), "/home/example".to_string())];+ let kept = ["/home/example/AppData/Temp/lc".to_string()];+ let l = local_places(builtin(), &kept, Some("/home/example/AppData/Temp/lc"), None, &[]);+ assert_eq!(l.owner, Some(2), "shown as its own kept row");+ for browsing in ["/home/example/AppData/Temp/lc", "/home/example/AppData/Temp/lc/Day 1"] {+ let l = local_places(builtin(), &kept, Some(browsing), None, &["/home/example/AppData/Temp/lc/".into()]);+ assert_eq!(names(&l.places), ["Pictures", "Home"], "{browsing}");+ assert_eq!((l.owner, l.browse_root.as_deref()), (None, None), "Home does not open down to {browsing}");+ }+ let l = local_places(builtin(), &[], Some("/home/example/Pictures/Trip"), None, &["/home/example".into()]);+ assert_eq!((names(&l.places), l.owner), (vec!["Pictures"], Some(0)));+ }++ #[test]+ fn a_local_folder_lines_up_with_the_rows_above_and_its_triangle_stays_left_of_the_icon() {+ use crate::Services;+ use crate::headless::HeadlessView;+ let mut app = crate::LightcraftApp::new(lightcraft_engine::Session::new(), Services::default());+ let mut view = HeadlessView::new();+ let path = "/lightcraft-test/Pictures";+ let mut widgets = vec![];+ for frame in 0..3 {+ let raw = HeadlessView::raw_input(egui::vec2(300.0, 200.0), 1.0, frame as f64 / 60.0, vec![]);+ view.run(raw, |ui| {+ super::row(&mut app, ui, "all", super::Icon::Photos, "All Photos", None, false, 0.0);+ super::folder_tree(&mut app, ui, path, "Pictures", path, 0.0, None, false, false);+ });+ widgets = crate::widgets::take_registry(&view.ctx);+ }+ let rect = |id: &str| widgets.iter().find(|(w, _)| w == id).unwrap_or_else(|| panic!("{id} not registered")).1;+ let (all, local) = (rect("label:all"), rect(&format!("label:local:{path}")));+ assert_eq!(local.left(), all.left(), "a top-level Local folder's name starts where All Photos' does");+ let triangle = rect(&format!("folderToggle:{path}"));+ // the icon is 16 points wide and ends 8 points before the name+ assert!(triangle.right() <= local.left() - 24.0, "triangle {triangle:?} overlaps the icon before {local:?}");+ }+ }diff --cc crates/ui-egui/src/services.rsindex 000000000,ccce723fb..8eb13aa85mode 000000,100644..100644--- a/crates/ui-egui/src/services.rs+++ b/crates/ui-egui/src/services.rs@@@ -1,0 -1,130 +1,132 @@@+ use super::*;++ pub type PickFiles = Box<dyn FnMut() -> Vec<String>>;++ /// A save dialog: suggested file name → chosen path (`None` = cancelled).+ pub type SaveFile = Box<dyn FnMut(&str) -> Option<String>>;++ pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;++ /// A writer other threads can use (background export).+ pub type SharedWrite = std::sync::Arc<dyn Fn(&str, &[u8]) -> Result<(), String> + Send + Sync>;++ pub type PngEncode = Box<dyn Fn(&lightcraft_raster::Rgba8) -> Vec<u8>>;++ /// A folder chooser (`None` = cancelled).+ pub type PickFolder = Box<dyn FnMut() -> Option<String>>;++ /// Reveal a file in the system file manager (Finder / Explorer / the folder on Linux).+ pub type RevealFn = Box<dyn FnMut(&str) -> Result<(), String>>;++ /// Open a URL in the user's browser.+ pub type OpenUrlFn = Box<dyn FnMut(&str) -> Result<(), String>>;++ /// Open a file in an application (`app` = "" for the system's default one).+ pub type OpenWithFn = Box<dyn FnMut(&str, &str) -> Result<(), String>>;++ /// Open several files with one start of an application (`app` as for [`OpenWithFn`]).+ pub type OpenAllWithFn = Box<dyn FnMut(&[String], &str) -> Result<(), String>>;++ /// Linux model-folder work: wait for the default opener on a background task.+ #[cfg(target_os = "linux")]+ pub type OpenModelFolderFn = std::sync::Arc<dyn Fn(&str) -> Result<(), String> + Send + Sync>;++ /// The ICC profile of the screen showing the window, as the system colour-manages it (`None`:+ /// not known).+ pub type ScreenProfileFn = Box<dyn FnMut() -> Option<Vec<u8>>>;++ /// Whether an external editor can be started (its name as in [`Services::open_with`]); the+ /// error says why not and what to do (e.g. PhotoCraft isn't installed).+ pub type CheckEditorFn = Box<dyn Fn(&str) -> Result<(), String>>;++ /// Something the host does with the session (web: back up or restore the library in browser+ /// storage); the work may finish asynchronously.+ pub type HostAction = Box<dyn FnMut(&mut Session) -> Result<Value, String>>;++ /// The system's dark/light appearance where egui doesn't report one (Linux desktops whose+ /// windowing layer says nothing, e.g. many Wayland compositors). The host answers from what it+ /// last heard and wakes the UI itself when that changes; it is never polled for changes.+ pub type SystemThemeFn = Box<dyn Fn(&egui::Context) -> Option<egui::Theme>>;++ /// Platform services injected by the host app (desktop or web).+ #[derive(Default)]+ pub struct Services {++ /// Local's built-in places as (label, path). None uses the host's home folder.++ pub local_places: Option<Vec<(String, String)>>,+ /// Native file dialogs for commands, shown off the UI thread and answered later+ /// (`pick`; #191). With it, the synchronous pickers below serve only the buttons inside+ /// dialogs; without it (the web, tests) they answer the commands too.+ pub picker: Option<pick::Picker>,+ /// Show an open dialog for photos; returns paths.+ pub pick_files: Option<PickFiles>,+ /// Local ONNX model; a manifest must accompany it.+ pub pick_denoise_model: Option<PickFiles>,+ /// Open dialog for a face model (`.onnx`; Settings ▸ Faces ▸ Add a model file…).+ pub pick_model_file: Option<PickFiles>,+ /// Open dialog for preset files (`.lcpreset`, `.xmp`, `.lrtemplate`, `.zip`, `.dng`, Luminar `.lmp` / `.mplumpack`).+ pub pick_preset_files: Option<PickFiles>,+ /// Open dialog for a GPS track log (`.gpx`; Photo ▸ Auto-Tag from Tracklog…).+ pub pick_tracklog: Option<PickFiles>,+ /// Open dialog for a monitor ICC profile (`.icc` / `.icm`; Settings ▸ Display; desktop only).+ pub pick_display_profile: Option<PickFiles>,+ /// The profile of the screen showing the window, used while none is chosen in Settings ▸+ /// Display (macOS, whose windows aren't colour-managed: issue #787).+ pub screen_profile: Option<ScreenProfileFn>,+ /// Save dialog for an exported `.lcpreset` file.+ pub save_preset_file: Option<SaveFile>,+ /// Open dialog for a keyword list file (`.txt`, Photo Supreme's `.utf8`; File ▸ Import Keywords…).+ pub pick_keyword_list: Option<PickFiles>,+ /// Save dialog for an exported keyword list (File ▸ Export Keywords…).+ pub save_keyword_list: Option<SaveFile>,+ /// Open dialog for point-curve preset files (`.lccurve`).+ pub pick_curve_preset_files: Option<PickFiles>,+ /// Save dialog for an exported `.lccurve` file.+ pub save_curve_preset_file: Option<SaveFile>,+ /// Open dialog for slideshow template files (`.json`; Settings ▸ Slideshow ▸ Templates ▸ Import…).+ pub pick_slideshow_templates: Option<PickFiles>,+ /// Save dialog for an exported slideshow template (`.json`).+ pub save_slideshow_template: Option<SaveFile>,+ /// Open dialog for print template files (`.lcprint`; File ▸ Print… ▸ Templates ▸ Import…).+ pub pick_print_templates: Option<PickFiles>,+ /// Save dialog for an exported print template (`.lcprint`).+ pub save_print_template: Option<SaveFile>,+ pub write: Option<WriteFn>,+ /// Create-new writer (never replaces an existing path), for screenshots of destinations that+ /// did not exist when the request was admitted. Required for such captures: falling back to+ /// [`Self::write`] would reopen the admission-to-write race.+ pub write_new: Option<WriteFn>,+ /// Thread-safe writer: with it, UI-started exports run in the background (desktop only).+ pub write_shared: Option<SharedWrite>,+ /// PNG encoder (the host links an image encoder; the UI crate stays codec-free).+ pub png: Option<PngEncode>,+ /// Show a file in the system file manager (desktop only).+ pub reveal: Option<RevealFn>,+ /// The host's current log file (`<settings>/logs/lightcraft.log`), which Help ▸ Open Log+ /// Folder reveals (#260). None where no log is kept: the web, `--memory`, `LIGHTCRAFT_NO_PREFS`.+ pub log_file: Option<String>,+ /// Choose a folder (Settings → General → Open Library…; desktop only).+ pub pick_folder: Option<PickFolder>,+ /// Open a Lightroom Classic `.lrcat` catalog for read-only import.+ pub pick_lightroom_catalog: Option<PickFolder>,+ /// Open a web link in the browser (Help menu, About, Discord button).+ pub open_url: Option<OpenUrlFn>,+ /// Open a file in an external editor (Edit in External Editor; desktop only).+ pub open_with: Option<OpenWithFn>,+ /// Open several files with one start of the editor (Open Original; desktop only): an editor+ /// that keeps one window takes them all. None = [`Services::open_with`] for each.+ pub open_all_with: Option<OpenAllWithFn>,+ /// Optional worker-safe model-folder opener alongside `open_with` (Linux desktop only).+ #[cfg(target_os = "linux")]+ pub open_model_folder: Option<OpenModelFolderFn>,+ /// Checked before Edit In renders a copy, so a missing editor leaves no copy behind (none =+ /// assume it can).+ pub check_editor: Option<CheckEditorFn>,+ /// File ▸ Back Up Library…: save the whole library (catalog and originals) as one file the+ /// user keeps (web only: there the library lives in browser storage, which the browser may+ /// clear; on the desktop it is a folder backed up like any other).+ pub backup_library: Option<HostAction>,+ /// File ▸ Restore Library from Backup… (web only; keeps the current library).+ pub restore_library: Option<HostAction>,+ /// The system appearance for Appearance Mode ▸ Auto, ahead of egui's own report.+ pub system_theme: Option<SystemThemeFn>,+ }diff --cc crates/ui-egui/src/tests/panels.rsindex 96b0a1a9d,569a12910..5208de9b7--- a/crates/ui-egui/src/tests/panels.rs+++ b/crates/ui-egui/src/tests/panels.rs@@@ -13,7 -13,7 +13,7 @@@ const T: Duration = Duration::from_secsconst SETTLE: Duration = Duration::from_secs(120);fn demo(size: [f32; 2], ui: serde_json::Value) -> Headless {-- let services = Services { png: None, ..Default::default() };++ let services = Services { png: None, local_places: Some(Vec::new()), ..Default::default() };let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), services);let mut h = Headless::new(app, size, 1.0);let r = h.request("ui.set", ui, T);