LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
refactor(lightcraft-ui-egui): split dialogs.rs into dialogs/
aiongg56494a130824
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 00b131713..772303ffb 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -7,6 +7,31 @@ use crate::LightcraftApp;use crate::state::Dialog;use crate::theme::Tokens;+mod confirm;+mod cull;+mod export;+mod frame;+mod rename;+mod sam_model;++pub(crate) use confirm::album_entries;+pub use confirm::confirm_dialog;+pub use cull::{MAX_BURST_GAP, clamp_cull_burst, cull_params, fmt_gap, parse_gap};+use export::{+ LIMIT_KB, QUALITY, START_NUMBER, WM_IMAGE_WIDTH, WM_INSET_X, WM_INSET_Y, WM_OPACITY, WM_POSITIONS, WM_SIZE, export_dialog_params, export_size,+ group_checklist, watermark_preview,+};+pub use frame::{ConfirmStyle, confirm_style, list_height, prompt};+use frame::{+ DIALOG_CHROME_GUESS, DIALOG_MIN_BODY, DIALOG_SCREEN_MARGIN, choices, clicked_backdrop, dialog_body, dialog_field, field, just_opened, num,+ only_shows, return_confirms, trailing_button_row,+};+pub(crate) use rename::rename_preview;+use rename::{RENAME_PREVIEW_ROWS, person_rename_plan};+pub(crate) use sam_model::show_model_folder;+use sam_model::{sam_by_hand, sam_model_body};+use slideshow_export::slideshow_export_body;+pub mod credits;pub mod faces;pub mod import;@@ -19,171 +44,6 @@ pub mod settings;pub mod slideshow_export;pub mod updates_ui;-/// Rows the Rename dialog previews.-const RENAME_PREVIEW_ROWS: usize = 6;--/// The Rename dialog's preview: its first rows (`None` while being planned) and how many files-/// are renamed. Which names are taken is checked on disk, which can block on a slow drive, so the-/// rows are planned on a worker thread, and only when the template, start number, photos or-/// catalog change — never once per frame.-pub(crate) fn rename_preview(- app: &mut LightcraftApp,- ctx: &egui::Context,- template: &str,- start: usize,-) -> (Option<Vec<lightcraft_engine::rename::RenamePlan>>, usize) {- use std::hash::{Hash, Hasher};- type Rows = std::sync::Arc<std::sync::Mutex<Option<Vec<lightcraft_engine::rename::RenamePlan>>>>;- let ids = app.session.selected();- let photos = lightcraft_engine::rename::rename_photos(&app.session.catalog, &ids);- let total = photos.len();- let mut h = std::collections::hash_map::DefaultHasher::new();- (template, start, app.session.catalog.revision, &ids).hash(&mut h);- let key = h.finish();- let id = egui::Id::unique("rename-preview-rows");- let read = |rows: &Rows| rows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();- if let Some((k, rows)) = ctx.data(|d| d.get_temp::<(u64, Rows)>(id))- && k == key- {- return (read(&rows), total);- }- let rows: Rows = Default::default();- let first: Vec<_> = photos.into_iter().take(RENAME_PREVIEW_ROWS).collect();- let (out, template, repaint) = (rows.clone(), template.to_string(), ctx.clone());- let exists = app.session.media.availability.probe();- let work = move || {- let plans = lightcraft_engine::rename::plan_rename_photos(&first, &template, start, &|f| exists(f));- *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(plans);- repaint.request_repaint();- };- #[cfg(not(target_arch = "wasm32"))]- if let Err(e) = std::thread::Builder::new().name("lc-rename-preview".into()).spawn(work) {- log::warn!("rename preview: {e}");- }- #[cfg(target_arch = "wasm32")]- work();- ctx.data_mut(|d| d.insert_temp(id, (key, rows.clone())));- (read(&rows), total)-}--/// The Export dialog's watermark preview: the first exported photo, as wide as the dialog whatever-/// its shape, with the watermark drawn on it as the file will have it at size `resize` (`None` =-/// full size). On a worker thread, once per photo, catalog change and size step, the cached-/// thumbnail comes first (at once, a little soft) and then a render at the preview's own pixel size-/// replaces it. The watermark is redrawn on a copy only when it, the output size or the picture-/// changes, which is quick at this size, so the preview follows the sliders.-fn watermark_preview(- app: &mut LightcraftApp,- ui: &mut egui::Ui,- wm: &lightcraft_engine::export::Watermark,- resize: Option<lightcraft_engine::export::Resize>,-) {- use std::hash::{Hash, Hasher};- // (pictures received so far: 1 the thumbnail, 2 the sharp render; the latest, or why none came)- type Base = std::sync::Arc<std::sync::Mutex<(u8, Option<Result<lightcraft_raster::Rgba8, String>>)>>;- type Shown = (u64, u8, lightcraft_engine::export::Watermark, usize, egui::TextureHandle);- let t = Tokens::get(ui.ctx());- let Some(&id) = app.session.selected().first() else { return };- let Some(photo) = app.session.catalog.photo(id).cloned() else { return };- let (out_w, out_h) = lightcraft_engine::export::output_size(&photo, &lightcraft_engine::export::ExportOptions { resize, ..Default::default() });- let export_short = out_w.min(out_h);- // pixels across the dialog, in steps so a scroll bar or a point of layout doesn't re-render- let step = 128.0;- let px = ((ui.available_width() * ui.ctx().pixels_per_point() / step).ceil() * step).clamp(step, 2048.0) as usize;- let mut h = std::collections::hash_map::DefaultHasher::new();- (id, app.session.catalog.revision, px).hash(&mut h);- let key = h.finish();- let ctx = ui.ctx().clone();- let (base_id, shown_id) = (egui::Id::unique("export-wm-preview-base"), egui::Id::unique("export-wm-preview-shown"));- let base = match ctx.data(|d| d.get_temp::<(u64, Base)>(base_id)) {- Some((k, base)) if k == key => base,- _ => {- let base: Base = Default::default();- // the thumbnail, then as wide as the dialog (a tall photo up to three times that high)- let jobs: Vec<_> = [app.session.thumb_job(id, 512), app.session.render_job(id, px, px * 3, false, true)].into_iter().flatten().collect();- // the web build has no worker thread: a full render there would hold up the page- #[cfg(target_arch = "wasm32")]- let jobs: Vec<_> = jobs.into_iter().take(1).collect();- if jobs.is_empty() {- *base.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = (1, Some(Err("no such photo".into())));- } else {- let (out, repaint) = (base.clone(), ctx.clone());- let work = move || {- for job in jobs {- // (a panic in the render is its failure: `RenderJob::run`)- let r = job.run().rendered.map(|r| r.image);- let mut got = out.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- // a failed sharp render keeps the thumbnail- if r.is_ok() || !matches!(got.1, Some(Ok(_))) {- *got = (got.0.saturating_add(1), Some(r));- repaint.request_repaint();- }- }- };- #[cfg(not(target_arch = "wasm32"))]- if let Err(e) = std::thread::Builder::new().name("lc-watermark-preview".into()).spawn(work) {- log::warn!("watermark preview: {e}");- }- #[cfg(target_arch = "wasm32")]- work();- }- ctx.data_mut(|d| d.insert_temp(base_id, (key, base.clone())));- base- }- };- let shown = ctx.data(|d| d.get_temp::<Shown>(shown_id));- let stage = base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).0;- let tex = match shown {- Some((k, g, w, s, tex)) if k == key && g == stage && &w == wm && s == export_short => tex,- _ => {- let photo_px = match &base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).1 {- Some(Ok(img)) => Ok(img.clone()),- Some(Err(e)) => Err(Some(e.clone())),- None => Err(None),- };- let mut img = match photo_px {- Ok(img) => img,- Err(e) => {- let note = if e.is_some() { "Preview unavailable" } else { "Loading preview…" };- let r = ui- .horizontal(|ui| {- if e.is_none() {- crate::progress::spinner(ui, 12.0);- }- ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim))- })- .inner;- if let Some(e) = e {- r.on_hover_text(e);- }- return;- }- };- lightcraft_engine::export::draw_watermark_preview(&mut img, wm, export_short);- // shown through the monitor profile like every other preview- if let Some(d) = app.renderer.display()- && let Err(e) = d.profile.from_srgb(&mut img)- {- log::warn!("display profile: {e}");- }- let color = std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], &img.as_bytes()));- let tex = match shown {- Some((.., mut tex)) => {- tex.set(color, egui::TextureOptions::LINEAR);- tex- }- None => ctx.load_texture("export-wm-preview", color, egui::TextureOptions::LINEAR),- };- ctx.data_mut(|d| d.insert_temp(shown_id, (key, stage, wm.clone(), export_short, tex.clone())));- tex- }- };- let size = tex.size_vec2();- let scale = ui.available_width() / size.x.max(1.0);- let r = ui.vertical_centered(|ui| ui.add(egui::Image::new((tex.id(), size * scale)))).inner;- crate::widgets::register(ui, "image:exportWatermarkPreview", r.rect);-}-/// About dialog tabs: (widget id suffix, label). The credits come from `crate::credits`.pub const ABOUT_TABS: &[(&str, &str)] = &[("about", "About"), ("contributors", "Contributors"), ("models", "Models")];@@ -1630,1034 +1490,8 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) {/// The last frame a dialog was drawn and stayed open, for [`clicked_backdrop`].const BACKDROP_SHOWN: &str = "dialog-backdrop-shown";-/// A click on the dimmed backdrop around the dialog: it closes the dialog like Esc. Pressed and-/// released outside the window, so a slider dragged past its edge doesn't close it; a press while a-/// popup is open (a dropdown, a date picker's calendar) only closes the popup: `popup_was_open` is-/// read before the window is drawn, since drawing it already closes the popup. Only a press made-/// while the dialog is shown counts: in the frame a dialog appears, its input is the click that-/// opened it (a quick click on a slow frame presses and releases in that one frame), so it never-/// closes it. (Read from the raw events: egui forgets the press origin on release.)-fn clicked_backdrop(ctx: &egui::Context, window: egui::Rect, popup_was_open: bool) -> bool {- let press_id = egui::Id::unique("dialog-backdrop-press");- let frame = ctx.cumulative_frame_nr();- // the same frame too: a second pass of it gets no input- let shown = ctx.data(|d| d.get_temp::<u64>(egui::Id::unique(BACKDROP_SHOWN))).is_some_and(|f| f + 1 >= frame);- if !shown {- ctx.data_mut(|d| d.remove_temp::<bool>(press_id));- return false;- }- let (press, release, clicked) = ctx.input(|i| {- let at = |down: bool| {- i.events.iter().rev().find_map(|e| match e {- egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } if *pressed == down => Some(*pos),- _ => None,- })- };- (at(true), at(false), i.pointer.primary_clicked())- });- if let Some(p) = press {- let outside = !window.contains(p) && !popup_was_open;- ctx.data_mut(|d| d.insert_temp(press_id, outside));- }- let Some(release) = release else { return false };- let pressed_outside = ctx.data_mut(|d| d.remove_temp::<bool>(press_id)).unwrap_or(false);- clicked && pressed_outside && !window.contains(release)-}--/// Room kept free above and below a dialog (#781).-const DIALOG_SCREEN_MARGIN: f32 = 12.0;-/// A dialog's title bar, frame and button row before the first frame measures them.-const DIALOG_CHROME_GUESS: f32 = 100.0;-/// A dialog's options never get less room than this, however short the window.-const DIALOG_MIN_BODY: f32 = 80.0;--/// A list that scrolls on its own never gets shorter than this to make its dialog fit.-const DIALOG_MIN_LIST: f32 = 120.0;--fn list_shrink_id() -> egui::Id {- egui::Id::unique("dialog-list-shrink")-}--fn list_applied_id() -> egui::Id {- egui::Id::unique("dialog-list-applied")-}--/// The height for a list in a dialog that scrolls on its own (What's New, All Metadata, the-/// shortcuts, smart-album rules): `preferred`, less what the dialog needs to fit the window, so-/// on a short window the list gets shorter rather than scrolling inside a scrolling dialog.-pub fn list_height(ui: &egui::Ui, preferred: f32) -> f32 {- let shrink = ui.data(|d| d.get_temp::<f32>(list_shrink_id())).unwrap_or(0.0);- let height = (preferred - shrink).max(preferred.min(DIALOG_MIN_LIST));- ui.data_mut(|d| *d.get_temp_mut_or_default::<f32>(list_applied_id()) += preferred - height);- height-}--/// A dialog's options: in a vertical scroll area at most `max_height` tall when `scroll` names-/// the dialog (it shrinks to its content, so a dialog that fits looks as it would without it;-/// each dialog keeps a scroll position of its own), drawn directly otherwise. Returns the height-/// they took when scrolled.-fn dialog_body(ui: &mut egui::Ui, scroll: Option<&str>, max_height: f32, body: impl FnOnce(&mut egui::Ui)) -> Option<f32> {- let Some(name) = scroll else {- ui.data_mut(|d| d.remove_temp::<f32>(list_shrink_id()));- body(ui);- return None;- };- ui.data_mut(|d| d.insert_temp(list_applied_id(), 0.0_f32));- let top = ui.cursor().top();- // (an auto-sized window offers its content last frame's height; the minimum lets a dialog- // that grows take its full height at once, and the area still shrinks to fit its content)- let out = egui::ScrollArea::vertical()- .id_salt(("dialog-body", name))- .max_height(max_height)- .min_scrolled_height(max_height)- .auto_shrink([true, true])- .show(ui, body);- // what the lists that scroll on their own gave up this frame, and what they should next frame- let applied = ui.data(|d| d.get_temp::<f32>(list_applied_id())).unwrap_or(0.0);- let was = ui.data(|d| d.get_temp::<f32>(list_shrink_id())).unwrap_or(0.0);- let shrink = (out.content_size.y + applied - max_height).max(0.0);- if (shrink - was).abs() > 0.5 {- ui.data_mut(|d| d.insert_temp(list_shrink_id(), shrink));- ui.ctx().request_repaint();- }- // (the room the scroll area took: its `inner_rect` can be taller than what it allocated)- Some(ui.min_rect().bottom() - top)-}--/// Apply a dialog's action (also used by `ui.dialog.confirm`).-/// What [`fmt_gap`] writes, read back: `90`, `90 s`, `1 min 30 s`, `2 h 5 min`, `1 day`-/// (units `s`, `min`, `h`, `day`, each optional after a plain number of seconds).-pub fn parse_gap(text: &str) -> Option<f64> {- // the one translated text `fmt_gap` writes ("1 Tag")- if text.trim() == crate::i18n::tr("1 day") {- return Some(86400.0);- }- let mut total = 0.0;- let mut seen = false;- let mut words = text.split_whitespace().peekable();- while let Some(word) = words.next() {- // "90s" as well as "90 s"- let split = word.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(word.len());- let (num, unit) = word.split_at(split);- let n: f64 = num.parse().ok().filter(|n: &f64| n.is_finite())?;- let unit = if unit.is_empty() {- match words.peek() {- Some(u) if u.parse::<f64>().is_err() => words.next().unwrap_or_default(),- _ => "s",- }- } else {- unit- };- let scale = match unit.trim_end_matches('.').to_lowercase().as_str() {- "s" | "sec" | "secs" | "second" | "seconds" => 1.0,- "m" | "min" | "mins" | "minute" | "minutes" => 60.0,- "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0,- "d" | "day" | "days" => 86400.0,- _ => return None,- };- total += n * scale;- seen = true;- }- seen.then_some(total)-}--/// The longest burst gap `photo.analyze` accepts: a day.-pub const MAX_BURST_GAP: f32 = 86_400.0;--/// Keep what was typed in the Assisted Culling value fields within what `photo.analyze` accepts-/// (a gap of 0 s to a day, a similarity of 0 to 1), not within the sliders' drag range.-pub fn clamp_cull_burst(gap: &mut f32, similarity: &mut f32) {- *gap = if gap.is_finite() { gap.clamp(0.0, MAX_BURST_GAP) } else { 10.0 };- *similarity = if similarity.is_finite() { similarity.clamp(0.0, 1.0) } else { 0.93 };-}--/// The `photo.analyze` parameters of the Assisted Culling dialog, its values as they are.-pub fn cull_params(reject_below: f32, pick_best: bool, burst_gap: f32, similarity: f32) -> serde_json::Value {- let mut p = json!({"pickBest": pick_best, "burstGap": burst_gap, "similarity": similarity});- if reject_below > 0.0 {- p["rejectBelow"] = json!(reject_below);- }- p-}--/// `90` → `1 min 30 s`.-pub fn fmt_gap(v: f64) -> String {- let v = v.round() as u64;- match v {- 0..60 => format!("{v} s"),- 60..3600 if v.is_multiple_of(60) => format!("{} min", v / 60),- 60..3600 => format!("{} min {} s", v / 60, v % 60),- 3600..86400 if v.is_multiple_of(3600) => format!("{} h", v / 3600),- 3600..86400 if v.is_multiple_of(60) => format!("{} h {} min", v / 3600, v % 3600 / 60),- // the seconds too, so editing the text reads back the same gap- 3600..86400 => format!("{} h {} min {} s", v / 3600, v % 3600 / 60, v % 60),- _ => crate::i18n::tr("1 day").into(),- }-}-/// Whether a dialog stays open after its action succeeded (the SAM 3 dialog while the model/// downloads).pub fn keeps_open(app: &LightcraftApp, dlg: &Dialog) -> bool {matches!(dlg, Dialog::SamModel { .. }) && !app.session.segmenter.installed()}--/// No SAM 3 model, no download running and nowhere to download it from: installing it by hand is-/// all the dialog can offer.-fn sam_by_hand(sam: &lightcraft_engine::segment::Segmenter) -> bool {- !sam.installed() && !sam.download_status().running && sam.mirrors().is_empty()-}--/// The model installation guide.-const SAM_HELP: &str = "https://github.com/storytold/lightcraft/blob/main/docs/ai-masks.md#getting-the-model";--/// Open the configured SAM 3 folder itself; revealing a file opens its parent instead.-pub(crate) fn show_model_folder(app: &mut LightcraftApp) -> Result<serde_json::Value, String> {- let dir = app.session.segmenter.dir.as_ref().ok_or("no folder is set for the SAM 3 model")?;- let path = dir.to_str().ok_or("the model folder path is not valid UTF-8")?;- let open = app.services.open_with.as_mut().ok_or("opening model folders is not available here")?;- // Create only after the host action is available. Existing model files are left alone.- std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;- #[cfg(target_os = "linux")]- if let Some(open_folder) = app.services.open_model_folder.clone() {- let path = path.to_string();- let folder = path.clone();- crate::tasks::spawn(- app,- "Show in File Manager",- Some("openModelFolder"),- move || open_folder(&folder),- |app, ctx, result| {- if let Err(e) = result {- app.toast_error(ctx, e);- }- },- )?;- return Ok(json!({"path": path, "background": true}));- }- open(path, "")?;- Ok(json!({"path": path}))-}--/// The SAM 3 dialog: what the model is, its size and licence, and the download's progress.-fn sam_model_body(app: &mut LightcraftApp, ui: &mut egui::Ui, error: Option<&str>) {- use lightcraft_engine::segment::{LICENSE_NAME, LICENSE_URL, MODEL_BYTES};- let t = Tokens::get(ui.ctx());- let seg = &app.session.segmenter;- let d = seg.download_status();- if seg.installed() {- ui.label(crate::i18n::tr("The SAM 3 model is installed: Object and Describe masks are ready."));- return;- }- let gb = |b: u64| b as f64 / 1e9;- ui.label(crate::i18n::tr(- "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.",- ));- let dir = seg.dir.as_ref().map(|d| d.display().to_string()).unwrap_or_default();- ui.label(format!("{} {:.1} GB, {} {dir}", crate::i18n::tr("A one-time download of about"), gb(MODEL_BYTES), crate::i18n::tr("saved in")));- ui.label(- egui::RichText::new(format!(- "{} {LICENSE_NAME} — {}",- crate::i18n::tr("Licence:"),- crate::i18n::tr("Meta's terms, not LightCraft's. Downloading it means accepting them.")- ))- .color(t.text_label),- );- let r = ui.link(crate::i18n::tr("Read the SAM License")).on_hover_text(LICENSE_URL);- crate::widgets::register(ui, "link:samLicense", r.rect);- if r.clicked() {- let _ = crate::links::open(app, LICENSE_URL);- }- let seg = &app.session.segmenter;- if d.running {- ui.add_space(4.0);- let text = format!("{:.2} / {:.2} GB · {}", gb(d.done), gb(d.total), d.file);- crate::progress::Progress::new(crate::progress::fraction_of(d.done, d.total)).label(text).widget("progress:samDownload").show(ui);- let r = ui.button(crate::i18n::tr("Cancel Download"));- crate::widgets::register(ui, "button:samCancel", r.rect);- if r.clicked() {- app.session.segmenter.cancel_download();- }- ui.label(egui::RichText::new(crate::i18n::tr("You can close this: the download continues, and resumes if interrupted.")).color(t.text_dim));- ui.ctx().request_repaint_after(std::time::Duration::from_millis(250));- return;- }- if seg.mirrors().is_empty() {- // nothing to download from: say how to install it by hand, with the folder and the guide a click away- let dir = seg.dir.clone();- ui.label(- egui::RichText::new(crate::i18n::tr(- "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.",- ))- .color(t.text_dim),- );- ui.horizontal_wrapped(|ui| {- if dir.is_some() && crate::menus::ui_enabled(app, "app.openSamModelFolder") {- let r = ui.button(crate::i18n::tr(crate::menus::reveal_label()));- crate::widgets::register(ui, "button:samFolder", r.rect);- if r.clicked()- && let Err(e) = app.run("app.openSamModelFolder", json!({}))- {- app.toast_error(ui.ctx(), e);- }- }- let r = ui.link(crate::i18n::tr("How to install the model")).on_hover_text(SAM_HELP);- crate::widgets::register(ui, "link:samHelp", r.rect);- if r.clicked()- && let Err(e) = crate::links::open(app, SAM_HELP)- {- app.toast(ui.ctx(), e);- }- });- }- if let Some(e) = error.map(str::to_string).or(d.error) {- ui.label(egui::RichText::new(format!("{} {e}", crate::i18n::tr("The download didn't work:"))).color(egui::Color32::from_rgb(230, 90, 80)));- }-}--/// Runs a command that creates an album and asks the Albums tree to open the folders down to it.-fn created_in(app: &mut LightcraftApp, command: &str, params: serde_json::Value) -> Result<serde_json::Value, String> {- let r = app.run(command, params)?;- app.ui.reveal_album = r.get("id").and_then(serde_json::Value::as_u64);- Ok(r)-}--/// The albums an Album rule in smart album `editing` picks from, in the sidebar's order: the album-/// itself and any smart album that tests it (testing it back would loop) are blocked, with why.-pub(crate) fn album_entries(cat: &lightcraft_catalog::Catalog, editing: Option<u64>) -> Vec<crate::album_picker::AlbumEntry> {- let editing = editing.map(lightcraft_catalog::AlbumId);- crate::album_picker::entries_from(cat, |a| match editing {- Some(e) if a.id == e => Some(crate::i18n::tr("This is the album you're editing").to_string()),- Some(e) if cat.album_reaches(a.id, e) => Some(crate::i18n::tr("It tests this album, so testing it back would loop").to_string()),- _ => None,- })-}--pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_json::Value, String> {- match dlg {- Dialog::LightroomResult { first, .. } => {- if let Some(first) = first {- app.run("library.source", json!({"kind": "all"}))?;- let mut filter = serde_json::to_value(lightcraft_catalog::Filter::default()).map_err(|e| e.to_string())?;- // The filter command merges a patch; these defaults are omitted by serde.- filter["only"] = json!([]);- filter["labels"] = json!([]);- filter["ruleSet"] = serde_json::Value::Null;- app.run("library.filter", filter)?;- app.run("library.select", json!({"ids": [first]}))?;- app.ui.view = crate::state::ViewMode::PhotoGrid;- }- Ok(serde_json::Value::Null)- }- Dialog::SamModel { then, .. } => {- if app.session.segmenter.installed() {- // installed: start what the user was doing- if let Some((kind, op)) = then {- crate::panels::masking::begin_ai(app, kind, op)?;- }- return Ok(serde_json::Value::Null);- }- let r = app.run("segment.model.download", json!({"acknowledged": true}));- if r.is_ok() {- app.ui.sam_downloading = true;- }- r- }- Dialog::NewAlbum { name, folder, parent, include_selected } => {- created_in(app, "album.create", json!({"name": name, "folder": folder, "addSelected": !folder && *include_selected, "parent": parent}))- }- Dialog::RenameAlbum { id, name } => app.run("album.rename", json!({"id": id, "name": name})),- Dialog::TextPrompt { value, command, params, key, .. } => {- let mut p = params.clone();- p[key.as_str()] = json!(value.trim());- app.run(command, p)- }- Dialog::CaptureTime { mode, time, days, hours, minutes, zone } => app.run(- "photo.setCaptureTime",- match mode.as_str() {- "set" => json!({"time": time}),- "shift" => json!({"shift": *days as i64 * 86_400 + *hours as i64 * 3600 + *minutes as i64 * 60}),- _ => json!({"hours": zone}),- },- ),- Dialog::LabelNames { names, save_as } => {- let mut m = serde_json::Map::new();- for (l, n) in lightcraft_catalog::ColorLabel::ALL.iter().zip(names) {- m.insert(format!("{l:?}").to_lowercase(), if n.trim().is_empty() { serde_json::Value::Null } else { json!(n.trim()) });- }- let r = app.run("label.setNames", json!({"names": m}));- if r.is_ok() && !save_as.trim().is_empty() {- return app.run("label.saveSet", json!({"name": save_as.trim()}));- }- r- }- Dialog::Rename { template, start } => app.run("photo.rename", json!({"template": template, "start": start})),- Dialog::RenameKeyword { from, to } => app.run("keyword.rename", json!({"from": from, "to": to})),- Dialog::RenamePerson { from, to, merge } => app.run("faces.renamePerson", json!({"from": from, "to": to.trim(), "merge": merge})),- Dialog::KeywordTag {- editing,- name,- parent,- inside,- synonyms,- include_on_export,- export_containing,- export_synonyms,- person,- add_to_selected,- reveal,- } => {- let mut params = json!({- "synonyms": synonyms.split(',').map(str::trim).filter(|s| !s.is_empty()).collect::<Vec<_>>(),- "includeOnExport": include_on_export,- "exportContaining": export_containing,- "exportSynonyms": export_synonyms,- "person": person,- });- match editing {- Some(keyword) => {- params["keyword"] = json!(keyword);- params["name"] = json!(name);- let r = app.run("keyword.edit", params);- if r.is_ok() {- let to = match keyword.rsplit_once('|') {- Some((parent, _)) => format!("{parent}|{}", name.trim()),- None => name.trim().to_string(),- };- crate::panels::keyword_list::follow(app, keyword, &to);- }- r- }- None => {- params["name"] = json!(name);- params["parent"] = if *inside { json!(parent) } else { serde_json::Value::Null };- params["addToSelected"] = json!(add_to_selected);- let r = app.run("keyword.create", params);- if *reveal && let Ok(made) = &r {- app.ui.reveal_keyword = made["keyword"].as_str().map(str::to_string);- }- r- }- }- }- Dialog::DeleteKeyword { keyword, .. } => app.run("keyword.delete", json!({"keyword": keyword})),- Dialog::KeywordSet { replaces, name, slots, as_new } => {- use lightcraft_catalog::keywords::same;- let name = name.trim();- if name.is_empty() {- return Err(crate::i18n::tr("A keyword set needs a name").to_string());- }- if same(name, lightcraft_engine::cmd::keywords::RECENT) {- return Err(crate::i18n::tr("Recent Keywords is built in: choose another name").to_string());- }- // the set it renames: none when saving as new, or when it was deleted meanwhile (then it is- // saved anew rather than refused)- let sets = &app.session.keyword_sets;- let renames = replaces.as_deref().filter(|_| !as_new).filter(|old| sets.iter().any(|x| same(&x.name, old)));- if sets.iter().any(|x| same(&x.name, name) && !renames.is_some_and(|old| same(&x.name, old))) {- return Err(crate::i18n::tr_format!("There is a keyword set “{name}” already", name = name));- }- let mut params = json!({"name": name, "keywords": slots});- match renames {- Some(old) => params["replace"] = json!(old),- None => params["new"] = json!(true),- }- app.run("keyword.saveSet", params)- }- Dialog::MoveKeyword { keyword, parent } => {- let r = app.run("keyword.move", json!({"keyword": keyword, "parent": parent, "merge": true}));- if r.is_ok() {- let leaf = keyword.rsplit('|').next().unwrap_or(keyword);- let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}|{leaf}"));- crate::panels::keyword_list::follow(app, keyword, &to);- }- r- }- Dialog::MergeKeywords { from, into } => app.run("keyword.merge", json!({"from": from, "into": into})),- Dialog::AutoStack { gap } => app.run("stack.auto", json!({"gap": gap})),- Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::install(app, info, *accepted),- Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted),- Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null),- Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => {- app.ui.cull_burst = Some((*burst_gap, *similarity));- app.run("photo.analyze", cull_params(*reject_below, *pick_best, *burst_gap, *similarity))- }- Dialog::SmartRules { id, name, rules, parent } => {- // refused before anything changes (not even the name)- if let Some(problem) = rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).first() {- return Err(problem.to_string());- }- let name = if name.trim().is_empty() { "Smart Album".to_string() } else { name.trim().to_string() };- match id {- // the name and the rules together: one undo step, both or neither- Some(id) => app.run("album.setRules", json!({"id": id, "name": name, "replace": true, "rules": {"ruleSet": rules}})),- None => created_in(app, "album.createSmart", json!({"name": name, "rules": {"ruleSet": rules}, "parent": parent})),- }- }- Dialog::NewSmartAlbum { name, parent } => {- created_in(app, "album.createSmart", json!({"name": if name.trim().is_empty() { "Smart Album" } else { name }, "parent": parent}))- }- Dialog::CreatePreset { name, group, groups } => app.run(- "preset.create",- json!({- "name": if name.trim().is_empty() { "My Preset" } else { name },- "group": if group.trim().is_empty() { "User Presets" } else { group },- "groups": groups,- }),- ),- Dialog::ContactSheet { options } => app.run("app.contactSheet", json!(options)),- Dialog::SlideshowExport { settings } => app.run("app.slideshowExport", json!(settings)),- Dialog::Print => app.run("app.print", json!({})),- Dialog::CopySettings { groups } => app.run("develop.copy", json!({"groups": groups})),- Dialog::PasteSettings { groups } => app.run("develop.paste", json!({"groups": groups})),- Dialog::Export { opts, full_size, resize, limit_kb, dir, .. } => {- let mut p = export_dialog_params(opts, *full_size, resize, *limit_kb);- p["dir"] = json!(dir);- p["background"] = json!(true);- app.run("app.export", p)- }- Dialog::Merge { opts } => crate::merge::start_final(app, opts),- Dialog::Import { opts } => crate::import::start(app, opts),- Dialog::ConfirmDelete { .. } => app.run("photo.delete", json!({})),- Dialog::MovePhotos { ids, folder, dont_ask, library, .. } => {- // another library opened meanwhile (from the menu bar, an agent): these numbers are- // other photos there- if *library != app.session.library_generation() {- return Err(crate::i18n::tr("Another library was opened since the photos were dropped: nothing was moved").to_string());- }- if *dont_ask {- app.ui.settings.ask_before_move = false;- }- crate::panels::left::move_photos(app, Some(ids), folder).map(|n| json!({"moved": n}))- }- // the catalog found: no file dialog; none: File ▸ Import Lightroom Catalog… asks for it- Dialog::LightroomCatalog { catalog, .. } => {- app.run("file.importLightroom", catalog.as_ref().map_or_else(|| json!({}), |c| json!({"path": c})))- }- d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::confirm(app, d),- Dialog::SaveEffect { name, group, fields, amount, brush } => {- crate::panels::mask_effects::save_confirm(app, name, group, fields, *amount, *brush)- }- Dialog::DeleteEffects { names } => app.run("mask.deleteEffect", json!({"names": names})),- Dialog::RemoveFolder { path, disk, .. } => app.run("library.removeFolder", json!({"path": path, "disk": disk})),- d @ Dialog::SynchronizeFolder { .. } => crate::sync::confirm(app, d),- Dialog::About | Dialog::Shortcuts | Dialog::Settings { .. } | Dialog::ManageEffects { .. } | Dialog::ViewOptions => {- Ok(serde_json::Value::Null)- }- }-}--/// Open a one-field dialog that runs `command` with `params` + `{key: typed value}`.-pub fn prompt(app: &mut LightcraftApp, title: &str, hint: &str, value: &str, command: &str, params: serde_json::Value, key: &str) {- app.ui.dialog =- Some(Dialog::TextPrompt { title: title.into(), hint: hint.into(), value: value.into(), command: command.into(), params, key: key.into() });-}--/// The Export dialog's choices as `app.export` params (without the folder).-fn export_dialog_params(- opts: &lightcraft_engine::export::ExportOptions,- full_size: bool,- resize: &lightcraft_engine::export::Resize,- limit_kb: u32,-) -> serde_json::Value {- let o = lightcraft_engine::export::ExportOptions {- resize: (!full_size).then_some(*resize),- limit_kb: (limit_kb > 0).then_some(limit_kb),- ..opts.clone()- };- o.to_json()-}--// ------------------------------------------------------------------------------------------ dialog widgets--/// Two columns of settings-group checkboxes (Copy Settings, Create Preset) plus All / None.-fn group_checklist(ui: &mut egui::Ui, tag: &str, groups: &mut Vec<String>) {- let key_of = |g: &SettingsGroup| serde_json::to_value(g).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();- ui.columns(2, |cols| {- for (i, g) in SettingsGroup::ALL.iter().enumerate() {- let key = key_of(g);- let mut on = groups.contains(&key);- let r = cols[i % 2].checkbox(&mut on, crate::i18n::tr(g.label()));- crate::widgets::register_response(format!("{tag}:{key}"), r.rect, &r);- if r.changed() {- if on {- groups.push(key);- } else {- groups.retain(|x| *x != key);- }- }- }- });- ui.horizontal(|ui| {- let all = ui.small_button(crate::i18n::tr("All"));- crate::widgets::register(ui, format!("{tag}:all"), all.rect);- if all.clicked() {- *groups = SettingsGroup::ALL.iter().map(key_of).collect();- }- let none = ui.small_button(crate::i18n::tr("None"));- crate::widgets::register(ui, format!("{tag}:none"), none.rect);- if none.clicked() {- groups.clear();- }- });-}--/// Width of the label column in dialogs.-const LABEL_W: f32 = 78.0;--const fn spec(id: &'static str, label: &'static str, min: f64, max: f64, default: f64, step: f64) -> ControlSpec {- ControlSpec { id, label, section: Section::Light, min, max, default, step, decimals: 0, track: Track::Plain }-}-const QUALITY: ControlSpec = spec("export.quality", "Quality", 1.0, 100.0, 90.0, 1.0);-const LIMIT_KB: ControlSpec = spec("export.limitKb", "Limit file size (KB, 0 = off)", 0.0, 20_000.0, 0.0, 10.0);-const SIZE_PX: ControlSpec = spec("export.sizePx", "Pixels", 16.0, 20_000.0, 2048.0, 16.0);-const SIZE_W: ControlSpec = spec("export.sizeW", "Width (px)", 16.0, 20_000.0, 2048.0, 16.0);-const SIZE_H: ControlSpec = spec("export.sizeH", "Height (px)", 16.0, 20_000.0, 2048.0, 16.0);-const SIZE_MP: ControlSpec = ControlSpec { decimals: 1, ..spec("export.sizeMp", "Megapixels", 0.1, 100.0, 12.0, 0.1) };-const SIZE_PCT: ControlSpec = spec("export.sizePercent", "Percent", 1.0, 400.0, 50.0, 1.0);-const START_NUMBER: ControlSpec = spec("export.startNumber", "Start number", 1.0, 9999.0, 1.0, 1.0);-const PPI: ControlSpec = spec("export.ppi", "Resolution (ppi)", 1.0, 1200.0, 240.0, 1.0);--/// Image Sizing: full size, or a resize mode and its value(s), don't enlarge, ppi.-fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::export::Resize, ppi: &mut u16) {- use lightcraft_engine::export::ResizeMode as R;- const MODES: [(R, &str); 8] = [- (R::LongEdge, "Long Edge"),- (R::ShortEdge, "Short Edge"),- (R::Width, "Width"),- (R::Height, "Height"),- (R::WidthHeight, "Width & Height"),- (R::Dimensions, "Dimensions"),- (R::Megapixels, "Megapixels"),- (R::Percent, "Percentage"),- ];- let r_full = ui.checkbox(full, crate::i18n::tr("Full size"));- crate::widgets::register(ui, "check:exportFullSize", r_full.rect);- if !*full {- field(ui, "Resize to", |ui| {- let cur = MODES.iter().find(|m| m.0 == r.mode).map_or("Long Edge", |m| m.1);- let before = r.mode;- let c = crate::widgets::combo_box("exportResizeMode").width(150.0).selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| {- for (m, l) in MODES {- ui.selectable_value(&mut r.mode, m, crate::i18n::tr(l));- }- });- crate::widgets::name_combo(&c.response, crate::i18n::tr("Resize"));- crate::widgets::register(ui, "combo:exportResizeMode", c.response.rect);- if r.mode != before {- // a sensible value for the new unit- r.value = match r.mode {- R::Megapixels => 12.0,- R::Percent => 50.0,- _ if matches!(before, R::Megapixels | R::Percent) => 2048.0,- _ => r.value,- };- if matches!(r.mode, R::Dimensions | R::WidthHeight) && r.height == 0 {- r.height = r.value as u32;- }- }- });- let mut v = r.value as f64;- let spec = match r.mode {- R::Megapixels => &SIZE_MP,- R::Percent => &SIZE_PCT,- R::Dimensions | R::WidthHeight => &SIZE_W,- _ => &SIZE_PX,- };- if num(ui, spec, &mut v) {- r.value = v as f32;- }- if matches!(r.mode, R::Dimensions | R::WidthHeight) {- let mut h = r.height as f64;- if num(ui, &SIZE_H, &mut h) {- r.height = h as u32;- }- }- let c = ui.checkbox(&mut r.dont_enlarge, crate::i18n::tr("Don't enlarge"));- crate::widgets::register(ui, "check:exportDontEnlarge", c.rect);- }- let mut p = *ppi as f64;- if num(ui, &PPI, &mut p) {- *ppi = p as u16;- }-}-/// All nine positions supported by both the text and graphic watermark renderer.-/// Keep them in grid order so bottom-centre and edge-centre anchors are available in Export.-const WM_POSITIONS: [(lightcraft_engine::export::Anchor, &str); 9] = {- use lightcraft_engine::export::Anchor::*;- [(TopLeft, "↖"), (Top, "↑"), (TopRight, "↗"), (Left, "←"), (Center, "•"), (Right, "→"), (BottomLeft, "↙"), (Bottom, "↓"), (BottomRight, "↘")]-};--const WM_IMAGE_WIDTH: ControlSpec = spec("export.watermarkImageWidth", "Width (% of photo)", 2.0, 100.0, 20.0, 1.0);-const WM_SIZE: ControlSpec = spec("export.watermarkSize", "Size (% of short edge)", 1.0, 15.0, 3.5, 0.5);-const WM_OPACITY: ControlSpec = spec("export.watermarkOpacity", "Opacity (%)", 5.0, 100.0, 70.0, 1.0);-const WM_INSET_X: ControlSpec =- ControlSpec { decimals: 1, ..spec("export.watermarkInsetX", "Horizontal inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) };-const WM_INSET_Y: ControlSpec =- ControlSpec { decimals: 1, ..spec("export.watermarkInsetY", "Vertical inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) };--/// A themed slider row editing `v`; true when it changed.-fn num(ui: &mut egui::Ui, spec: &ControlSpec, v: &mut f64) -> bool {- match crate::widgets::slider(ui, spec, *v, true, None).value {- Some(n) => {- *v = n;- true- }- None => false,- }-}--/// A labelled row (fixed label column).-/// View ▸ Export Slideshow…: what to write (PDF, JPEG sequence, video) and how big; where comes-/// after (a save dialog).-fn slideshow_export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, settings: &mut lightcraft_engine::slideshow_export::ExportSettings) {- use lightcraft_engine::slideshow_export::{ExportSettings, Format};- let t = Tokens::get(ui.ctx());- let photos = app.session.visible_cloned().len();- let slide = app.session.slideshow.slide_duration;- let (intro, ending) = app.session.slide_titles.durations(slide);- let titles = usize::from(intro.is_some()) + usize::from(ending.is_some());- let seconds = photos as f64 * slide + intro.unwrap_or(0.0) + ending.unwrap_or(0.0);- let summary = crate::i18n::tr_format!(- "{n} photos in view · {slides} slides · {time}",- n = photos,- slides = photos + titles,- time = format!("{}:{:02}", (seconds / 60.0).floor() as u64, (seconds % 60.0).round() as u64)- );- ui.label(egui::RichText::new(summary).color(t.text_dim));- let before = settings.format;- choices(ui, "Format", "slideshowExportFormat", &[(Format::Pdf, "PDF"), (Format::Jpeg, "JPEG"), (Format::Video, "Video")], &mut settings.format);- if settings.format != before {- *settings = ExportSettings { full_screen: settings.full_screen, ..ExportSettings::for_format(settings.format) };- }- match settings.format {- Format::Video => {- choices(ui, "Size", "slideshowExportSize", &[(720, "720p"), (1080, "1080p")], &mut settings.size);- choices(ui, "Frame rate", "slideshowExportFps", &[(24, "24 fps"), (30, "30 fps")], &mut settings.fps);- let mut webm = settings.container == "webm";- choices(ui, "Container", "slideshowExportContainer", &[(false, "MP4"), (true, "WebM")], &mut webm);- settings.container = if webm { "webm".into() } else { "mp4".into() };- }- _ => {- choices(ui, "Size", "slideshowExportSize", &[(1024, "1024 px"), (1920, "1920 px"), (3840, "3840 px")], &mut settings.size);- }- }- field(ui, "Quality", |ui| {- let r = ui.add(egui::Slider::new(&mut settings.quality, 1..=100));- crate::widgets::register(ui, "slider:slideshowExportQuality", r.rect);- });- let note = match settings.format {- Format::Pdf => {- let r = ui.checkbox(&mut settings.full_screen, crate::i18n::tr("Automatically show full screen"));- crate::widgets::register(ui, "check:slideshowExportFullScreen", r.rect);- "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode."- }- Format::Jpeg => "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.",- Format::Video => "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.",- };- ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim));- ui.label(- egui::RichText::new(crate::i18n::tr("Slides use the slideshow's layout, overlays and intro and ending screens, in view order."))- .color(t.text_dim),- );-}--fn field<R>(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R {- let t = Tokens::get(ui.ctx());- ui.horizontal(|ui| {- ui.allocate_ui_with_layout(egui::vec2(LABEL_W, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {- ui.set_min_width(LABEL_W);- ui.label(egui::RichText::new(crate::i18n::tr(label)).color(t.text_label));- });- add(ui)- })- .inner-}--/// The rest of a [`field`] row, laid out right to left: `add` places its trailing button(s) first,-/// then a text field taking exactly the width that's left. (Subtracting a guessed button width-/// instead made the auto-sized dialog grow every frame when the real button was wider, #8.)-fn trailing_button_row(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) {- let h = ui.spacing().interact_size.y.max(24.0);- ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), h), egui::Layout::right_to_left(egui::Align::Center), add);-}--/// A labelled row of mutually exclusive choice buttons (ids `button:{id}-{index}`).-fn choices<V: PartialEq + Copy>(ui: &mut egui::Ui, label: &str, id: &str, options: &[(V, &str)], value: &mut V) {- field(ui, label, |ui| {- ui.spacing_mut().item_spacing.x = 4.0;- for (i, (v, l)) in options.iter().enumerate() {- if crate::widgets::text_button(ui, &format!("{id}-{i}"), l, *value == *v).clicked() {- *value = *v;- }- }- });-}--/// Dialogs that Return confirms with nothing focused (those with text fields confirm from the-/// field: `dialog_field`).-fn return_confirms(dlg: &Dialog) -> bool {- matches!(dlg, Dialog::CopySettings { .. } | Dialog::PasteSettings { .. })-}--struct PersonRenamePlan {- faces: usize,- needs_merge: bool,- /// Why Rename stays disabled. `None` when the typed name can be applied.- block: Option<&'static str>,-}--/// What renaming `from` to `to` would do, using the same rules as `faces.renamePerson`.-fn person_rename_plan(cat: &lightcraft_catalog::Catalog, from: &str, to: &str) -> PersonRenamePlan {- let to_trim = to.trim();- if to_trim.is_empty() {- return PersonRenamePlan { faces: 0, needs_merge: false, block: Some("Type a name") };- }- if to_trim.chars().count() > 200 || to_trim.chars().any(char::is_control) {- return PersonRenamePlan { faces: 0, needs_merge: false, block: Some("A name is at most 200 characters, without control characters") };- }- let from_key = from.trim().to_lowercase();- let to_key = to_trim.to_lowercase();- let mut matched = 0usize;- let mut faces = 0usize;- let mut needs_merge = false;- if !from_key.is_empty() {- for photo in cat.photos().filter(|p| p.in_library()) {- for region in photo.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) {- let Some(name) = region.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue };- let key = name.to_lowercase();- if key == from_key {- matched += 1;- if region.name.as_deref() != Some(to_trim) {- faces += 1;- }- } else if key == to_key {- needs_merge = true;- }- }- }- }- let block = if matched == 0 {- Some("No person by that name")- } else if faces == 0 {- Some("That is already their name")- } else {- None- };- // a case-only change is the same person, not a merge- PersonRenamePlan { faces, needs_merge: needs_merge && from_key != to_key, block }-}--/// A dialog's one text field: it takes the focus when the dialog opens, and opens with its text-/// selected, so typing replaces it. It takes the focus back only while nothing else has it: taking-/// it back every frame would keep Tab from ever reaching the dialog's buttons and check boxes.-/// True when Return confirms the dialog; Esc cancels the dialog (`show`).-fn dialog_field(ui: &mut egui::Ui, widget: &str, text: &mut String, hint: &str) -> bool {- let r = crate::text_field::TextField::singleline(widget, text).hint(crate::i18n::tr(hint)).width(f32::INFINITY).select_on_focus(true).show(ui);- // (and takes it back when nothing has it: after a click on the dialog's background or a check box,- // or when Return gave it up on a refusal; a control Tab reached keeps it). A disabled dialog (a- // prompt or the blocking library window owns input) must not request the focus at all: egui's- // text edit would otherwise keep editing the draft from host text behind that window.- if ui.is_enabled() && (just_opened(ui, widget) || (!r.editing && r.ending.is_none() && ui.memory(|m| m.focused().is_none()))) {- r.response.request_focus();- }- r.ending == Some(crate::text_field::Ending::Return)-}--/// The dialog part `key` is drawn this frame but wasn't the frame before: the dialog has just-/// opened (to give its first field the focus once).-fn just_opened(ui: &egui::Ui, key: &str) -> bool {- let id = egui::Id::unique(("dialog-shown", key));- let pass = ui.ctx().cumulative_pass_nr();- let last: Option<u64> = ui.data_mut(|d| d.get_temp(id));- ui.data_mut(|d| d.insert_temp(id, pass));- last.and_then(|l| l.checked_add(1)) != Some(pass)-}--#[cfg(test)]-mod watermark_position_tests {- use super::WM_POSITIONS;- use lightcraft_engine::export::Anchor;-- #[test]- fn export_dialog_offers_every_rendered_anchor_exactly_once() {- let anchors = [- Anchor::TopLeft,- Anchor::Top,- Anchor::TopRight,- Anchor::Left,- Anchor::Center,- Anchor::Right,- Anchor::BottomLeft,- Anchor::Bottom,- Anchor::BottomRight,- ];- assert_eq!(WM_POSITIONS.len(), anchors.len());- for anchor in anchors {- assert_eq!(WM_POSITIONS.iter().filter(|(position, _)| *position == anchor).count(), 1);- }- }-}--/// How a dialog's confirm button looks: [`ConfirmStyle::Primary`] (the accent's fill) when it-/// makes or brings in something, plain when it deletes or removes (never the eye-catching-/// default) or when the dialog only shows something (its Close).-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum ConfirmStyle {- Primary,- Plain,-}--pub fn confirm_style(dlg: &Dialog) -> ConfirmStyle {- match dlg {- Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } | Dialog::RemoveFolder { .. } => {- ConfirmStyle::Plain- }- _ if only_shows(dlg) => ConfirmStyle::Plain,- _ => ConfirmStyle::Primary,- }-}--/// A dialog that only shows something: one Close, nothing to confirm or cancel. (Synchronize-/// Folder is one when its folder turned out up to date.)-fn only_shows(dlg: &Dialog) -> bool {- matches!(- dlg,- Dialog::About- | Dialog::Shortcuts- | Dialog::Settings { .. }- | Dialog::SystemInfo { .. }- | Dialog::AllMetadata { .. }- | Dialog::WhatsNew- | Dialog::ManageEffects { .. }- | Dialog::ViewOptions- ) || matches!(dlg, Dialog::SynchronizeFolder { counts: Some(c), .. } if c.up_to_date())-}--#[cfg(test)]-mod gap_tests {- use super::{fmt_gap, parse_gap};-- #[test]- fn gap_text_reads_back_what_it_shows() {- for v in [0.0, 1.0, 12.0, 59.0, 60.0, 90.0, 600.0, 3599.0, 3600.0, 3601.0, 3661.0, 3900.0, 7325.0, 86340.0, 86399.0] {- assert_eq!(parse_gap(&fmt_gap(v)), Some(v), "{}", fmt_gap(v));- }- assert_eq!(parse_gap("1 day"), Some(86400.0));- assert_eq!(parse_gap("45"), Some(45.0));- assert_eq!(parse_gap(" 45s "), Some(45.0));- assert_eq!(parse_gap("2min 5s"), Some(125.0));- for bad in ["", "abc", "5 parsecs", "NaN", "1 min x"] {- assert_eq!(parse_gap(bad), None, "{bad:?}");- }- // a day reads back in the UI language too ("1 Tag")- crate::i18n::set_language(crate::i18n::Locale::De);- let shown = fmt_gap(86400.0);- let back = parse_gap(&shown);- crate::i18n::set_language(crate::i18n::Locale::En);- assert_eq!((shown.as_str(), back), ("1 Tag", Some(86400.0)));- }-- #[test]- fn gaps_past_the_slider_read_back_too() {- // the Assisted Culling slider drags to 10 min; its value field takes up to a day- for (v, text) in [(1800.0, "30 min"), (5400.0, "1 h 30 min"), (3601.0, "1 h 0 min 1 s"), (86400.0, "1 day")] {- assert_eq!(fmt_gap(v), text);- assert_eq!(parse_gap(text), Some(v), "{text}");- }- assert_eq!(parse_gap("1800"), Some(1800.0));- assert_eq!(parse_gap("0"), Some(0.0));- }-}--#[cfg(test)]-mod cull_dialog_tests {- use std::time::Duration;-- use serde_json::json;-- use super::{clamp_cull_burst, cull_params};- use crate::headless::Headless;- use crate::state::Dialog;- use crate::{LightcraftApp, Services};-- const T: Duration = Duration::from_secs(20);-- #[test]- fn typed_values_are_kept_within_what_photo_analyze_accepts() {- for (gap, sim) in [(0.0, 0.0), (1800.0, 1.0), (86400.0, 0.5), (0.5, 0.995)] {- let (mut g, mut s) = (gap, sim);- clamp_cull_burst(&mut g, &mut s);- assert_eq!((g, s), (gap, sim), "in range: kept as typed");- }- for ((gap, sim), want) in [((-5.0, -0.1), (0.0, 0.0)), ((90000.0, 1.5), (86400.0, 1.0)), ((f32::NAN, f32::INFINITY), (10.0, 0.93))] {- let (mut g, mut s) = (gap, sim);- clamp_cull_burst(&mut g, &mut s);- assert_eq!((g, s), want);- }- assert_eq!(cull_params(0.0, true, 1800.0, 1.0), json!({"pickBest": true, "burstGap": 1800.0, "similarity": 1.0}));- assert_eq!(cull_params(20.0, false, 0.0, 0.7)["rejectBelow"], 20.0);- }-- /// Click the value field right of a slider registered as `id`, type `text`, Enter.- fn type_value(h: &mut Headless, id: &str, text: &str) {- let r = h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("{id} not on screen"));- let spacing = h.view.ctx.global_style().spacing.clone();- let x = r.left() + spacing.slider_width + spacing.item_spacing.x + 6.0;- assert_eq!(h.request("ui.click", json!({"x": x, "y": r.center().y}), T)["ok"], true);- h.step();- for key in ["a", "Backspace"] {- assert_eq!(h.request("ui.key", json!({"key": key, "cmd": key == "a"}), T)["ok"], true);- }- assert_eq!(h.request("ui.text", json!({"text": text}), T)["ok"], true);- assert_eq!(h.request("ui.key", json!({"key": "Enter"}), T)["ok"], true);- h.step();- h.step();- }-- fn burst(h: &Headless) -> (f32, f32) {- match &h.app.ui.dialog {- Some(Dialog::Cull { burst_gap, similarity, .. }) => (*burst_gap, *similarity),- d => panic!("{d:?}"),- }- }-- #[test]- fn the_culling_value_fields_take_values_past_the_sliders() {- let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());- let mut h = Headless::new(app, [1400.0, 1000.0], 1.0);- h.step();- h.app.run("dialog.cull", json!({})).unwrap();- for _ in 0..4 {- h.step();- }- assert_eq!(burst(&h), (10.0, 0.93));- // half an hour and "only identical shots": past the sliders' 10 min and 0.99- type_value(&mut h, "field:cullGap", "30 min");- type_value(&mut h, "field:cullSimilar", "1.0");- assert_eq!(burst(&h), (1800.0, 1.0));- // a day is as far as photo.analyze goes; more is held there- type_value(&mut h, "field:cullGap", "2 days");- assert_eq!(burst(&h).0, 86400.0);- type_value(&mut h, "field:cullGap", "0");- assert_eq!(burst(&h), (0.0, 1.0));- type_value(&mut h, "field:cullGap", "1800");- assert_eq!(burst(&h).0, 1800.0);- // a similarity between the slider's hundredths is kept to the thousandth- type_value(&mut h, "field:cullSimilar", "0.995");- assert_eq!(burst(&h).1, 0.995);- type_value(&mut h, "field:cullSimilar", "0.9951");- assert_eq!(burst(&h).1, 0.995);- type_value(&mut h, "field:cullSimilar", "1.0");- assert_eq!(burst(&h).1, 1.0);- // OK hands them to photo.analyze as typed (it refuses values out of its range)- let r = h.request("ui.dialog.confirm", json!({}), T);- assert_eq!(r["ok"], true, "{r}");- assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog);- assert_eq!(h.app.ui.cull_burst, Some((1800.0, 1.0)));- // and the next opening starts from them, not from the sliders' range- h.app.run("dialog.cull", json!({})).unwrap();- h.step();- h.step();- assert_eq!(burst(&h), (1800.0, 1.0));- }-}diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rsnew file mode 100644index 000000000..196018e55--- /dev/null+++ b/crates/ui-egui/src/dialogs/confirm.rs@@ -0,0 +1,235 @@+use super::cull::cull_params;+use super::export::export_dialog_params;+use super::*;++/// Runs a command that creates an album and asks the Albums tree to open the folders down to it.+fn created_in(app: &mut LightcraftApp, command: &str, params: serde_json::Value) -> Result<serde_json::Value, String> {+ let r = app.run(command, params)?;+ app.ui.reveal_album = r.get("id").and_then(serde_json::Value::as_u64);+ Ok(r)+}++/// The albums an Album rule in smart album `editing` picks from, in the sidebar's order: the album+/// itself and any smart album that tests it (testing it back would loop) are blocked, with why.+pub(crate) fn album_entries(cat: &lightcraft_catalog::Catalog, editing: Option<u64>) -> Vec<crate::album_picker::AlbumEntry> {+ let editing = editing.map(lightcraft_catalog::AlbumId);+ crate::album_picker::entries_from(cat, |a| match editing {+ Some(e) if a.id == e => Some(crate::i18n::tr("This is the album you're editing").to_string()),+ Some(e) if cat.album_reaches(a.id, e) => Some(crate::i18n::tr("It tests this album, so testing it back would loop").to_string()),+ _ => None,+ })+}++pub fn confirm_dialog(app: &mut LightcraftApp, dlg: &Dialog) -> Result<serde_json::Value, String> {+ match dlg {+ Dialog::LightroomResult { first, .. } => {+ if let Some(first) = first {+ app.run("library.source", json!({"kind": "all"}))?;+ let mut filter = serde_json::to_value(lightcraft_catalog::Filter::default()).map_err(|e| e.to_string())?;+ // The filter command merges a patch; these defaults are omitted by serde.+ filter["only"] = json!([]);+ filter["labels"] = json!([]);+ filter["ruleSet"] = serde_json::Value::Null;+ app.run("library.filter", filter)?;+ app.run("library.select", json!({"ids": [first]}))?;+ app.ui.view = crate::state::ViewMode::PhotoGrid;+ }+ Ok(serde_json::Value::Null)+ }+ Dialog::SamModel { then, .. } => {+ if app.session.segmenter.installed() {+ // installed: start what the user was doing+ if let Some((kind, op)) = then {+ crate::panels::masking::begin_ai(app, kind, op)?;+ }+ return Ok(serde_json::Value::Null);+ }+ let r = app.run("segment.model.download", json!({"acknowledged": true}));+ if r.is_ok() {+ app.ui.sam_downloading = true;+ }+ r+ }+ Dialog::NewAlbum { name, folder, parent, include_selected } => {+ created_in(app, "album.create", json!({"name": name, "folder": folder, "addSelected": !folder && *include_selected, "parent": parent}))+ }+ Dialog::RenameAlbum { id, name } => app.run("album.rename", json!({"id": id, "name": name})),+ Dialog::TextPrompt { value, command, params, key, .. } => {+ let mut p = params.clone();+ p[key.as_str()] = json!(value.trim());+ app.run(command, p)+ }+ Dialog::CaptureTime { mode, time, days, hours, minutes, zone } => app.run(+ "photo.setCaptureTime",+ match mode.as_str() {+ "set" => json!({"time": time}),+ "shift" => json!({"shift": *days as i64 * 86_400 + *hours as i64 * 3600 + *minutes as i64 * 60}),+ _ => json!({"hours": zone}),+ },+ ),+ Dialog::LabelNames { names, save_as } => {+ let mut m = serde_json::Map::new();+ for (l, n) in lightcraft_catalog::ColorLabel::ALL.iter().zip(names) {+ m.insert(format!("{l:?}").to_lowercase(), if n.trim().is_empty() { serde_json::Value::Null } else { json!(n.trim()) });+ }+ let r = app.run("label.setNames", json!({"names": m}));+ if r.is_ok() && !save_as.trim().is_empty() {+ return app.run("label.saveSet", json!({"name": save_as.trim()}));+ }+ r+ }+ Dialog::Rename { template, start } => app.run("photo.rename", json!({"template": template, "start": start})),+ Dialog::RenameKeyword { from, to } => app.run("keyword.rename", json!({"from": from, "to": to})),+ Dialog::RenamePerson { from, to, merge } => app.run("faces.renamePerson", json!({"from": from, "to": to.trim(), "merge": merge})),+ Dialog::KeywordTag {+ editing,+ name,+ parent,+ inside,+ synonyms,+ include_on_export,+ export_containing,+ export_synonyms,+ person,+ add_to_selected,+ reveal,+ } => {+ let mut params = json!({+ "synonyms": synonyms.split(',').map(str::trim).filter(|s| !s.is_empty()).collect::<Vec<_>>(),+ "includeOnExport": include_on_export,+ "exportContaining": export_containing,+ "exportSynonyms": export_synonyms,+ "person": person,+ });+ match editing {+ Some(keyword) => {+ params["keyword"] = json!(keyword);+ params["name"] = json!(name);+ let r = app.run("keyword.edit", params);+ if r.is_ok() {+ let to = match keyword.rsplit_once('|') {+ Some((parent, _)) => format!("{parent}|{}", name.trim()),+ None => name.trim().to_string(),+ };+ crate::panels::keyword_list::follow(app, keyword, &to);+ }+ r+ }+ None => {+ params["name"] = json!(name);+ params["parent"] = if *inside { json!(parent) } else { serde_json::Value::Null };+ params["addToSelected"] = json!(add_to_selected);+ let r = app.run("keyword.create", params);+ if *reveal && let Ok(made) = &r {+ app.ui.reveal_keyword = made["keyword"].as_str().map(str::to_string);+ }+ r+ }+ }+ }+ Dialog::DeleteKeyword { keyword, .. } => app.run("keyword.delete", json!({"keyword": keyword})),+ Dialog::KeywordSet { replaces, name, slots, as_new } => {+ use lightcraft_catalog::keywords::same;+ let name = name.trim();+ if name.is_empty() {+ return Err(crate::i18n::tr("A keyword set needs a name").to_string());+ }+ if same(name, lightcraft_engine::cmd::keywords::RECENT) {+ return Err(crate::i18n::tr("Recent Keywords is built in: choose another name").to_string());+ }+ // the set it renames: none when saving as new, or when it was deleted meanwhile (then it is+ // saved anew rather than refused)+ let sets = &app.session.keyword_sets;+ let renames = replaces.as_deref().filter(|_| !as_new).filter(|old| sets.iter().any(|x| same(&x.name, old)));+ if sets.iter().any(|x| same(&x.name, name) && !renames.is_some_and(|old| same(&x.name, old))) {+ return Err(crate::i18n::tr_format!("There is a keyword set “{name}” already", name = name));+ }+ let mut params = json!({"name": name, "keywords": slots});+ match renames {+ Some(old) => params["replace"] = json!(old),+ None => params["new"] = json!(true),+ }+ app.run("keyword.saveSet", params)+ }+ Dialog::MoveKeyword { keyword, parent } => {+ let r = app.run("keyword.move", json!({"keyword": keyword, "parent": parent, "merge": true}));+ if r.is_ok() {+ let leaf = keyword.rsplit('|').next().unwrap_or(keyword);+ let to = parent.as_deref().map_or_else(|| leaf.to_string(), |p| format!("{p}|{leaf}"));+ crate::panels::keyword_list::follow(app, keyword, &to);+ }+ r+ }+ Dialog::MergeKeywords { from, into } => app.run("keyword.merge", json!({"from": from, "into": into})),+ Dialog::AutoStack { gap } => app.run("stack.auto", json!({"gap": gap})),+ Dialog::DenoiseModel { info, accepted } => crate::panels::denoise::install(app, info, *accepted),+ Dialog::FaceModel { path, info, accepted } => crate::panels::faces::install(app, path, info, *accepted),+ Dialog::AllMetadata { .. } | Dialog::SystemInfo { .. } | Dialog::WhatsNew => Ok(serde_json::Value::Null),+ Dialog::Cull { reject_below, pick_best, burst_gap, similarity } => {+ app.ui.cull_burst = Some((*burst_gap, *similarity));+ app.run("photo.analyze", cull_params(*reject_below, *pick_best, *burst_gap, *similarity))+ }+ Dialog::SmartRules { id, name, rules, parent } => {+ // refused before anything changes (not even the name)+ if let Some(problem) = rules.check_for(&app.session.catalog, id.map(lightcraft_catalog::AlbumId)).first() {+ return Err(problem.to_string());+ }+ let name = if name.trim().is_empty() { "Smart Album".to_string() } else { name.trim().to_string() };+ match id {+ // the name and the rules together: one undo step, both or neither+ Some(id) => app.run("album.setRules", json!({"id": id, "name": name, "replace": true, "rules": {"ruleSet": rules}})),+ None => created_in(app, "album.createSmart", json!({"name": name, "rules": {"ruleSet": rules}, "parent": parent})),+ }+ }+ Dialog::NewSmartAlbum { name, parent } => {+ created_in(app, "album.createSmart", json!({"name": if name.trim().is_empty() { "Smart Album" } else { name }, "parent": parent}))+ }+ Dialog::CreatePreset { name, group, groups } => app.run(+ "preset.create",+ json!({+ "name": if name.trim().is_empty() { "My Preset" } else { name },+ "group": if group.trim().is_empty() { "User Presets" } else { group },+ "groups": groups,+ }),+ ),+ Dialog::ContactSheet { options } => app.run("app.contactSheet", json!(options)),+ Dialog::SlideshowExport { settings } => app.run("app.slideshowExport", json!(settings)),+ Dialog::Print => app.run("app.print", json!({})),+ Dialog::CopySettings { groups } => app.run("develop.copy", json!({"groups": groups})),+ Dialog::PasteSettings { groups } => app.run("develop.paste", json!({"groups": groups})),+ Dialog::Export { opts, full_size, resize, limit_kb, dir, .. } => {+ let mut p = export_dialog_params(opts, *full_size, resize, *limit_kb);+ p["dir"] = json!(dir);+ p["background"] = json!(true);+ app.run("app.export", p)+ }+ Dialog::Merge { opts } => crate::merge::start_final(app, opts),+ Dialog::Import { opts } => crate::import::start(app, opts),+ Dialog::ConfirmDelete { .. } => app.run("photo.delete", json!({})),+ Dialog::MovePhotos { ids, folder, dont_ask, library, .. } => {+ // another library opened meanwhile (from the menu bar, an agent): these numbers are+ // other photos there+ if *library != app.session.library_generation() {+ return Err(crate::i18n::tr("Another library was opened since the photos were dropped: nothing was moved").to_string());+ }+ if *dont_ask {+ app.ui.settings.ask_before_move = false;+ }+ crate::panels::left::move_photos(app, Some(ids), folder).map(|n| json!({"moved": n}))+ }+ // the catalog found: no file dialog; none: File ▸ Import Lightroom Catalog… asks for it+ Dialog::LightroomCatalog { catalog, .. } => {+ app.run("file.importLightroom", catalog.as_ref().map_or_else(|| json!({}), |c| json!({"path": c})))+ }+ d @ Dialog::LightroomDestination { .. } => crate::lightroom_destination::confirm(app, d),+ Dialog::SaveEffect { name, group, fields, amount, brush } => {+ crate::panels::mask_effects::save_confirm(app, name, group, fields, *amount, *brush)+ }+ Dialog::DeleteEffects { names } => app.run("mask.deleteEffect", json!({"names": names})),+ Dialog::RemoveFolder { path, disk, .. } => app.run("library.removeFolder", json!({"path": path, "disk": disk})),+ d @ Dialog::SynchronizeFolder { .. } => crate::sync::confirm(app, d),+ Dialog::About | Dialog::Shortcuts | Dialog::Settings { .. } | Dialog::ManageEffects { .. } | Dialog::ViewOptions => {+ Ok(serde_json::Value::Null)+ }+ }+}diff --git a/crates/ui-egui/src/dialogs/cull.rs b/crates/ui-egui/src/dialogs/cull.rsnew file mode 100644index 000000000..2c3d6497a--- /dev/null+++ b/crates/ui-egui/src/dialogs/cull.rs@@ -0,0 +1,201 @@+use super::*;++/// Apply a dialog's action (also used by `ui.dialog.confirm`).+/// What [`fmt_gap`] writes, read back: `90`, `90 s`, `1 min 30 s`, `2 h 5 min`, `1 day`+/// (units `s`, `min`, `h`, `day`, each optional after a plain number of seconds).+pub fn parse_gap(text: &str) -> Option<f64> {+ // the one translated text `fmt_gap` writes ("1 Tag")+ if text.trim() == crate::i18n::tr("1 day") {+ return Some(86400.0);+ }+ let mut total = 0.0;+ let mut seen = false;+ let mut words = text.split_whitespace().peekable();+ while let Some(word) = words.next() {+ // "90s" as well as "90 s"+ let split = word.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(word.len());+ let (num, unit) = word.split_at(split);+ let n: f64 = num.parse().ok().filter(|n: &f64| n.is_finite())?;+ let unit = if unit.is_empty() {+ match words.peek() {+ Some(u) if u.parse::<f64>().is_err() => words.next().unwrap_or_default(),+ _ => "s",+ }+ } else {+ unit+ };+ let scale = match unit.trim_end_matches('.').to_lowercase().as_str() {+ "s" | "sec" | "secs" | "second" | "seconds" => 1.0,+ "m" | "min" | "mins" | "minute" | "minutes" => 60.0,+ "h" | "hr" | "hrs" | "hour" | "hours" => 3600.0,+ "d" | "day" | "days" => 86400.0,+ _ => return None,+ };+ total += n * scale;+ seen = true;+ }+ seen.then_some(total)+}++/// The longest burst gap `photo.analyze` accepts: a day.+pub const MAX_BURST_GAP: f32 = 86_400.0;++/// Keep what was typed in the Assisted Culling value fields within what `photo.analyze` accepts+/// (a gap of 0 s to a day, a similarity of 0 to 1), not within the sliders' drag range.+pub fn clamp_cull_burst(gap: &mut f32, similarity: &mut f32) {+ *gap = if gap.is_finite() { gap.clamp(0.0, MAX_BURST_GAP) } else { 10.0 };+ *similarity = if similarity.is_finite() { similarity.clamp(0.0, 1.0) } else { 0.93 };+}++/// The `photo.analyze` parameters of the Assisted Culling dialog, its values as they are.+pub fn cull_params(reject_below: f32, pick_best: bool, burst_gap: f32, similarity: f32) -> serde_json::Value {+ let mut p = json!({"pickBest": pick_best, "burstGap": burst_gap, "similarity": similarity});+ if reject_below > 0.0 {+ p["rejectBelow"] = json!(reject_below);+ }+ p+}++/// `90` → `1 min 30 s`.+pub fn fmt_gap(v: f64) -> String {+ let v = v.round() as u64;+ match v {+ 0..60 => format!("{v} s"),+ 60..3600 if v.is_multiple_of(60) => format!("{} min", v / 60),+ 60..3600 => format!("{} min {} s", v / 60, v % 60),+ 3600..86400 if v.is_multiple_of(3600) => format!("{} h", v / 3600),+ 3600..86400 if v.is_multiple_of(60) => format!("{} h {} min", v / 3600, v % 3600 / 60),+ // the seconds too, so editing the text reads back the same gap+ 3600..86400 => format!("{} h {} min {} s", v / 3600, v % 3600 / 60, v % 60),+ _ => crate::i18n::tr("1 day").into(),+ }+}++#[cfg(test)]+mod gap_tests {+ use super::{fmt_gap, parse_gap};++ #[test]+ fn gap_text_reads_back_what_it_shows() {+ for v in [0.0, 1.0, 12.0, 59.0, 60.0, 90.0, 600.0, 3599.0, 3600.0, 3601.0, 3661.0, 3900.0, 7325.0, 86340.0, 86399.0] {+ assert_eq!(parse_gap(&fmt_gap(v)), Some(v), "{}", fmt_gap(v));+ }+ assert_eq!(parse_gap("1 day"), Some(86400.0));+ assert_eq!(parse_gap("45"), Some(45.0));+ assert_eq!(parse_gap(" 45s "), Some(45.0));+ assert_eq!(parse_gap("2min 5s"), Some(125.0));+ for bad in ["", "abc", "5 parsecs", "NaN", "1 min x"] {+ assert_eq!(parse_gap(bad), None, "{bad:?}");+ }+ // a day reads back in the UI language too ("1 Tag")+ crate::i18n::set_language(crate::i18n::Locale::De);+ let shown = fmt_gap(86400.0);+ let back = parse_gap(&shown);+ crate::i18n::set_language(crate::i18n::Locale::En);+ assert_eq!((shown.as_str(), back), ("1 Tag", Some(86400.0)));+ }++ #[test]+ fn gaps_past_the_slider_read_back_too() {+ // the Assisted Culling slider drags to 10 min; its value field takes up to a day+ for (v, text) in [(1800.0, "30 min"), (5400.0, "1 h 30 min"), (3601.0, "1 h 0 min 1 s"), (86400.0, "1 day")] {+ assert_eq!(fmt_gap(v), text);+ assert_eq!(parse_gap(text), Some(v), "{text}");+ }+ assert_eq!(parse_gap("1800"), Some(1800.0));+ assert_eq!(parse_gap("0"), Some(0.0));+ }+}++#[cfg(test)]+mod cull_dialog_tests {+ use std::time::Duration;++ use serde_json::json;++ use super::{clamp_cull_burst, cull_params};+ use crate::headless::Headless;+ use crate::state::Dialog;+ use crate::{LightcraftApp, Services};++ const T: Duration = Duration::from_secs(20);++ #[test]+ fn typed_values_are_kept_within_what_photo_analyze_accepts() {+ for (gap, sim) in [(0.0, 0.0), (1800.0, 1.0), (86400.0, 0.5), (0.5, 0.995)] {+ let (mut g, mut s) = (gap, sim);+ clamp_cull_burst(&mut g, &mut s);+ assert_eq!((g, s), (gap, sim), "in range: kept as typed");+ }+ for ((gap, sim), want) in [((-5.0, -0.1), (0.0, 0.0)), ((90000.0, 1.5), (86400.0, 1.0)), ((f32::NAN, f32::INFINITY), (10.0, 0.93))] {+ let (mut g, mut s) = (gap, sim);+ clamp_cull_burst(&mut g, &mut s);+ assert_eq!((g, s), want);+ }+ assert_eq!(cull_params(0.0, true, 1800.0, 1.0), json!({"pickBest": true, "burstGap": 1800.0, "similarity": 1.0}));+ assert_eq!(cull_params(20.0, false, 0.0, 0.7)["rejectBelow"], 20.0);+ }++ /// Click the value field right of a slider registered as `id`, type `text`, Enter.+ fn type_value(h: &mut Headless, id: &str, text: &str) {+ let r = h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("{id} not on screen"));+ let spacing = h.view.ctx.global_style().spacing.clone();+ let x = r.left() + spacing.slider_width + spacing.item_spacing.x + 6.0;+ assert_eq!(h.request("ui.click", json!({"x": x, "y": r.center().y}), T)["ok"], true);+ h.step();+ for key in ["a", "Backspace"] {+ assert_eq!(h.request("ui.key", json!({"key": key, "cmd": key == "a"}), T)["ok"], true);+ }+ assert_eq!(h.request("ui.text", json!({"text": text}), T)["ok"], true);+ assert_eq!(h.request("ui.key", json!({"key": "Enter"}), T)["ok"], true);+ h.step();+ h.step();+ }++ fn burst(h: &Headless) -> (f32, f32) {+ match &h.app.ui.dialog {+ Some(Dialog::Cull { burst_gap, similarity, .. }) => (*burst_gap, *similarity),+ d => panic!("{d:?}"),+ }+ }++ #[test]+ fn the_culling_value_fields_take_values_past_the_sliders() {+ let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());+ let mut h = Headless::new(app, [1400.0, 1000.0], 1.0);+ h.step();+ h.app.run("dialog.cull", json!({})).unwrap();+ for _ in 0..4 {+ h.step();+ }+ assert_eq!(burst(&h), (10.0, 0.93));+ // half an hour and "only identical shots": past the sliders' 10 min and 0.99+ type_value(&mut h, "field:cullGap", "30 min");+ type_value(&mut h, "field:cullSimilar", "1.0");+ assert_eq!(burst(&h), (1800.0, 1.0));+ // a day is as far as photo.analyze goes; more is held there+ type_value(&mut h, "field:cullGap", "2 days");+ assert_eq!(burst(&h).0, 86400.0);+ type_value(&mut h, "field:cullGap", "0");+ assert_eq!(burst(&h), (0.0, 1.0));+ type_value(&mut h, "field:cullGap", "1800");+ assert_eq!(burst(&h).0, 1800.0);+ // a similarity between the slider's hundredths is kept to the thousandth+ type_value(&mut h, "field:cullSimilar", "0.995");+ assert_eq!(burst(&h).1, 0.995);+ type_value(&mut h, "field:cullSimilar", "0.9951");+ assert_eq!(burst(&h).1, 0.995);+ type_value(&mut h, "field:cullSimilar", "1.0");+ assert_eq!(burst(&h).1, 1.0);+ // OK hands them to photo.analyze as typed (it refuses values out of its range)+ let r = h.request("ui.dialog.confirm", json!({}), T);+ assert_eq!(r["ok"], true, "{r}");+ assert!(h.app.ui.dialog.is_none(), "{:?}", h.app.ui.dialog);+ assert_eq!(h.app.ui.cull_burst, Some((1800.0, 1.0)));+ // and the next opening starts from them, not from the sliders' range+ h.app.run("dialog.cull", json!({})).unwrap();+ h.step();+ h.step();+ assert_eq!(burst(&h), (1800.0, 1.0));+ }+}diff --git a/crates/ui-egui/src/dialogs/export.rs b/crates/ui-egui/src/dialogs/export.rsnew file mode 100644index 000000000..56292605c--- /dev/null+++ b/crates/ui-egui/src/dialogs/export.rs@@ -0,0 +1,302 @@+use super::frame::{field, num};+use super::*;++/// The Export dialog's watermark preview: the first exported photo, as wide as the dialog whatever+/// its shape, with the watermark drawn on it as the file will have it at size `resize` (`None` =+/// full size). On a worker thread, once per photo, catalog change and size step, the cached+/// thumbnail comes first (at once, a little soft) and then a render at the preview's own pixel size+/// replaces it. The watermark is redrawn on a copy only when it, the output size or the picture+/// changes, which is quick at this size, so the preview follows the sliders.+pub(super) fn watermark_preview(+ app: &mut LightcraftApp,+ ui: &mut egui::Ui,+ wm: &lightcraft_engine::export::Watermark,+ resize: Option<lightcraft_engine::export::Resize>,+) {+ use std::hash::{Hash, Hasher};+ // (pictures received so far: 1 the thumbnail, 2 the sharp render; the latest, or why none came)+ type Base = std::sync::Arc<std::sync::Mutex<(u8, Option<Result<lightcraft_raster::Rgba8, String>>)>>;+ type Shown = (u64, u8, lightcraft_engine::export::Watermark, usize, egui::TextureHandle);+ let t = Tokens::get(ui.ctx());+ let Some(&id) = app.session.selected().first() else { return };+ let Some(photo) = app.session.catalog.photo(id).cloned() else { return };+ let (out_w, out_h) = lightcraft_engine::export::output_size(&photo, &lightcraft_engine::export::ExportOptions { resize, ..Default::default() });+ let export_short = out_w.min(out_h);+ // pixels across the dialog, in steps so a scroll bar or a point of layout doesn't re-render+ let step = 128.0;+ let px = ((ui.available_width() * ui.ctx().pixels_per_point() / step).ceil() * step).clamp(step, 2048.0) as usize;+ let mut h = std::collections::hash_map::DefaultHasher::new();+ (id, app.session.catalog.revision, px).hash(&mut h);+ let key = h.finish();+ let ctx = ui.ctx().clone();+ let (base_id, shown_id) = (egui::Id::unique("export-wm-preview-base"), egui::Id::unique("export-wm-preview-shown"));+ let base = match ctx.data(|d| d.get_temp::<(u64, Base)>(base_id)) {+ Some((k, base)) if k == key => base,+ _ => {+ let base: Base = Default::default();+ // the thumbnail, then as wide as the dialog (a tall photo up to three times that high)+ let jobs: Vec<_> = [app.session.thumb_job(id, 512), app.session.render_job(id, px, px * 3, false, true)].into_iter().flatten().collect();+ // the web build has no worker thread: a full render there would hold up the page+ #[cfg(target_arch = "wasm32")]+ let jobs: Vec<_> = jobs.into_iter().take(1).collect();+ if jobs.is_empty() {+ *base.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = (1, Some(Err("no such photo".into())));+ } else {+ let (out, repaint) = (base.clone(), ctx.clone());+ let work = move || {+ for job in jobs {+ // (a panic in the render is its failure: `RenderJob::run`)+ let r = job.run().rendered.map(|r| r.image);+ let mut got = out.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ // a failed sharp render keeps the thumbnail+ if r.is_ok() || !matches!(got.1, Some(Ok(_))) {+ *got = (got.0.saturating_add(1), Some(r));+ repaint.request_repaint();+ }+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ if let Err(e) = std::thread::Builder::new().name("lc-watermark-preview".into()).spawn(work) {+ log::warn!("watermark preview: {e}");+ }+ #[cfg(target_arch = "wasm32")]+ work();+ }+ ctx.data_mut(|d| d.insert_temp(base_id, (key, base.clone())));+ base+ }+ };+ let shown = ctx.data(|d| d.get_temp::<Shown>(shown_id));+ let stage = base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).0;+ let tex = match shown {+ Some((k, g, w, s, tex)) if k == key && g == stage && &w == wm && s == export_short => tex,+ _ => {+ let photo_px = match &base.lock().unwrap_or_else(std::sync::PoisonError::into_inner).1 {+ Some(Ok(img)) => Ok(img.clone()),+ Some(Err(e)) => Err(Some(e.clone())),+ None => Err(None),+ };+ let mut img = match photo_px {+ Ok(img) => img,+ Err(e) => {+ let note = if e.is_some() { "Preview unavailable" } else { "Loading preview…" };+ let r = ui+ .horizontal(|ui| {+ if e.is_none() {+ crate::progress::spinner(ui, 12.0);+ }+ ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim))+ })+ .inner;+ if let Some(e) = e {+ r.on_hover_text(e);+ }+ return;+ }+ };+ lightcraft_engine::export::draw_watermark_preview(&mut img, wm, export_short);+ // shown through the monitor profile like every other preview+ if let Some(d) = app.renderer.display()+ && let Err(e) = d.profile.from_srgb(&mut img)+ {+ log::warn!("display profile: {e}");+ }+ let color = std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], &img.as_bytes()));+ let tex = match shown {+ Some((.., mut tex)) => {+ tex.set(color, egui::TextureOptions::LINEAR);+ tex+ }+ None => ctx.load_texture("export-wm-preview", color, egui::TextureOptions::LINEAR),+ };+ ctx.data_mut(|d| d.insert_temp(shown_id, (key, stage, wm.clone(), export_short, tex.clone())));+ tex+ }+ };+ let size = tex.size_vec2();+ let scale = ui.available_width() / size.x.max(1.0);+ let r = ui.vertical_centered(|ui| ui.add(egui::Image::new((tex.id(), size * scale)))).inner;+ crate::widgets::register(ui, "image:exportWatermarkPreview", r.rect);+}++/// The Export dialog's choices as `app.export` params (without the folder).+pub(super) fn export_dialog_params(+ opts: &lightcraft_engine::export::ExportOptions,+ full_size: bool,+ resize: &lightcraft_engine::export::Resize,+ limit_kb: u32,+) -> serde_json::Value {+ let o = lightcraft_engine::export::ExportOptions {+ resize: (!full_size).then_some(*resize),+ limit_kb: (limit_kb > 0).then_some(limit_kb),+ ..opts.clone()+ };+ o.to_json()+}++// ------------------------------------------------------------------------------------------ dialog widgets++/// Two columns of settings-group checkboxes (Copy Settings, Create Preset) plus All / None.+pub(super) fn group_checklist(ui: &mut egui::Ui, tag: &str, groups: &mut Vec<String>) {+ let key_of = |g: &SettingsGroup| serde_json::to_value(g).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();+ ui.columns(2, |cols| {+ for (i, g) in SettingsGroup::ALL.iter().enumerate() {+ let key = key_of(g);+ let mut on = groups.contains(&key);+ let r = cols[i % 2].checkbox(&mut on, crate::i18n::tr(g.label()));+ crate::widgets::register_response(format!("{tag}:{key}"), r.rect, &r);+ if r.changed() {+ if on {+ groups.push(key);+ } else {+ groups.retain(|x| *x != key);+ }+ }+ }+ });+ ui.horizontal(|ui| {+ let all = ui.small_button(crate::i18n::tr("All"));+ crate::widgets::register(ui, format!("{tag}:all"), all.rect);+ if all.clicked() {+ *groups = SettingsGroup::ALL.iter().map(key_of).collect();+ }+ let none = ui.small_button(crate::i18n::tr("None"));+ crate::widgets::register(ui, format!("{tag}:none"), none.rect);+ if none.clicked() {+ groups.clear();+ }+ });+}++/// Width of the label column in dialogs.+pub(super) const LABEL_W: f32 = 78.0;++const fn spec(id: &'static str, label: &'static str, min: f64, max: f64, default: f64, step: f64) -> ControlSpec {+ ControlSpec { id, label, section: Section::Light, min, max, default, step, decimals: 0, track: Track::Plain }+}++pub(super) const QUALITY: ControlSpec = spec("export.quality", "Quality", 1.0, 100.0, 90.0, 1.0);++pub(super) const LIMIT_KB: ControlSpec = spec("export.limitKb", "Limit file size (KB, 0 = off)", 0.0, 20_000.0, 0.0, 10.0);++const SIZE_PX: ControlSpec = spec("export.sizePx", "Pixels", 16.0, 20_000.0, 2048.0, 16.0);++const SIZE_W: ControlSpec = spec("export.sizeW", "Width (px)", 16.0, 20_000.0, 2048.0, 16.0);++const SIZE_H: ControlSpec = spec("export.sizeH", "Height (px)", 16.0, 20_000.0, 2048.0, 16.0);++const SIZE_MP: ControlSpec = ControlSpec { decimals: 1, ..spec("export.sizeMp", "Megapixels", 0.1, 100.0, 12.0, 0.1) };++const SIZE_PCT: ControlSpec = spec("export.sizePercent", "Percent", 1.0, 400.0, 50.0, 1.0);++pub(super) const START_NUMBER: ControlSpec = spec("export.startNumber", "Start number", 1.0, 9999.0, 1.0, 1.0);++const PPI: ControlSpec = spec("export.ppi", "Resolution (ppi)", 1.0, 1200.0, 240.0, 1.0);++/// Image Sizing: full size, or a resize mode and its value(s), don't enlarge, ppi.+pub(super) fn export_size(ui: &mut egui::Ui, full: &mut bool, r: &mut lightcraft_engine::export::Resize, ppi: &mut u16) {+ use lightcraft_engine::export::ResizeMode as R;+ const MODES: [(R, &str); 8] = [+ (R::LongEdge, "Long Edge"),+ (R::ShortEdge, "Short Edge"),+ (R::Width, "Width"),+ (R::Height, "Height"),+ (R::WidthHeight, "Width & Height"),+ (R::Dimensions, "Dimensions"),+ (R::Megapixels, "Megapixels"),+ (R::Percent, "Percentage"),+ ];+ let r_full = ui.checkbox(full, crate::i18n::tr("Full size"));+ crate::widgets::register(ui, "check:exportFullSize", r_full.rect);+ if !*full {+ field(ui, "Resize to", |ui| {+ let cur = MODES.iter().find(|m| m.0 == r.mode).map_or("Long Edge", |m| m.1);+ let before = r.mode;+ let c = crate::widgets::combo_box("exportResizeMode").width(150.0).selected_text(crate::i18n::tr(cur)).show_ui(ui, |ui| {+ for (m, l) in MODES {+ ui.selectable_value(&mut r.mode, m, crate::i18n::tr(l));+ }+ });+ crate::widgets::name_combo(&c.response, crate::i18n::tr("Resize"));+ crate::widgets::register(ui, "combo:exportResizeMode", c.response.rect);+ if r.mode != before {+ // a sensible value for the new unit+ r.value = match r.mode {+ R::Megapixels => 12.0,+ R::Percent => 50.0,+ _ if matches!(before, R::Megapixels | R::Percent) => 2048.0,+ _ => r.value,+ };+ if matches!(r.mode, R::Dimensions | R::WidthHeight) && r.height == 0 {+ r.height = r.value as u32;+ }+ }+ });+ let mut v = r.value as f64;+ let spec = match r.mode {+ R::Megapixels => &SIZE_MP,+ R::Percent => &SIZE_PCT,+ R::Dimensions | R::WidthHeight => &SIZE_W,+ _ => &SIZE_PX,+ };+ if num(ui, spec, &mut v) {+ r.value = v as f32;+ }+ if matches!(r.mode, R::Dimensions | R::WidthHeight) {+ let mut h = r.height as f64;+ if num(ui, &SIZE_H, &mut h) {+ r.height = h as u32;+ }+ }+ let c = ui.checkbox(&mut r.dont_enlarge, crate::i18n::tr("Don't enlarge"));+ crate::widgets::register(ui, "check:exportDontEnlarge", c.rect);+ }+ let mut p = *ppi as f64;+ if num(ui, &PPI, &mut p) {+ *ppi = p as u16;+ }+}++/// All nine positions supported by both the text and graphic watermark renderer.+/// Keep them in grid order so bottom-centre and edge-centre anchors are available in Export.+pub(super) const WM_POSITIONS: [(lightcraft_engine::export::Anchor, &str); 9] = {+ use lightcraft_engine::export::Anchor::*;+ [(TopLeft, "↖"), (Top, "↑"), (TopRight, "↗"), (Left, "←"), (Center, "•"), (Right, "→"), (BottomLeft, "↙"), (Bottom, "↓"), (BottomRight, "↘")]+};++pub(super) const WM_IMAGE_WIDTH: ControlSpec = spec("export.watermarkImageWidth", "Width (% of photo)", 2.0, 100.0, 20.0, 1.0);++pub(super) const WM_SIZE: ControlSpec = spec("export.watermarkSize", "Size (% of short edge)", 1.0, 15.0, 3.5, 0.5);++pub(super) const WM_OPACITY: ControlSpec = spec("export.watermarkOpacity", "Opacity (%)", 5.0, 100.0, 70.0, 1.0);++pub(super) const WM_INSET_X: ControlSpec =+ ControlSpec { decimals: 1, ..spec("export.watermarkInsetX", "Horizontal inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) };++pub(super) const WM_INSET_Y: ControlSpec =+ ControlSpec { decimals: 1, ..spec("export.watermarkInsetY", "Vertical inset (% of short edge)", 0.0, 40.0, 2.5, 0.5) };++#[cfg(test)]+mod watermark_position_tests {+ use super::WM_POSITIONS;+ use lightcraft_engine::export::Anchor;++ #[test]+ fn export_dialog_offers_every_rendered_anchor_exactly_once() {+ let anchors = [+ Anchor::TopLeft,+ Anchor::Top,+ Anchor::TopRight,+ Anchor::Left,+ Anchor::Center,+ Anchor::Right,+ Anchor::BottomLeft,+ Anchor::Bottom,+ Anchor::BottomRight,+ ];+ assert_eq!(WM_POSITIONS.len(), anchors.len());+ for anchor in anchors {+ assert_eq!(WM_POSITIONS.iter().filter(|(position, _)| *position == anchor).count(), 1);+ }+ }+}diff --git a/crates/ui-egui/src/dialogs/frame.rs b/crates/ui-egui/src/dialogs/frame.rsnew file mode 100644index 000000000..3d8eb4ef8--- /dev/null+++ b/crates/ui-egui/src/dialogs/frame.rs@@ -0,0 +1,214 @@+use super::export::LABEL_W;+use super::*;++/// A click on the dimmed backdrop around the dialog: it closes the dialog like Esc. Pressed and+/// released outside the window, so a slider dragged past its edge doesn't close it; a press while a+/// popup is open (a dropdown, a date picker's calendar) only closes the popup: `popup_was_open` is+/// read before the window is drawn, since drawing it already closes the popup. Only a press made+/// while the dialog is shown counts: in the frame a dialog appears, its input is the click that+/// opened it (a quick click on a slow frame presses and releases in that one frame), so it never+/// closes it. (Read from the raw events: egui forgets the press origin on release.)+pub(super) fn clicked_backdrop(ctx: &egui::Context, window: egui::Rect, popup_was_open: bool) -> bool {+ let press_id = egui::Id::unique("dialog-backdrop-press");+ let frame = ctx.cumulative_frame_nr();+ // the same frame too: a second pass of it gets no input+ let shown = ctx.data(|d| d.get_temp::<u64>(egui::Id::unique(BACKDROP_SHOWN))).is_some_and(|f| f + 1 >= frame);+ if !shown {+ ctx.data_mut(|d| d.remove_temp::<bool>(press_id));+ return false;+ }+ let (press, release, clicked) = ctx.input(|i| {+ let at = |down: bool| {+ i.events.iter().rev().find_map(|e| match e {+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } if *pressed == down => Some(*pos),+ _ => None,+ })+ };+ (at(true), at(false), i.pointer.primary_clicked())+ });+ if let Some(p) = press {+ let outside = !window.contains(p) && !popup_was_open;+ ctx.data_mut(|d| d.insert_temp(press_id, outside));+ }+ let Some(release) = release else { return false };+ let pressed_outside = ctx.data_mut(|d| d.remove_temp::<bool>(press_id)).unwrap_or(false);+ clicked && pressed_outside && !window.contains(release)+}++/// Room kept free above and below a dialog (#781).+pub(super) const DIALOG_SCREEN_MARGIN: f32 = 12.0;++/// A dialog's title bar, frame and button row before the first frame measures them.+pub(super) const DIALOG_CHROME_GUESS: f32 = 100.0;++/// A dialog's options never get less room than this, however short the window.+pub(super) const DIALOG_MIN_BODY: f32 = 80.0;++/// A list that scrolls on its own never gets shorter than this to make its dialog fit.+const DIALOG_MIN_LIST: f32 = 120.0;++fn list_shrink_id() -> egui::Id {+ egui::Id::unique("dialog-list-shrink")+}++fn list_applied_id() -> egui::Id {+ egui::Id::unique("dialog-list-applied")+}++/// The height for a list in a dialog that scrolls on its own (What's New, All Metadata, the+/// shortcuts, smart-album rules): `preferred`, less what the dialog needs to fit the window, so+/// on a short window the list gets shorter rather than scrolling inside a scrolling dialog.+pub fn list_height(ui: &egui::Ui, preferred: f32) -> f32 {+ let shrink = ui.data(|d| d.get_temp::<f32>(list_shrink_id())).unwrap_or(0.0);+ let height = (preferred - shrink).max(preferred.min(DIALOG_MIN_LIST));+ ui.data_mut(|d| *d.get_temp_mut_or_default::<f32>(list_applied_id()) += preferred - height);+ height+}++/// A dialog's options: in a vertical scroll area at most `max_height` tall when `scroll` names+/// the dialog (it shrinks to its content, so a dialog that fits looks as it would without it;+/// each dialog keeps a scroll position of its own), drawn directly otherwise. Returns the height+/// they took when scrolled.+pub(super) fn dialog_body(ui: &mut egui::Ui, scroll: Option<&str>, max_height: f32, body: impl FnOnce(&mut egui::Ui)) -> Option<f32> {+ let Some(name) = scroll else {+ ui.data_mut(|d| d.remove_temp::<f32>(list_shrink_id()));+ body(ui);+ return None;+ };+ ui.data_mut(|d| d.insert_temp(list_applied_id(), 0.0_f32));+ let top = ui.cursor().top();+ // (an auto-sized window offers its content last frame's height; the minimum lets a dialog+ // that grows take its full height at once, and the area still shrinks to fit its content)+ let out = egui::ScrollArea::vertical()+ .id_salt(("dialog-body", name))+ .max_height(max_height)+ .min_scrolled_height(max_height)+ .auto_shrink([true, true])+ .show(ui, body);+ // what the lists that scroll on their own gave up this frame, and what they should next frame+ let applied = ui.data(|d| d.get_temp::<f32>(list_applied_id())).unwrap_or(0.0);+ let was = ui.data(|d| d.get_temp::<f32>(list_shrink_id())).unwrap_or(0.0);+ let shrink = (out.content_size.y + applied - max_height).max(0.0);+ if (shrink - was).abs() > 0.5 {+ ui.data_mut(|d| d.insert_temp(list_shrink_id(), shrink));+ ui.ctx().request_repaint();+ }+ // (the room the scroll area took: its `inner_rect` can be taller than what it allocated)+ Some(ui.min_rect().bottom() - top)+}++/// Open a one-field dialog that runs `command` with `params` + `{key: typed value}`.+pub fn prompt(app: &mut LightcraftApp, title: &str, hint: &str, value: &str, command: &str, params: serde_json::Value, key: &str) {+ app.ui.dialog =+ Some(Dialog::TextPrompt { title: title.into(), hint: hint.into(), value: value.into(), command: command.into(), params, key: key.into() });+}++/// A themed slider row editing `v`; true when it changed.+pub(super) fn num(ui: &mut egui::Ui, spec: &ControlSpec, v: &mut f64) -> bool {+ match crate::widgets::slider(ui, spec, *v, true, None).value {+ Some(n) => {+ *v = n;+ true+ }+ None => false,+ }+}++pub(super) fn field<R>(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R {+ let t = Tokens::get(ui.ctx());+ ui.horizontal(|ui| {+ ui.allocate_ui_with_layout(egui::vec2(LABEL_W, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {+ ui.set_min_width(LABEL_W);+ ui.label(egui::RichText::new(crate::i18n::tr(label)).color(t.text_label));+ });+ add(ui)+ })+ .inner+}++/// The rest of a [`field`] row, laid out right to left: `add` places its trailing button(s) first,+/// then a text field taking exactly the width that's left. (Subtracting a guessed button width+/// instead made the auto-sized dialog grow every frame when the real button was wider, #8.)+pub(super) fn trailing_button_row(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) {+ let h = ui.spacing().interact_size.y.max(24.0);+ ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), h), egui::Layout::right_to_left(egui::Align::Center), add);+}++/// A labelled row of mutually exclusive choice buttons (ids `button:{id}-{index}`).+pub(super) fn choices<V: PartialEq + Copy>(ui: &mut egui::Ui, label: &str, id: &str, options: &[(V, &str)], value: &mut V) {+ field(ui, label, |ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ for (i, (v, l)) in options.iter().enumerate() {+ if crate::widgets::text_button(ui, &format!("{id}-{i}"), l, *value == *v).clicked() {+ *value = *v;+ }+ }+ });+}++/// Dialogs that Return confirms with nothing focused (those with text fields confirm from the+/// field: `dialog_field`).+pub(super) fn return_confirms(dlg: &Dialog) -> bool {+ matches!(dlg, Dialog::CopySettings { .. } | Dialog::PasteSettings { .. })+}++/// A dialog's one text field: it takes the focus when the dialog opens, and opens with its text+/// selected, so typing replaces it. It takes the focus back only while nothing else has it: taking+/// it back every frame would keep Tab from ever reaching the dialog's buttons and check boxes.+/// True when Return confirms the dialog; Esc cancels the dialog (`show`).+pub(super) fn dialog_field(ui: &mut egui::Ui, widget: &str, text: &mut String, hint: &str) -> bool {+ let r = crate::text_field::TextField::singleline(widget, text).hint(crate::i18n::tr(hint)).width(f32::INFINITY).select_on_focus(true).show(ui);+ // (and takes it back when nothing has it: after a click on the dialog's background or a check box,+ // or when Return gave it up on a refusal; a control Tab reached keeps it). A disabled dialog (a+ // prompt or the blocking library window owns input) must not request the focus at all: egui's+ // text edit would otherwise keep editing the draft from host text behind that window.+ if ui.is_enabled() && (just_opened(ui, widget) || (!r.editing && r.ending.is_none() && ui.memory(|m| m.focused().is_none()))) {+ r.response.request_focus();+ }+ r.ending == Some(crate::text_field::Ending::Return)+}++/// The dialog part `key` is drawn this frame but wasn't the frame before: the dialog has just+/// opened (to give its first field the focus once).+pub(super) fn just_opened(ui: &egui::Ui, key: &str) -> bool {+ let id = egui::Id::unique(("dialog-shown", key));+ let pass = ui.ctx().cumulative_pass_nr();+ let last: Option<u64> = ui.data_mut(|d| d.get_temp(id));+ ui.data_mut(|d| d.insert_temp(id, pass));+ last.and_then(|l| l.checked_add(1)) != Some(pass)+}++/// How a dialog's confirm button looks: [`ConfirmStyle::Primary`] (the accent's fill) when it+/// makes or brings in something, plain when it deletes or removes (never the eye-catching+/// default) or when the dialog only shows something (its Close).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ConfirmStyle {+ Primary,+ Plain,+}++pub fn confirm_style(dlg: &Dialog) -> ConfirmStyle {+ match dlg {+ Dialog::ConfirmDelete { .. } | Dialog::DeleteKeyword { .. } | Dialog::DeleteEffects { .. } | Dialog::RemoveFolder { .. } => {+ ConfirmStyle::Plain+ }+ _ if only_shows(dlg) => ConfirmStyle::Plain,+ _ => ConfirmStyle::Primary,+ }+}++/// A dialog that only shows something: one Close, nothing to confirm or cancel. (Synchronize+/// Folder is one when its folder turned out up to date.)+pub(super) fn only_shows(dlg: &Dialog) -> bool {+ matches!(+ dlg,+ Dialog::About+ | Dialog::Shortcuts+ | Dialog::Settings { .. }+ | Dialog::SystemInfo { .. }+ | Dialog::AllMetadata { .. }+ | Dialog::WhatsNew+ | Dialog::ManageEffects { .. }+ | Dialog::ViewOptions+ ) || matches!(dlg, Dialog::SynchronizeFolder { counts: Some(c), .. } if c.up_to_date())+}diff --git a/crates/ui-egui/src/dialogs/rename.rs b/crates/ui-egui/src/dialogs/rename.rsnew file mode 100644index 000000000..f178ba6eb--- /dev/null+++ b/crates/ui-egui/src/dialogs/rename.rs@@ -0,0 +1,96 @@+use super::*;++/// Rows the Rename dialog previews.+pub(super) const RENAME_PREVIEW_ROWS: usize = 6;++/// The Rename dialog's preview: its first rows (`None` while being planned) and how many files+/// are renamed. Which names are taken is checked on disk, which can block on a slow drive, so the+/// rows are planned on a worker thread, and only when the template, start number, photos or+/// catalog change — never once per frame.+pub(crate) fn rename_preview(+ app: &mut LightcraftApp,+ ctx: &egui::Context,+ template: &str,+ start: usize,+) -> (Option<Vec<lightcraft_engine::rename::RenamePlan>>, usize) {+ use std::hash::{Hash, Hasher};+ type Rows = std::sync::Arc<std::sync::Mutex<Option<Vec<lightcraft_engine::rename::RenamePlan>>>>;+ let ids = app.session.selected();+ let photos = lightcraft_engine::rename::rename_photos(&app.session.catalog, &ids);+ let total = photos.len();+ let mut h = std::collections::hash_map::DefaultHasher::new();+ (template, start, app.session.catalog.revision, &ids).hash(&mut h);+ let key = h.finish();+ let id = egui::Id::unique("rename-preview-rows");+ let read = |rows: &Rows| rows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();+ if let Some((k, rows)) = ctx.data(|d| d.get_temp::<(u64, Rows)>(id))+ && k == key+ {+ return (read(&rows), total);+ }+ let rows: Rows = Default::default();+ let first: Vec<_> = photos.into_iter().take(RENAME_PREVIEW_ROWS).collect();+ let (out, template, repaint) = (rows.clone(), template.to_string(), ctx.clone());+ let exists = app.session.media.availability.probe();+ let work = move || {+ let plans = lightcraft_engine::rename::plan_rename_photos(&first, &template, start, &|f| exists(f));+ *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(plans);+ repaint.request_repaint();+ };+ #[cfg(not(target_arch = "wasm32"))]+ if let Err(e) = std::thread::Builder::new().name("lc-rename-preview".into()).spawn(work) {+ log::warn!("rename preview: {e}");+ }+ #[cfg(target_arch = "wasm32")]+ work();+ ctx.data_mut(|d| d.insert_temp(id, (key, rows.clone())));+ (read(&rows), total)+}++pub(super) struct PersonRenamePlan {+ pub(super) faces: usize,+ pub(super) needs_merge: bool,+ /// Why Rename stays disabled. `None` when the typed name can be applied.+ pub(super) block: Option<&'static str>,+}++/// What renaming `from` to `to` would do, using the same rules as `faces.renamePerson`.+pub(super) fn person_rename_plan(cat: &lightcraft_catalog::Catalog, from: &str, to: &str) -> PersonRenamePlan {+ let to_trim = to.trim();+ if to_trim.is_empty() {+ return PersonRenamePlan { faces: 0, needs_merge: false, block: Some("Type a name") };+ }+ if to_trim.chars().count() > 200 || to_trim.chars().any(char::is_control) {+ return PersonRenamePlan { faces: 0, needs_merge: false, block: Some("A name is at most 200 characters, without control characters") };+ }+ let from_key = from.trim().to_lowercase();+ let to_key = to_trim.to_lowercase();+ let mut matched = 0usize;+ let mut faces = 0usize;+ let mut needs_merge = false;+ if !from_key.is_empty() {+ for photo in cat.photos().filter(|p| p.in_library()) {+ for region in photo.meta.regions.iter().filter(|r| r.kind == lightcraft_meta::RegionKind::Face) {+ let Some(name) = region.name.as_deref().map(str::trim).filter(|n| !n.is_empty()) else { continue };+ let key = name.to_lowercase();+ if key == from_key {+ matched += 1;+ if region.name.as_deref() != Some(to_trim) {+ faces += 1;+ }+ } else if key == to_key {+ needs_merge = true;+ }+ }+ }+ }+ let block = if matched == 0 {+ Some("No person by that name")+ } else if faces == 0 {+ Some("That is already their name")+ } else {+ None+ };+ // a case-only change is the same person, not a merge+ PersonRenamePlan { faces, needs_merge: needs_merge && from_key != to_key, block }+}diff --git a/crates/ui-egui/src/dialogs/sam_model.rs b/crates/ui-egui/src/dialogs/sam_model.rsnew file mode 100644index 000000000..fa578440b--- /dev/null+++ b/crates/ui-egui/src/dialogs/sam_model.rs@@ -0,0 +1,114 @@+use super::*;++/// No SAM 3 model, no download running and nowhere to download it from: installing it by hand is+/// all the dialog can offer.+pub(super) fn sam_by_hand(sam: &lightcraft_engine::segment::Segmenter) -> bool {+ !sam.installed() && !sam.download_status().running && sam.mirrors().is_empty()+}++/// The model installation guide.+const SAM_HELP: &str = "https://github.com/storytold/lightcraft/blob/main/docs/ai-masks.md#getting-the-model";++/// Open the configured SAM 3 folder itself; revealing a file opens its parent instead.+pub(crate) fn show_model_folder(app: &mut LightcraftApp) -> Result<serde_json::Value, String> {+ let dir = app.session.segmenter.dir.as_ref().ok_or("no folder is set for the SAM 3 model")?;+ let path = dir.to_str().ok_or("the model folder path is not valid UTF-8")?;+ let open = app.services.open_with.as_mut().ok_or("opening model folders is not available here")?;+ // Create only after the host action is available. Existing model files are left alone.+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ #[cfg(target_os = "linux")]+ if let Some(open_folder) = app.services.open_model_folder.clone() {+ let path = path.to_string();+ let folder = path.clone();+ crate::tasks::spawn(+ app,+ "Show in File Manager",+ Some("openModelFolder"),+ move || open_folder(&folder),+ |app, ctx, result| {+ if let Err(e) = result {+ app.toast_error(ctx, e);+ }+ },+ )?;+ return Ok(json!({"path": path, "background": true}));+ }+ open(path, "")?;+ Ok(json!({"path": path}))+}++/// The SAM 3 dialog: what the model is, its size and licence, and the download's progress.+pub(super) fn sam_model_body(app: &mut LightcraftApp, ui: &mut egui::Ui, error: Option<&str>) {+ use lightcraft_engine::segment::{LICENSE_NAME, LICENSE_URL, MODEL_BYTES};+ let t = Tokens::get(ui.ctx());+ let seg = &app.session.segmenter;+ let d = seg.download_status();+ if seg.installed() {+ ui.label(crate::i18n::tr("The SAM 3 model is installed: Object and Describe masks are ready."));+ return;+ }+ let gb = |b: u64| b as f64 / 1e9;+ ui.label(crate::i18n::tr(+ "Object and Describe masks use SAM 3, Meta's segmentation model. It isn't part of LightCraft, and everything else works without it.",+ ));+ let dir = seg.dir.as_ref().map(|d| d.display().to_string()).unwrap_or_default();+ ui.label(format!("{} {:.1} GB, {} {dir}", crate::i18n::tr("A one-time download of about"), gb(MODEL_BYTES), crate::i18n::tr("saved in")));+ ui.label(+ egui::RichText::new(format!(+ "{} {LICENSE_NAME} — {}",+ crate::i18n::tr("Licence:"),+ crate::i18n::tr("Meta's terms, not LightCraft's. Downloading it means accepting them.")+ ))+ .color(t.text_label),+ );+ let r = ui.link(crate::i18n::tr("Read the SAM License")).on_hover_text(LICENSE_URL);+ crate::widgets::register(ui, "link:samLicense", r.rect);+ if r.clicked() {+ let _ = crate::links::open(app, LICENSE_URL);+ }+ let seg = &app.session.segmenter;+ if d.running {+ ui.add_space(4.0);+ let text = format!("{:.2} / {:.2} GB · {}", gb(d.done), gb(d.total), d.file);+ crate::progress::Progress::new(crate::progress::fraction_of(d.done, d.total)).label(text).widget("progress:samDownload").show(ui);+ let r = ui.button(crate::i18n::tr("Cancel Download"));+ crate::widgets::register(ui, "button:samCancel", r.rect);+ if r.clicked() {+ app.session.segmenter.cancel_download();+ }+ ui.label(egui::RichText::new(crate::i18n::tr("You can close this: the download continues, and resumes if interrupted.")).color(t.text_dim));+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(250));+ return;+ }+ if seg.mirrors().is_empty() {+ // nothing to download from: say how to install it by hand, with the folder and the guide a click away+ let dir = seg.dir.clone();+ ui.label(+ egui::RichText::new(crate::i18n::tr(+ "This build can't download the model yet. To install it by hand, put model.safetensors, vocab.json and merges.txt from Meta's facebook/sam3 in the folder above: Object and Describe work as soon as they are there.",+ ))+ .color(t.text_dim),+ );+ ui.horizontal_wrapped(|ui| {+ if dir.is_some() && crate::menus::ui_enabled(app, "app.openSamModelFolder") {+ let r = ui.button(crate::i18n::tr(crate::menus::reveal_label()));+ crate::widgets::register(ui, "button:samFolder", r.rect);+ if r.clicked()+ && let Err(e) = app.run("app.openSamModelFolder", json!({}))+ {+ app.toast_error(ui.ctx(), e);+ }+ }+ let r = ui.link(crate::i18n::tr("How to install the model")).on_hover_text(SAM_HELP);+ crate::widgets::register(ui, "link:samHelp", r.rect);+ if r.clicked()+ && let Err(e) = crate::links::open(app, SAM_HELP)+ {+ app.toast(ui.ctx(), e);+ }+ });+ }+ if let Some(e) = error.map(str::to_string).or(d.error) {+ ui.label(egui::RichText::new(format!("{} {e}", crate::i18n::tr("The download didn't work:"))).color(egui::Color32::from_rgb(230, 90, 80)));+ }+}diff --git a/crates/ui-egui/src/dialogs/slideshow_export.rs b/crates/ui-egui/src/dialogs/slideshow_export.rsindex 62996e421..ed33d0341 100644--- a/crates/ui-egui/src/dialogs/slideshow_export.rs+++ b/crates/ui-egui/src/dialogs/slideshow_export.rs@@ -5,6 +5,8 @@use serde_json::{Value, json};+use super::frame::{choices, field};+use super::*;use crate::LightcraftApp;use crate::pick::{PickKind, PickRequest, Picked};@@ -71,6 +73,61 @@ pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) {app.toast(ctx, msg);}+/// A labelled row (fixed label column).+/// View ▸ Export Slideshow…: what to write (PDF, JPEG sequence, video) and how big; where comes+/// after (a save dialog).+pub(super) fn slideshow_export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, settings: &mut lightcraft_engine::slideshow_export::ExportSettings) {+ use lightcraft_engine::slideshow_export::{ExportSettings, Format};+ let t = Tokens::get(ui.ctx());+ let photos = app.session.visible_cloned().len();+ let slide = app.session.slideshow.slide_duration;+ let (intro, ending) = app.session.slide_titles.durations(slide);+ let titles = usize::from(intro.is_some()) + usize::from(ending.is_some());+ let seconds = photos as f64 * slide + intro.unwrap_or(0.0) + ending.unwrap_or(0.0);+ let summary = crate::i18n::tr_format!(+ "{n} photos in view · {slides} slides · {time}",+ n = photos,+ slides = photos + titles,+ time = format!("{}:{:02}", (seconds / 60.0).floor() as u64, (seconds % 60.0).round() as u64)+ );+ ui.label(egui::RichText::new(summary).color(t.text_dim));+ let before = settings.format;+ choices(ui, "Format", "slideshowExportFormat", &[(Format::Pdf, "PDF"), (Format::Jpeg, "JPEG"), (Format::Video, "Video")], &mut settings.format);+ if settings.format != before {+ *settings = ExportSettings { full_screen: settings.full_screen, ..ExportSettings::for_format(settings.format) };+ }+ match settings.format {+ Format::Video => {+ choices(ui, "Size", "slideshowExportSize", &[(720, "720p"), (1080, "1080p")], &mut settings.size);+ choices(ui, "Frame rate", "slideshowExportFps", &[(24, "24 fps"), (30, "30 fps")], &mut settings.fps);+ let mut webm = settings.container == "webm";+ choices(ui, "Container", "slideshowExportContainer", &[(false, "MP4"), (true, "WebM")], &mut webm);+ settings.container = if webm { "webm".into() } else { "mp4".into() };+ }+ _ => {+ choices(ui, "Size", "slideshowExportSize", &[(1024, "1024 px"), (1920, "1920 px"), (3840, "3840 px")], &mut settings.size);+ }+ }+ field(ui, "Quality", |ui| {+ let r = ui.add(egui::Slider::new(&mut settings.quality, 1..=100));+ crate::widgets::register(ui, "slider:slideshowExportQuality", r.rect);+ });+ let note = match settings.format {+ Format::Pdf => {+ let r = ui.checkbox(&mut settings.full_screen, crate::i18n::tr("Automatically show full screen"));+ crate::widgets::register(ui, "check:slideshowExportFullScreen", r.rect);+ "One page per slide (the long side in pixels = points), with the slide duration and fade for the viewer's presentation mode."+ }+ Format::Jpeg => "Numbered JPEG files (name-001.jpg…) in a new folder named in the next step.",+ Format::Video => "AV1 video, each slide held for its duration with its fades. No sound: music is not exported yet.",+ };+ ui.label(egui::RichText::new(crate::i18n::tr(note)).color(t.text_dim));+ ui.label(+ egui::RichText::new(crate::i18n::tr("Slides use the slideshow's layout, overlays and intro and ending screens, in view order."))+ .color(t.text_dim),+ );+}+#[cfg(test)]mod tests {use super::*;