LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Merge main (Photo Merge); M1.14b: stack merge results with their sources
Brandon Thomasce3dd5e15646
diff --cc crates/engine/src/cmd/mod.rsindex cce167ed7,623313490..bf4582212--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@@ -8,7 -8,7 +8,8 @@@ mod developmod edit;mod library;mod masks;+ mod merge;+mod organize;mod preset_files;mod query;mod xmp;@@@ -103,7 -103,7 +104,8 @@@ pub fn command_specs() -> &'static [Comv.extend(library::specs());v.extend(develop::specs());v.extend(masks::specs());+ v.extend(organize::specs());+ v.extend(merge::specs());v.extend(query::specs());v.extend(xmp::specs());v.extend(preset_files::specs());diff --cc crates/engine/src/lib.rsindex 25efe8757,89b28fef9..5002e5012--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@ -339,6 -325,6 +340,8 @@@ mod tests_import#[cfg(test)]mod tests_library;#[cfg(test)]+ mod tests_merge;+ #[cfg(test)]+mod tests_organize;+#[cfg(test)]mod tests_xmp;diff --cc crates/engine/src/merge.rsindex 000000000,608928edc..81d06e34dmode 000000,100644..100644--- a/crates/engine/src/merge.rs+++ b/crates/engine/src/merge.rs@@@ -1,0 -1,408 +1,413 @@@+ //! Photo Merge (HDR, Panorama, HDR Panorama) in the library.+ //!+ //! A merge is planned from the session ([`crate::Session::plan_merge`] → [`MergeJob`], which is+ //! `Send` and self-contained), run anywhere (a worker thread in the app, inline for the CLI/MCP:+ //! [`MergeJob::run`], with progress and cancellation), and finished on the session+ //! ([`crate::Session::finish_merge`]): the DNG is written next to the first source photo+ //! (`<name>-HDR.dng`, `-Pano.dng`, `-HDR-Pano.dng`), imported, selected, and given Auto Settings /+ //! the auto-crop rectangle when asked. A *preview* run works on ≤ 1024 px frames and returns a+ //! rendered image (with the deghost overlay when asked) instead of a file.++ use std::sync::Arc;++ use lightcraft_catalog::{PhotoId, Source};+ use lightcraft_develop::DevelopSettings;+ use lightcraft_merge::{Deghost, Frame, HdrOptions, PanoOptions, Projection};+ use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo};+ use lightcraft_raster::{Rgb32f, Rgba8};+ use serde::{Deserialize, Serialize};+ use serde_json::{Value, json};++ use crate::{EngineError, Result, Session};++ /// Long edge of the frames of a preview merge.+ pub const PREVIEW_EDGE: usize = 1024;++ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+ #[serde(tag = "kind", rename_all = "camelCase")]+ pub enum MergeKind {+ Hdr {+ hdr: HdrOptions,+ },+ Panorama {+ pano: PanoOptions,+ },+ /// Merge each bracket (`bracket` consecutive photos; 0 = detect from EXIF), then stitch.+ HdrPanorama {+ hdr: HdrOptions,+ pano: PanoOptions,+ bracket: usize,+ },+ }++ impl MergeKind {+ fn suffix(&self) -> &'static str {+ match self {+ MergeKind::Hdr { .. } => "HDR",+ MergeKind::Panorama { .. } => "Pano",+ MergeKind::HdrPanorama { .. } => "HDR-Pano",+ }+ }+ fn min_photos(&self) -> usize {+ match self {+ MergeKind::HdrPanorama { .. } => 4,+ _ => 2,+ }+ }+ }++ /// Options that apply after the merge.+ #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+ #[serde(default, rename_all = "camelCase")]+ pub struct MergeFinish {+ /// Run Auto Settings on the result.+ pub auto_settings: bool,- /// Group the result with its sources. LightCraft has no stacks yet: recorded in the result's- /// caption instead (see `docs/merge.md`).++ /// Stack the result on top of its sources (collapsed); the result's caption also lists them.+ pub stack: bool,+ /// Preview only: tint deghosted areas red.+ pub show_overlay: bool,+ }++ /// Reads a source photo's bytes (by catalog path).+ pub type ByteReader = Arc<dyn Fn(&str) -> std::result::Result<Vec<u8>, String> + Send + Sync>;++ /// A planned merge, detached from the session.+ #[derive(Clone)]+ pub struct MergeJob {+ pub kind: MergeKind,+ pub finish: MergeFinish,+ pub sources: Vec<(PhotoId, String)>,+ /// `Some(edge)`: preview at that frame size; `None`: the full-resolution merge.+ pub preview: Option<usize>,+ pub read: ByteReader,+ }++ /// What a merge produced.+ pub struct MergeOutput {+ /// The DNG (also for previews, at preview size).+ pub dng: Vec<u8>,+ /// Rendered preview (previews only).+ pub preview: Option<Rgba8>,+ /// Auto-crop rectangle (normalised x, y, w, h) for panoramas.+ pub crop: Option<[f64; 4]>,+ /// Statistics for the caller (exposures, alignment, projection, …).+ pub info: Value,+ }++ pub type ProgressFn<'a> = dyn Fn(f32, &str) -> bool + Sync + 'a;++ fn err(e: impl std::fmt::Display) -> String {+ e.to_string()+ }++ impl MergeJob {+ fn load(&self, orient: bool, progress: &ProgressFn, span: (f32, f32)) -> std::result::Result<Vec<Frame>, String> {+ use rayon::prelude::*;+ let done = std::sync::atomic::AtomicUsize::new(0);+ let n = self.sources.len();+ let frames: std::result::Result<Vec<Frame>, String> = self+ .sources+ .par_iter()+ .map(|(_, path)| {+ let bytes = (self.read)(path)?;+ let f = lightcraft_merge::load_frame(&bytes, self.preview, orient).map_err(|e| format!("{path}: {e}"));+ let k = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;+ progress(span.0 + (span.1 - span.0) * k as f32 / n as f32, "Reading photos");+ f+ })+ .collect();+ frames+ }++ /// Run the merge. `progress(fraction, stage)` returns false to cancel.+ pub fn run(&self, progress: &ProgressFn) -> std::result::Result<MergeOutput, String> {+ if self.sources.len() < self.kind.min_photos() {+ return Err(format!("select at least {} photos", self.kind.min_photos()));+ }+ if !progress(0.0, "Reading photos") {+ return Err("cancelled".into());+ }+ let sub = |a: f32, b: f32| move |f: f32, s: &str| progress(a + (b - a) * f, s);+ let (image, color, orientation, metadata, baseline, samples, crop, mut info, ghost) = match &self.kind {+ MergeKind::Hdr { hdr } => {+ let frames = self.load(false, progress, (0.0, 0.3))?;+ let p = sub(0.3, 0.9);+ let r = lightcraft_merge::merge_hdr(frames, hdr, &p).map_err(err)?;+ let info = json!({+ "reference": self.sources[r.reference].0.0,+ "ev": r.ev, "evExif": r.ev_exif,+ "alignment": r.alignments.iter().map(|a| json!({"model": a.model, "inliers": a.inliers, "rmsPx": a.rms})).collect::<Vec<_>>(),+ });+ let ghost = (!r.ghost.data.is_empty()).then(|| r.ghost.oriented(r.orientation));+ (r.radiance, r.color, r.orientation, r.metadata, r.baseline_exposure, lightcraft_merge::DngSamples::Half, None, info, ghost)+ }+ MergeKind::Panorama { pano } => {+ let frames = self.load(true, progress, (0.0, 0.25))?;+ let p = sub(0.25, 0.9);+ let r = lightcraft_merge::stitch(frames, pano, &p).map_err(err)?;+ let info = pano_info(&r, &self.sources);+ (+ r.image,+ r.color,+ lightcraft_geom::Orientation::Normal,+ r.metadata,+ r.baseline_exposure,+ lightcraft_merge::DngSamples::U16,+ r.crop,+ info,+ None,+ )+ }+ MergeKind::HdrPanorama { hdr, pano, bracket } => {+ let frames = self.load(false, progress, (0.0, 0.2))?;+ let b =+ if *bracket >= 2 { *bracket } else { detect_bracket(&frames).ok_or("could not detect the bracket size from EXIF; set it")? };+ if !frames.len().is_multiple_of(b) || frames.len() / b < 2 {+ return Err(format!("{} photos don't form brackets of {b} for at least two positions", frames.len()));+ }+ let groups = frames.len() / b;+ let mut merged = Vec::new();+ let mut it = frames.into_iter();+ for g in 0..groups {+ let set: Vec<Frame> = it.by_ref().take(b).collect();+ let p = sub(0.2 + 0.4 * g as f32 / groups as f32, 0.2 + 0.4 * (g + 1) as f32 / groups as f32);+ let r = lightcraft_merge::merge_hdr(set, hdr, &p).map_err(err)?;+ let mut f = Frame {+ image: r.radiance,+ clip: f32::INFINITY,+ exposure: None,+ raw: r.raw,+ color: r.color,+ orientation: r.orientation,+ metadata: r.metadata,+ baseline_exposure: r.baseline_exposure,+ };+ f.orient();+ merged.push(f);+ }+ let p = sub(0.6, 0.9);+ let r = lightcraft_merge::stitch(merged, pano, &p).map_err(err)?;+ let mut info = pano_info(&r, &self.sources);+ info["bracket"] = json!(b);+ (+ r.image,+ r.color,+ lightcraft_geom::Orientation::Normal,+ r.metadata,+ r.baseline_exposure,+ lightcraft_merge::DngSamples::Half,+ r.crop,+ info,+ None,+ )+ }+ };+ if !progress(0.9, "Writing DNG") {+ return Err("cancelled".into());+ }+ let mut metadata = metadata;+ if self.finish.stack {+ let names: Vec<&str> =+ self.sources.iter().map(|(_, p)| std::path::Path::new(p).file_name().and_then(|n| n.to_str()).unwrap_or(p)).collect();+ metadata.caption = Some(format!("Merged from {}", names.join(", ")));+ }+ metadata.software = Some("LightCraft Photo Merge".into());+ let dng = lightcraft_merge::write_linear_dng(&image, &color, orientation, &metadata, baseline, samples).map_err(err)?;+ info["width"] = json!(image.width);+ info["height"] = json!(image.height);+ let preview = match self.preview {+ Some(edge) => Some(render_preview(&dng, edge, self.finish.auto_settings, crop, ghost.as_ref().filter(|_| self.finish.show_overlay))?),+ None => None,+ };+ progress(1.0, "Done");+ Ok(MergeOutput { dng, preview, crop, info })+ }+ }++ fn pano_info(r: &lightcraft_merge::PanoResult, sources: &[(PhotoId, String)]) -> Value {+ json!({+ "projection": r.projection,+ "used": r.used.iter().filter_map(|&i| sources.get(i).map(|s| s.0.0)).collect::<Vec<_>>(),+ "fov": [r.fov.0, r.fov.1],+ "rmsPx": r.rms,+ "gains": r.gains,+ "crop": r.crop,+ })+ }++ /// Bracket size from EXIF: the smallest period of the exposure sequence (≥ 2).+ pub fn detect_bracket(frames: &[Frame]) -> Option<usize> {+ let ev: Vec<f64> = frames.iter().map(|f| f.exposure).collect::<Option<_>>()?;+ let n = ev.len();+ (2..=n / 2).find(|&b| n.is_multiple_of(b) && (0..n).all(|k| (ev[k] - ev[k % b]).abs() < 0.2) && (1..b).any(|k| (ev[k] - ev[0]).abs() > 0.5))+ }++ /// Render a merged DNG like the library will show it (default raw settings, optionally Auto+ /// Settings and the auto crop), with the deghost overlay tinted red.+ fn render_preview(+ dng: &[u8],+ edge: usize,+ auto: bool,+ crop: Option<[f64; 4]>,+ ghost: Option<&lightcraft_raster::Plane>,+ ) -> std::result::Result<Rgba8, String> {+ let (src, info) = crate::files::load_bytes(dng, edge)?;+ let mut s = DevelopSettings::for_raw(info.as_shot_temp, info.as_shot_tint);+ if auto {+ apply_auto(&mut s, &src, &info);+ }+ if let Some(c) = crop {+ s.crop.geometry.rect = lightcraft_geom::Rect::from_xywh(c[0], c[1], c[2], c[3]);+ }+ let req = RenderRequest { max_w: edge, max_h: edge, quality: Quality::Full, apply_crop: false };+ let mut img = lightcraft_pipeline::render(&src, &info, &s, &req).image;+ if let Some(g) = ghost {+ let (w, h) = (img.width, img.height);+ for y in 0..h {+ for x in 0..w {+ let gx = ((x as f32 + 0.5) / w as f32 * g.width as f32) as usize;+ let gy = ((y as f32 + 0.5) / h as f32 * g.height as f32) as usize;+ let a = g.get(gx.min(g.width - 1), gy.min(g.height - 1)).clamp(0.0, 1.0) * 0.6;+ if a > 0.01 {+ let p = &mut img.data[y * w + x];+ p[0] = (p[0] as f32 * (1.0 - a) + 255.0 * a) as u8;+ p[1] = (p[1] as f32 * (1.0 - a)) as u8;+ p[2] = (p[2] as f32 * (1.0 - a)) as u8;+ }+ }+ }+ }+ if let Some(c) = crop {+ // draw the auto-crop frame+ let (w, h) = (img.width as f64, img.height as f64);+ let (x0, y0, x1, y1) = ((c[0] * w) as usize, (c[1] * h) as usize, ((c[0] + c[2]) * w) as usize, ((c[1] + c[3]) * h) as usize);+ for y in y0..y1.min(img.height) {+ for x in x0..x1.min(img.width) {+ if y == y0 || y + 1 == y1 || x == x0 || x + 1 == x1 {+ img.data[y * img.width + x] = [255, 255, 255, 255];+ }+ }+ }+ }+ Ok(img)+ }++ fn apply_auto(s: &mut DevelopSettings, src: &Rgb32f, info: &SourceInfo) {+ let a = lightcraft_pipeline::auto::auto_tone(src, info, s);+ s.light.exposure = a.exposure;+ s.light.contrast = a.contrast;+ s.light.highlights = a.highlights;+ s.light.shadows = a.shadows;+ s.light.whites = a.whites;+ s.light.blacks = a.blacks;+ s.color.vibrance = a.vibrance;+ s.color.saturation = a.saturation;+ }++ /// A free file name `dir/<stem>-<suffix>.dng` (`-2`, `-3`… when taken).+ fn output_path(first: &str, suffix: &str) -> String {+ let p = std::path::Path::new(first);+ let dir = p.parent().map(|d| d.to_path_buf()).unwrap_or_default();+ let stem = p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "Merge".into());+ for k in 1.. {+ let name = if k == 1 { format!("{stem}-{suffix}.dng") } else { format!("{stem}-{suffix}-{k}.dng") };+ let cand = dir.join(name);+ if !cand.exists() {+ return cand.to_string_lossy().to_string();+ }+ }+ unreachable!()+ }++ /// Parse `merge.*` command parameters into a kind and finishing options.+ pub fn parse(id: &str, p: &Value) -> Result<(MergeKind, MergeFinish)> {+ let bad = |m: String| EngineError::BadParams { cmd: id.into(), msg: m };+ let deghost: Deghost = serde_json::from_value(p.get("deghost").cloned().unwrap_or(json!("none"))).map_err(|e| bad(format!("deghost: {e}")))?;+ let hdr = HdrOptions { align: p.get("align").and_then(Value::as_bool).unwrap_or(true), deghost };+ let projection: Projection =+ serde_json::from_value(p.get("projection").cloned().unwrap_or(json!("auto"))).map_err(|e| bad(format!("projection: {e}")))?;+ let pano = PanoOptions {+ projection,+ boundary_warp: p.get("boundaryWarp").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 100.0),+ auto_crop: p.get("autoCrop").and_then(Value::as_bool).unwrap_or(false),+ fill_edges: p.get("fillEdges").and_then(Value::as_bool).unwrap_or(false),+ max_megapixels: p.get("maxMegapixels").and_then(Value::as_f64).unwrap_or(40.0),+ };+ let kind = match id {+ "merge.hdr" => MergeKind::Hdr { hdr },+ "merge.panorama" => MergeKind::Panorama { pano },+ _ => MergeKind::HdrPanorama { hdr, pano, bracket: p.get("bracket").and_then(Value::as_u64).unwrap_or(0) as usize },+ };+ let finish = MergeFinish {+ auto_settings: p.get("autoSettings").and_then(Value::as_bool).unwrap_or(true),+ stack: p.get("stack").and_then(Value::as_bool).unwrap_or(false),+ show_overlay: p.get("showOverlay").and_then(Value::as_bool).unwrap_or(false),+ };+ Ok((kind, finish))+ }++ impl Session {+ /// Plan a merge of `ids` (catalog order of the given ids is kept).+ pub fn plan_merge(&self, kind: MergeKind, finish: MergeFinish, ids: &[PhotoId], preview: bool) -> Result<MergeJob> {+ let mut sources = Vec::new();+ for id in ids {+ let p = self.catalog.photo(*id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(*id))?;+ match &p.source {+ Source::File { path } => sources.push((*id, path.clone())),+ Source::Demo { .. } => return Err(EngineError::Other(format!("{} is a demo photo; Photo Merge needs photo files", p.file_name))),+ }+ }+ if sources.len() < kind.min_photos() {+ return Err(EngineError::Other(format!("select at least {} photos to merge", kind.min_photos())));+ }+ let read: ByteReader = match &self.media.file_bytes {+ Some(r) => r.clone(),+ None => Arc::new(|path: &str| std::fs::read(path).map_err(|e| format!("{path}: {e}"))),+ };+ Ok(MergeJob { kind, finish, sources, preview: preview.then_some(PREVIEW_EDGE), read })+ }++ /// Write a finished (non-preview) merge next to its first source, import it, select it and+ /// apply Auto Settings / the auto crop. Returns `{id, path, …info}`.+ pub fn finish_merge(&mut self, job: &MergeJob, out: MergeOutput) -> Result<Value> {+ let first = &job.sources.first().ok_or_else(|| EngineError::Other("nothing merged".into()))?.1;+ let path = output_path(first, job.kind.suffix());+ std::fs::write(&path, &out.dng).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ let report = crate::import::import(self, std::slice::from_ref(&path), crate::import::ImportMode::Add)?;+ let id = report+ .imported+ .first()+ .copied()+ .map(PhotoId)+ .ok_or_else(|| EngineError::Other(format!("the merged file {path} could not be imported: {:?}", report.failed)))?;++ if job.finish.stack {++ let sources: Vec<PhotoId> = job.sources.iter().map(|(p, _)| *p).collect();++ if let Some(op) = self.catalog.stack_with_ops(id, &sources) {++ self.commit("Stack with Sources", op)?;++ }++ }+ self.selection = crate::Selection::single(id);+ if job.finish.auto_settings {+ self.execute("develop.auto", &json!({}))?;+ }+ if let Some(c) = out.crop+ && let Some(d) = self.develop_of(id)+ {+ let mut d = (*d).clone();+ d.crop.geometry.rect = lightcraft_geom::Rect::from_xywh(c[0], c[1], c[2], c[3]);+ self.set_develop(id, d, "Auto Crop")?;+ }+ let mut info = out.info;+ info["id"] = json!(id.0);+ info["path"] = json!(path);+ info["bytes"] = json!(out.dng.len());+ Ok(info)+ }++ /// Plan, run and finish a merge synchronously (CLI, MCP, control channel).+ pub fn merge_now(&mut self, kind: MergeKind, finish: MergeFinish, ids: &[PhotoId]) -> Result<Value> {+ let job = self.plan_merge(kind, finish, ids, false)?;+ let out = job.run(&|_, _| true).map_err(EngineError::Other)?;+ self.finish_merge(&job, out)+ }+ }diff --cc crates/engine/src/tests_merge.rsindex 000000000,507df3e11..93791fba0mode 000000,100644..100644--- a/crates/engine/src/tests_merge.rs+++ b/crates/engine/src/tests_merge.rs@@@ -1,0 -1,82 +1,90 @@@+ //! Photo Merge through the command layer: synthetic brackets / panorama views on disk → merged+ //! DNG next to the sources → imported, selected, Auto Settings / auto crop applied.++ use serde_json::json;++ use crate::Session;++ fn temp_dir(tag: &str) -> std::path::PathBuf {+ let d = std::env::temp_dir().join(format!("lc-merge-{tag}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+ }++ fn import(s: &mut Session, paths: Vec<String>) -> Vec<u64> {+ let r = s.execute("library.import", &json!({"paths": paths})).unwrap();+ r["imported"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect()+ }++ #[test]+ fn hdr_merge_command_creates_and_imports_a_dng() {+ let dir = temp_dir("hdr");+ let mut paths = Vec::new();+ for (i, b) in lightcraft_merge::synth::bracket_dngs(480, 320, &[-2.0, 0.0, 2.0]).into_iter().enumerate() {+ let p = dir.join(format!("IMG_{i}.dng"));+ std::fs::write(&p, b).unwrap();+ paths.push(p.to_string_lossy().to_string());+ }+ let mut s = Session::new().with_fs();+ let ids = import(&mut s, paths);+ assert_eq!(ids.len(), 3);+ // preview: rendered PNG, nothing added+ let png = dir.join("preview.png");+ let pv = s.execute("merge.hdr", &json!({"ids": ids, "deghost": "medium", "preview": true, "showOverlay": true, "previewPath": png})).unwrap();+ assert!(png.exists() && pv["previewSize"][0].as_u64().unwrap() > 100, "{pv}");+ assert_eq!(s.catalog.photos().count(), 3);+ let ev: Vec<f64> = pv["ev"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();+ assert!((ev[0] + 2.0).abs() < 0.1 && (ev[2] - 2.0).abs() < 0.1, "{ev:?}");+ // full merge+ let r = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": true, "stack": true})).unwrap();+ let path = r["path"].as_str().unwrap();+ assert!(path.ends_with("IMG_0-HDR.dng"), "{path}");+ let id = lightcraft_catalog::PhotoId(r["id"].as_u64().unwrap());+ let p = s.catalog.photo(id).unwrap().clone();+ assert_eq!((p.width, p.height), (480, 320));+ assert_eq!(p.kind, lightcraft_catalog::MediaKind::Raw);+ assert_eq!(s.selection.active, Some(id));+ let d = s.develop_of(id).unwrap();+ assert!(d.light.exposure != 0.0 || d.light.highlights != 0.0, "auto settings applied");+ let img = s.render_now(id, 256, 256).unwrap();+ assert_eq!(img.image.width, 256);++ // Create Stack: the result tops a collapsed stack of its sources, so the grid shows the result++ let st = s.catalog.stack_of(id).expect("merge result stacked").clone();++ assert_eq!(st.top(), id);++ assert_eq!(st.photos[1..].iter().map(|p| p.0).collect::<Vec<_>>(), ids);++ assert!(st.collapsed);++ assert_eq!(s.visible_cloned(), vec![id]);+ // the second merge doesn't overwrite the first+ let r2 = s.execute("merge.hdr", &json!({"ids": ids, "autoSettings": false})).unwrap();+ assert!(r2["path"].as_str().unwrap().ends_with("IMG_0-HDR-2.dng"));++ let id2 = lightcraft_catalog::PhotoId(r2["id"].as_u64().unwrap());++ assert!(s.catalog.stack_of(id2).is_none(), "no stack without the option");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn panorama_command_with_auto_crop() {+ let dir = temp_dir("pano");+ let mut paths = Vec::new();+ for (i, v) in lightcraft_merge::synth::pano_views(480, 360, 420.0, &[-25.0, 0.0, 25.0]).into_iter().enumerate() {+ let img = v.to_srgb8();+ let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();+ let p = dir.join(format!("P_{i}.png"));+ std::fs::write(&p, png).unwrap();+ paths.push(p.to_string_lossy().to_string());+ }+ let mut s = Session::new().with_fs();+ let ids = import(&mut s, paths);+ let r = s.execute("merge.panorama", &json!({"ids": ids, "projection": "cylindrical", "autoCrop": true, "autoSettings": false})).unwrap();+ assert_eq!(r["projection"], "cylindrical");+ assert_eq!(r["used"].as_array().unwrap().len(), 3);+ let id = lightcraft_catalog::PhotoId(r["id"].as_u64().unwrap());+ let p = s.catalog.photo(id).unwrap().clone();+ assert!(p.width > 800 && p.height > 300, "{}×{}", p.width, p.height);+ let crop = s.develop_of(id).unwrap().crop.geometry.rect;+ assert!(crop.width() < 1.0 && crop.width() * crop.height() > 0.5, "{crop:?}");+ // too few photos+ assert!(s.execute("merge.panorama", &json!({"ids": [ids[0]]})).is_err());+ let _ = std::fs::remove_dir_all(&dir);+ }diff --cc crates/ui-egui/src/lib.rsindex cd62c08a5,37fd8f579..71aed1e87--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -8,8 -8,8 +8,9 @@@pub mod control;pub mod headless;pub mod icons;+pub mod menubar;pub mod menus;+ pub mod merge;pub mod panels;pub mod render;pub mod shortcuts;diff --cc crates/ui-egui/src/menubar.rsindex 19d190500,000000000..1b56db044mode 100644,000000..100644--- a/crates/ui-egui/src/menubar.rs+++ b/crates/ui-egui/src/menubar.rs@@@ -1,579 -1,0 +1,580 @@@+//! The menu bar model: File, Edit, View, Photo, Window, Help, generated from the command registry+//! (engine commands with menu paths + [`crate::menus::UI_COMMANDS`]) with live labels, shortcuts,+//! enabled and checked state.+//!+//! One model drives every menu surface: the native macOS menu bar (built by the desktop host), the+//! in-window menu bar (web, Windows, Linux — [`show_in_window`]) and the control channel+//! (`ui.menu.tree`). Items are a command id plus parameters, run through [`run_item`] so they+//! behave exactly like their keyboard shortcuts.++use serde::Serialize;+use serde_json::{Value, json};++use crate::LightcraftApp;+use crate::menus::MenuEntry;+use crate::state::{RightPanel, ViewMode};++#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(tag = "kind", rename_all = "camelCase")]+pub enum MenuNode {+ Item {+ id: String,+ #[serde(skip_serializing_if = "Value::is_null")]+ params: Value,+ label: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ shortcut: Option<String>,+ enabled: bool,+ /// `Some` for toggles and radio-style choices.+ #[serde(skip_serializing_if = "Option::is_none")]+ checked: Option<bool>,+ },+ Separator,+ Submenu {+ label: String,+ children: Vec<MenuNode>,+ },+}++impl MenuNode {+ /// `id|params` — a stable key for one item (native menu ids).+ pub fn key(id: &str, params: &Value) -> String {+ if params.is_null() { id.to_string() } else { format!("{id}|{params}") }+ }+}++/// Top-level menus in order (the macOS app menu is added by the host).+pub const MENUS: &[&str] = &["File", "Edit", "View", "Photo", "Window", "Help"];++/// Order and grouping per menu: command ids, `---` separators and `@Submenu` placeholders.+/// Entries with a menu path that aren't listed are appended at the end of their menu.+const LAYOUT: &[(&str, &[&str])] = &[+ (+ "File",+ &[+ "file.addPhotos",+ "---",+ "dialog.newAlbum",+ "dialog.newFolder",+ "dialog.newSmartAlbum",+ "---",+ "file.importPresets",+ "file.exportPresets",+ "---",+ "dialog.export",+ "app.exportPrevious",+ "---",+ "library.toggleAutoWriteXmp",+ "---",+ ],+ ),+ (+ "Edit",+ &["edit.undo", "edit.redo", "---", "develop.copy", "dialog.copySettings", "develop.paste", "---", "library.selectAll", "library.selectNone"],+ ),+ (+ "View",+ &[+ "view.photoGrid",+ "view.squareGrid",+ "view.detail",+ "view.compare",+ "view.survey",+ "---",+ "view.leftPanel",+ "view.filmstrip",+ "view.histogram",+ "---",+ "view.showOriginal",+ "view.beforeAfter",+ "view.beforeAfterSplit",+ "---",+ "view.zoomIn",+ "view.zoomOut",+ "view.zoomToggle",+ "view.zoomFit",+ "view.zoom100",+ "---",+ "view.clipping",+ "view.maskOverlay",+ "view.cropOverlay",+ "---",+ "@Sort",+ "@Stacks",+ "view.filterBar",+ "library.clearFilter",+ "---",+ "compare.swap",+ "compare.makeSelect",+ ],+ ),+ (+ "Photo",+ &[+ "@Add to Album",+ "---",+ "@Set Rating",+ "@Set Flag",+ "@Set Color Label",+ "view.autoAdvance",+ "---",+ "photo.rotateLeft",+ "photo.rotateRight",+ "photo.flipHorizontal",+ "photo.flipVertical",+ "---",+ "version.create",+ "photo.virtualCopy",+ "@Stack",++ "@Photo Merge",+ "---",+ "develop.auto",+ "develop.treatment",+ "develop.reset",+ "dialog.createPreset",+ "---",+ "photo.saveMetadataToFile",+ "photo.readMetadataFromFile",+ "app.showInFinder",+ "---",+ "photo.delete",+ ],+ ),+ (+ "Window",+ &[+ "panel.edit",+ "panel.crop",+ "panel.remove",+ "panel.masking",+ "panel.redeye",+ "---",+ "panel.presets",+ "panel.versions",+ "panel.activity",+ "panel.info",+ "panel.keywords",+ "---",+ "@Edit Sections",+ "@Tools",+ ],+ ),+ ("Help", &["app.shortcuts", "---", "app.about"]),+];++/// Registry entries that are reached another way (parameterized commands are expanded into+/// submenus below; others duplicate a dialog command).+const HIDDEN: &[&str] = &[+ "photo.rate",+ "photo.flag",+ "photo.pick",+ "photo.reject",+ "photo.unflag",+ "photo.label",+ "library.sort",+ "album.addPhotos",+ "album.create",+ "library.import",+ "preset.create",+];++fn item(id: &str, params: Value, label: impl Into<String>, shortcut: Option<&str>, enabled: bool, checked: Option<bool>) -> MenuNode {+ MenuNode::Item { id: id.into(), params, label: label.into(), shortcut: shortcut.map(str::to_string), enabled, checked }+}++/// Checked state of toggles and radio items.+pub fn checked(app: &LightcraftApp, id: &str) -> Option<bool> {+ let u = &app.ui;+ let panel = |p: RightPanel| Some(u.right == p);+ match id {+ "view.photoGrid" => Some(u.view == ViewMode::PhotoGrid),+ "view.squareGrid" => Some(u.view == ViewMode::SquareGrid),+ "view.detail" => Some(u.view == ViewMode::Detail),+ "view.compare" => Some(u.view == ViewMode::Compare),+ "view.survey" => Some(u.view == ViewMode::Survey),+ "view.leftPanel" => Some(u.left_panel),+ "view.filmstrip" => Some(u.filmstrip),+ "view.histogram" => Some(u.histogram),+ "view.clipping" => Some(u.show_clipping),+ "view.maskOverlay" => Some(u.mask_overlay),+ "view.showOriginal" => Some(u.before_after == crate::state::BeforeAfter::Original),+ "view.beforeAfter" => Some(u.before_after == crate::state::BeforeAfter::SideBySide),+ "view.beforeAfterSplit" => Some(u.before_after == crate::state::BeforeAfter::Split),+ "view.autoAdvance" => Some(u.auto_advance),+ "view.filterBar" => Some(u.filter_bar),+ "panel.edit" => panel(RightPanel::Edit),+ "panel.crop" => panel(RightPanel::Crop),+ "panel.remove" => panel(RightPanel::Remove),+ "panel.masking" => panel(RightPanel::Masking),+ "panel.redeye" => panel(RightPanel::RedEye),+ "panel.versions" => panel(RightPanel::Versions),+ "panel.activity" => panel(RightPanel::Activity),+ "panel.info" => panel(RightPanel::Info),+ "panel.keywords" => panel(RightPanel::Keywords),+ "panel.presets" => Some(u.presets),+ "library.toggleAutoWriteXmp" => Some(app.session.xmp.auto_write),+ _ => None,+ }+}++/// Labels that follow the state ("Undo Exposure", "Delete 3 Photos").+fn live_label(app: &LightcraftApp, id: &str, label: &str) -> String {+ let n = app.session.selection.ids.len();+ match id {+ "edit.undo" => app.session.undo.last().map(|e| format!("Undo {}", e.label)).unwrap_or_else(|| "Undo".into()),+ "edit.redo" => app.session.redo.last().map(|e| format!("Redo {}", e.label)).unwrap_or_else(|| "Redo".into()),+ "photo.delete" if n > 1 => format!("Delete {n} Photos"),+ "photo.virtualCopy" if n > 1 => format!("Create {n} Virtual Copies"),+ _ => label.to_string(),+ }+}++/// The parameterized submenus.+fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>> {+ let active = app.session.active().and_then(|id| app.session.catalog.photo(id).cloned());+ let has = active.is_some();+ Some(match name {+ "Set Rating" => (0..=5u8)+ .map(|r| {+ let label = if r == 0 { "None".to_string() } else { "★".repeat(r as usize) };+ let sc = ["0", "1", "2", "3", "4", "5"][r as usize];+ item("photo.rate", json!({"rating": r}), label, Some(sc), has, Some(active.as_ref().is_some_and(|p| p.rating == r)))+ })+ .collect(),+ "Set Flag" => [+ ("pick", "Pick", "P", lightcraft_catalog::Flag::Pick),+ ("reject", "Reject", "X", lightcraft_catalog::Flag::Reject),+ ("none", "Unflagged", "U", lightcraft_catalog::Flag::None),+ ]+ .into_iter()+ .map(|(f, label, sc, flag)| {+ item("photo.flag", json!({"flag": f}), label, Some(sc), has, Some(active.as_ref().is_some_and(|p| p.flag == flag)))+ })+ .collect(),+ "Set Color Label" => {+ let mut v: Vec<MenuNode> = lightcraft_catalog::ColorLabel::ALL+ .iter()+ .zip([Some("6"), Some("7"), Some("8"), Some("9"), None])+ .map(|(l, sc)| {+ let name = format!("{l:?}");+ item(+ "photo.label",+ json!({"label": name.to_lowercase()}),+ name,+ sc,+ has,+ Some(active.as_ref().is_some_and(|p| p.label == Some(*l))),+ )+ })+ .collect();+ v.push(MenuNode::Separator);+ v.push(item("photo.label", json!({"label": "none"}), "None", None, has, Some(active.as_ref().is_some_and(|p| p.label.is_none()))));+ v+ }+ "Sort" => {+ use lightcraft_catalog::SortKey::*;+ let cur = app.session.sort;+ let mut v: Vec<MenuNode> = [+ ("Capture Date", CaptureDate, "captureDate"),+ ("Import Date", ImportDate, "importDate"),+ ("Modified Date", EditDate, "editDate"),+ ("File Name", FileName, "fileName"),+ ("Rating", Rating, "rating"),+ ("File Size", FileSize, "fileSize"),+ ]+ .into_iter()+ .map(|(label, key, k)| item("library.sort", json!({"key": k}), label, None, true, Some(cur.key == key)))+ .collect();+ v.push(MenuNode::Separator);+ v.push(item("library.sort", json!({"ascending": true}), "Ascending", None, true, Some(cur.ascending)));+ v.push(item("library.sort", json!({"ascending": false}), "Descending", None, true, Some(!cur.ascending)));+ v+ }+ "Add to Album" => {+ let sel = !app.session.selection.ids.is_empty() || has;+ let mut albums: Vec<_> = app.session.catalog.albums().filter(|a| !a.folder && !a.is_smart()).map(|a| (a.name.clone(), a.id.0)).collect();+ albums.sort_by_key(|(n, _)| n.to_lowercase());+ let mut v: Vec<MenuNode> =+ albums.into_iter().map(|(name, id)| item("album.addPhotos", json!({"id": id}), name, None, sel, None)).collect();+ if !v.is_empty() {+ v.push(MenuNode::Separator);+ }+ v.push(item("dialog.newAlbum", Value::Null, "New Album…", None, true, None));+ v+ }+ _ => return None,+ })+}++fn node(app: &LightcraftApp, e: &MenuEntry) -> MenuNode {+ item(&e.id, Value::Null, live_label(app, &e.id, &e.label), e.shortcut.as_deref(), e.enabled, checked(app, &e.id))+}++/// Drop leading, trailing and doubled separators (also inside submenus) and empty submenus.+fn tidy(v: Vec<MenuNode>) -> Vec<MenuNode> {+ let mut out: Vec<MenuNode> = Vec::with_capacity(v.len());+ for n in v {+ let n = match n {+ MenuNode::Submenu { label, children } => {+ let children = tidy(children);+ if children.is_empty() {+ continue;+ }+ MenuNode::Submenu { label, children }+ }+ n => n,+ };+ if n == MenuNode::Separator && out.last().is_none_or(|l| *l == MenuNode::Separator) {+ continue;+ }+ out.push(n);+ }+ while out.last() == Some(&MenuNode::Separator) {+ out.pop();+ }+ out+}++/// The whole menu bar: (title, items) per menu in [`MENUS`] order.+pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec<MenuNode>)> {+ let entries: Vec<MenuEntry> = crate::menus::menu_entries(app).into_iter().filter(|e| !HIDDEN.contains(&e.id.as_str())).collect();+ let mut used = vec![false; entries.len()];+ let mut bar = Vec::new();+ for title in MENUS {+ let layout = LAYOUT.iter().find(|(t, _)| t == title).map(|(_, l)| *l).unwrap_or(&[]);+ let mut items = Vec::new();+ let sub = |name: &str, used: &mut [bool]| -> Vec<MenuNode> {+ let mut children = expanded(app, name).unwrap_or_default();+ let mut dialogs = Vec::new();+ for (i, e) in entries.iter().enumerate() {+ if !used[i] && e.menu.len() == 2 && e.menu[0] == *title && e.menu[1] == name {+ used[i] = true;+ // commands that open a dialog go last, after a separator+ if e.label.ends_with('…') { dialogs.push(node(app, e)) } else { children.push(node(app, e)) }+ }+ }+ if !dialogs.is_empty() {+ children.push(MenuNode::Separator);+ children.extend(dialogs);+ }+ children+ };+ for slot in layout {+ if *slot == "---" {+ items.push(MenuNode::Separator);+ } else if let Some(name) = slot.strip_prefix('@') {+ let children = sub(name, &mut used);+ items.push(MenuNode::Submenu { label: name.to_string(), children });+ } else if let Some(i) = entries.iter().position(|e| e.id == *slot && e.menu.first().map(String::as_str) == Some(title)) {+ used[i] = true;+ items.push(node(app, &entries[i]));+ }+ }+ // everything else that names this menu+ items.push(MenuNode::Separator);+ let mut extra_subs: Vec<String> = Vec::new();+ for (i, e) in entries.iter().enumerate() {+ if used[i] || e.menu.first().map(String::as_str) != Some(title) {+ continue;+ }+ if e.menu.len() == 1 {+ used[i] = true;+ items.push(node(app, e));+ } else if !extra_subs.contains(&e.menu[1]) {+ extra_subs.push(e.menu[1].clone());+ }+ }+ for name in extra_subs {+ let children = sub(&name, &mut used);+ items.push(MenuNode::Submenu { label: name, children });+ }+ bar.push((title.to_string(), tidy(items)));+ }+ bar+}++/// Run a menu item. Rating, flag and label items behave like their keys (the active photo only in+/// Compare/Survey; Auto Advance moves on).+pub fn run_item(app: &mut LightcraftApp, id: &str, params: Value) -> Result<Value, String> {+ let mut params = if params.is_null() { json!({}) } else { params };+ let culling_cmd = matches!(id, "photo.rate" | "photo.flag" | "photo.label" | "photo.pick" | "photo.reject" | "photo.unflag");+ if culling_cmd {+ crate::panels::compare::target_active(app, &mut params);+ }+ let r = app.run(id, params);+ if culling_cmd && r.is_ok() && app.ui.auto_advance {+ crate::panels::compare::advance(app);+ }+ r+}++/// Human-readable shortcut text for menus: `Cmd+Shift+Z` → `⌘⇧Z` on macOS, `Ctrl+Shift+Z` elsewhere.+pub fn shortcut_text(sc: &str, mac: bool) -> String {+ if mac {+ let mut mods = String::new();+ let mut key = "";+ for part in sc.split('+') {+ match part {+ "Ctrl" => mods.push('⌃'),+ "Alt" => mods.push('⌥'),+ "Shift" => mods.push('⇧'),+ "Cmd" => mods.push('⌘'),+ k => key = k,+ }+ }+ let key = match key {+ "Delete" => "⌫",+ "Escape" => "⎋",+ "Left" => "←",+ "Right" => "→",+ k => k,+ };+ format!("{mods}{key}")+ } else {+ sc.replace("Cmd", "Ctrl")+ }+}++/// Width of the in-window menu bar's titles.+pub fn bar_width(ui: &egui::Ui) -> f32 {+ let t = crate::theme::Tokens::get(ui.ctx());+ MENUS.iter().map(|m| ui.painter().layout_no_wrap(m.to_string(), t.font(13.0), t.text).size().x + 16.0).sum::<f32>()+ + ui.spacing().item_spacing.x * MENUS.len() as f32+}++/// The in-window menu bar (hosts without a native one): one dropdown per menu, or a single+/// "Menu" button when the space is too narrow. Returns the width used.+pub fn show_in_window(app: &mut LightcraftApp, ui: &mut egui::Ui, max_width: f32) -> f32 {+ let t = crate::theme::Tokens::get(ui.ctx());+ let bar = menu_bar(app);+ let font = t.font(13.0);+ let widths: Vec<f32> = bar.iter().map(|(title, _)| ui.painter().layout_no_wrap(title.clone(), font.clone(), t.text).size().x + 16.0).collect();+ let total: f32 = widths.iter().sum();+ let mut clicked: Option<(String, Value)> = None;+ let start = ui.cursor().left();+ let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac;+ if total <= max_width {+ for (title, items) in &bar {+ let r = ui.add(egui::Button::new(egui::RichText::new(title).font(font.clone()).color(t.text_label)).frame(false));+ crate::widgets::register(ui.ctx(), format!("menu:{title}"), r.rect);+ egui::Popup::menu(&r).show(|ui| nodes_ui(ui, items, mac, &mut clicked));+ }+ } else {+ let r = ui.add(egui::Button::new(egui::RichText::new("Menu").font(font.clone()).color(t.text_label)).frame(false));+ crate::widgets::register(ui.ctx(), "menu:all", r.rect);+ egui::Popup::menu(&r).show(|ui| {+ for (title, items) in &bar {+ ui.menu_button(title, |ui| nodes_ui(ui, items, mac, &mut clicked));+ }+ });+ }+ if let Some((id, params)) = clicked {+ let _ = run_item(app, &id, params);+ }+ ui.cursor().left() - start+}++fn nodes_ui(ui: &mut egui::Ui, nodes: &[MenuNode], mac: bool, clicked: &mut Option<(String, Value)>) {+ ui.set_min_width(220.0);+ for n in nodes {+ match n {+ MenuNode::Separator => {+ ui.separator();+ }+ MenuNode::Submenu { label, children } => {+ ui.menu_button(format!(" {label}"), |ui| nodes_ui(ui, children, mac, clicked));+ }+ MenuNode::Item { id, params, label, shortcut, enabled, checked } => {+ // a gutter for check marks, like native menus+ let mut b = egui::Button::new(format!(" {label}"));+ if let Some(sc) = shortcut {+ b = b.shortcut_text(shortcut_text(sc, mac));+ }+ let r = ui.add_enabled(*enabled, b);+ if *checked == Some(true) {+ let t = crate::theme::Tokens::get(ui.ctx());+ let c = egui::Rect::from_center_size(egui::pos2(r.rect.left() + 11.0, r.rect.center().y), egui::vec2(13.0, 13.0));+ crate::icons::paint(ui.painter(), c, crate::icons::Icon::Check, if *enabled { t.text } else { t.text_disabled });+ }+ if r.clicked() {+ *clicked = Some((id.clone(), params.clone()));+ ui.close();+ }+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn app() -> LightcraftApp {+ LightcraftApp::new(lightcraft_engine::Session::with_demo(), Default::default())+ }++ fn find<'a>(nodes: &'a [MenuNode], id: &str) -> Option<&'a MenuNode> {+ nodes.iter().find_map(|n| match n {+ MenuNode::Item { id: i, .. } if i == id => Some(n),+ MenuNode::Submenu { children, .. } => find(children, id),+ _ => None,+ })+ }++ #[test]+ fn bar_follows_the_registry_and_state() {+ let mut app = app();+ let bar = menu_bar(&app);+ let titles: Vec<&str> = bar.iter().map(|(t, _)| t.as_str()).collect();+ assert_eq!(titles, MENUS);+ let all: Vec<MenuNode> = bar.iter().flat_map(|(_, v)| v.clone()).collect();+ // every engine command with a menu path is reachable (parameterized ones via submenus)+ for c in lightcraft_engine::command_specs().iter().filter(|c| !c.menu.is_empty() && !HIDDEN.contains(&c.id)) {+ assert!(find(&all, c.id).is_some(), "{} missing from the menu bar", c.id);+ }+ for id in ["photo.rate", "photo.flag", "photo.label", "library.sort", "album.addPhotos", "view.compare", "stack.group", "photo.virtualCopy"] {+ assert!(find(&all, id).is_some(), "{id}");+ }+ // no doubled or dangling separators+ fn check(v: &[MenuNode]) {+ assert_ne!(v.first(), Some(&MenuNode::Separator));+ assert_ne!(v.last(), Some(&MenuNode::Separator));+ for w in v.windows(2) {+ assert!(!(w[0] == MenuNode::Separator && w[1] == MenuNode::Separator));+ }+ for n in v {+ if let MenuNode::Submenu { children, .. } = n {+ check(children);+ }+ }+ }+ bar.iter().for_each(|(_, v)| check(v));+ // live state: undo label, enabled, checked+ let Some(MenuNode::Item { enabled, .. }) = find(&all, "edit.undo") else { panic!() };+ assert!(!enabled);+ run_item(&mut app, "photo.rate", json!({"rating": 3})).unwrap();+ let bar = menu_bar(&app);+ let all: Vec<MenuNode> = bar.iter().flat_map(|(_, v)| v.clone()).collect();+ let Some(MenuNode::Item { label, enabled, .. }) = find(&all, "edit.undo") else { panic!() };+ assert_eq!((label.as_str(), *enabled), ("Undo Set Rating", true));+ let rated: Vec<_> = all+ .iter()+ .filter_map(|n| match n {+ MenuNode::Submenu { label, children } if label == "Set Rating" => Some(children.clone()),+ _ => None,+ })+ .flatten()+ .filter(|n| matches!(n, MenuNode::Item { checked: Some(true), .. }))+ .collect();+ assert!(matches!(&rated[..], [MenuNode::Item { params, .. }] if params["rating"] == 3));+ let Some(MenuNode::Item { checked, .. }) = find(&all, "view.filmstrip") else { panic!() };+ assert_eq!(*checked, Some(app.ui.filmstrip));+ }++ #[test]+ fn shortcut_text_per_platform() {+ assert_eq!(shortcut_text("Cmd+Shift+Z", true), "⌘⇧Z");+ assert_eq!(shortcut_text("Cmd+Shift+Z", false), "Ctrl+Shift+Z");+ assert_eq!(shortcut_text("Delete", true), "⌫");+ }+}diff --cc crates/ui-egui/src/menus.rsindex fffb9b928,b11cd6eda..e0cc0d107--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -35,36 -30,37 +35,39 @@@ pub const UI_COMMANDS: &[UiCommand] = &("view.histogram", "Histogram", Some("Cmd+Shift+H"), "View"),("view.maskOverlay", "Show Mask Overlay", Some("O"), "View"),("view.cropOverlay", "Cycle Crop Overlay", Some("Shift+O"), "View"),- ("view.back", "Back to Grid", Some("Escape"), "View"),- ("view.filterBar", "Filter", None, "View"),- ("panel.edit", "Edit", Some("E"), "View"),- ("panel.crop", "Crop & Rotate", Some("C"), "View"),- ("panel.remove", "Remove", Some("H"), "View"),- ("panel.masking", "Masking", Some("M"), "View"),- ("panel.redeye", "Red Eye", None, "View"),- ("panel.presets", "Presets", Some("Shift+P"), "View"),- ("panel.info", "Info", Some("I"), "View"),- ("panel.keywords", "Keywords", Some("K"), "View"),- ("panel.versions", "Versions", Some("Shift+V"), "View"),- ("panel.activity", "History", None, "View"),- ("panel.close", "Close Panel", None, "View"),- ("section.light", "Light", Some("Cmd+Alt+1"), "View"),- ("section.color", "Color", Some("Cmd+Alt+2"), "View"),- ("section.effects", "Effects", Some("Cmd+Alt+3"), "View"),- ("section.detail", "Detail", Some("Cmd+Alt+4"), "View"),- ("section.optics", "Optics", Some("Cmd+Alt+5"), "View"),- ("tool.brush", "Brush", Some("B"), "View"),- ("tool.linear", "Linear Gradient", Some("L"), "View"),- ("tool.radial", "Radial Gradient", Some("R"), "View"),- ("tool.wbPicker", "White Balance Selector", Some("W"), "View"),- ("tool.none", "No Tool", None, "View"),+ ("view.back", "Back to Grid", Some("Escape"), ""),+ ("view.filterBar", "Filter Bar", Some("Shift+F"), "View"),+ ("panel.edit", "Edit", Some("E"), "Window"),+ ("panel.crop", "Crop & Rotate", Some("C"), "Window"),+ ("panel.remove", "Remove", Some("H"), "Window"),+ ("panel.masking", "Masking", Some("M"), "Window"),+ ("panel.redeye", "Red Eye", None, "Window"),+ ("panel.presets", "Presets", Some("Shift+P"), "Window"),+ ("panel.info", "Info", Some("I"), "Window"),+ ("panel.keywords", "Keywords", Some("K"), "Window"),+ ("panel.versions", "Versions", Some("Shift+V"), "Window"),+ ("panel.activity", "History", None, "Window"),+ ("panel.close", "Close Panel", None, ""),+ ("section.light", "Light", Some("Cmd+Alt+1"), "Window>Edit Sections"),+ ("section.color", "Color", Some("Cmd+Alt+2"), "Window>Edit Sections"),+ ("section.effects", "Effects", Some("Cmd+Alt+3"), "Window>Edit Sections"),+ ("section.detail", "Detail", Some("Cmd+Alt+4"), "Window>Edit Sections"),+ ("section.optics", "Optics", Some("Cmd+Alt+5"), "Window>Edit Sections"),+ ("tool.brush", "Brush", Some("B"), "Window>Tools"),+ ("tool.linear", "Linear Gradient", Some("L"), "Window>Tools"),+ ("tool.radial", "Radial Gradient", Some("R"), "Window>Tools"),+ ("tool.wbPicker", "White Balance Selector", Some("W"), "Window>Tools"),+ ("tool.none", "No Tool", None, ""),("dialog.newAlbum", "New Album…", Some("Cmd+N"), "File"),("dialog.newFolder", "New Folder…", Some("Cmd+Shift+N"), "File"),+ ("dialog.newSmartAlbum", "New Smart Album from Filter…", Some("Cmd+Alt+N"), "File"),("dialog.createPreset", "Create Preset…", Some("Cmd+Shift+P"), "Photo"),- ("dialog.copySettings", "Choose Edit Settings to Copy…", Some("Cmd+Shift+C"), "Photo"),+ ("dialog.autoStack", "Auto-Stack by Capture Time…", None, "Photo>Stack"),+ ("dialog.copySettings", "Choose Edit Settings to Copy…", Some("Cmd+Shift+C"), "Edit"),("dialog.export", "Export…", Some("Cmd+Shift+E"), "File"),- ("dialog.mergeHdr", "Photo Merge ▸ HDR…", Some("Ctrl+H"), "Photo"),- ("dialog.mergePanorama", "Photo Merge ▸ Panorama…", Some("Ctrl+M"), "Photo"),- ("dialog.mergeHdrPanorama", "Photo Merge ▸ HDR Panorama…", None, "Photo"),++ ("dialog.mergeHdr", "HDR…", Some("Ctrl+H"), "Photo>Photo Merge"),++ ("dialog.mergePanorama", "Panorama…", Some("Ctrl+M"), "Photo>Photo Merge"),++ ("dialog.mergeHdrPanorama", "HDR Panorama…", None, "Photo>Photo Merge"),("file.addPhotos", "Add Photos…", Some("Cmd+Shift+I"), "File"),("file.importPresets", "Import Presets…", None, "File"),("file.exportPresets", "Export Presets…", None, "File"),@@@ -433,8 -407,7 +439,9 @@@ pub fn ui_enabled(app: &LightcraftApp,.is_some_and(|p| matches!(p.source, lightcraft_engine::catalog::Source::File { .. }))}"file.exportPresets" => app.session.presets.iter().any(|p| !p.builtin),+ "view.compare" => app.session.catalog.len() > 1,+ "compare.swap" | "compare.makeSelect" => app.ui.view == ViewMode::Compare,+ s if s.starts_with("dialog.merge") => app.session.targets(&serde_json::json!({})).len() >= 2 && app.merge.final_task.is_none(),_ => true,}}diff --cc docs/merge.mdindex 000000000,b802bacf4..600eb840fmode 000000,100644..100644--- a/docs/merge.md+++ b/docs/merge.md@@@ -1,0 -1,63 +1,64 @@@+ # Photo Merge (HDR, Panorama, HDR Panorama)++ `crates/merge` (layer L3, no UI dependencies) implements the algorithms; `crates/engine/src/merge.rs`+ plans, runs and finishes merges in the library; the desktop UI shows a dialog with a live preview.+ All algorithms are our own implementations from published papers (cited in the module docs).++ ## Using it++ - **App:** select the photos, then *Photo Merge ▸ HDR…* (`Ctrl+H`), *Panorama…* (`Ctrl+M`) or+ *HDR Panorama…* from the photo context menu (or the `dialog.merge*` commands). The dialog previews+ the merge at ≤ 1024 px and re-runs the preview when an option changes; *Merge* runs the full merge+ in the background (progress in a toast). The result is written next to the first photo as+ `<name>-HDR.dng`, `-Pano.dng` or `-HDR-Pano.dng`, imported and selected.+ - **Commands** (CLI, MCP, control channel):+ - `merge.hdr {ids?, align=true, deghost=none|low|medium|high, autoSettings=true, stack=false, preview=false, showOverlay=false, previewPath?}`+ - `merge.panorama {ids?, projection=auto|spherical|cylindrical|perspective, boundaryWarp=0..100, autoCrop=false, fillEdges=false, autoSettings=true, maxMegapixels=40, preview, previewPath?}`+ - `merge.hdrPanorama {ids?, bracket=0 (from EXIF), …both sets of options}`+ - **CLI:** `lightcraft-cli merge hdr|panorama|hdr-panorama [options] FILES…`;+ `lightcraft-cli synth-merge hdr|panorama -o DIR` writes synthetic inputs (procedural scene).++ ## What it does++ **HDR** (`hdr.rs`): frames ordered by EXIF exposure (or median luminance); the middle one is the+ reference. Auto Align: features on exposure-normalised luminance, RANSAC translation / similarity /+ homography (the simplest model that explains ≥ 97 % of the matches). Exposure ratios are measured+ (median log ratio of well-exposed pixels between brightness neighbours), EXIF is the fallback.+ Radiance is a weighted mean in linear light, weight `k · (1 − smoothstep(0.8·clip, 0.96·clip, max+ channel))`. Deghost: a per-pixel consistency test against the reference radiance (with a noise+ floor), dilated and feathered masks; the union is the deghost overlay. Output: 16-bit float DNG.++ **Panorama** (`pano/`): MOPS-style features, pairwise RANSAC homographies with Brown & Lowe's+ verification, focal from homographies (or EXIF 35 mm), rotations chained along a maximum spanning+ tree, Levenberg–Marquardt bundle adjustment of rotations + focal lengths, straightening.+ Projections: spherical, cylindrical, perspective; *Auto* picks perspective for compact fields of+ view < 110°, cylindrical when the vertical field is < 90°, else spherical. Exposure: EXIF, then+ gain compensation from the overlaps. Seams: each pixel goes to the image with the highest+ centre-weighted feather weight; multi-band blending (Laplacian pyramids) in log space. Boundary+ Warp: a separable stretch of the smoothed valid-area edges to the canvas edges. Auto Crop: the+ largest rectangle of image data (set as the develop crop, so it stays adjustable). Fill Edges:+ push–pull diffusion. Output: 16-bit integer DNG (16-bit float for HDR panoramas).++ **DNG output** (`output.rs`): LinearRaw, 3 samples, Deflate tiles; values scaled below 1.0 with the+ scale in `BaselineExposure`; raw sources keep their DNG colour tags (camera RGB), other sources get+ `ColorMatrix1`/`ForwardMatrix1` of their RGB space.++ ## Measured (synthetic tests, `cargo test -p lightcraft-merge`)++ - HDR, 3 brackets ±2 EV with 14-bit noise and handheld shifts: alignment error < 0.3 px, exposure+ error < 0.02 EV, radiance median log error < 0.03 (noise-limited, bias < 0.01), recovered+ highlights < 0.05; moving object: ghost error 0.2–2.0 without deghosting, < 0.06 with High.+ - Panorama, 5 views over 182° with a 1.3× exposure drift: relative rotations < 0.1°, focal < 1 %,+ BA RMS ≈ 0.35 px; median log error vs ground truth < 0.02; no seam steps.++ ## Limits (known gaps)++ - No lens-distortion model in the panorama bundle adjustment (rectilinear lenses assumed); no+ 360° wrap-around; flat (translating-camera) scans are fitted with the rotation model.+ - No camera response calibration for JPEG brackets (sRGB decoding is taken as linear light).+ - Boundary Warp is a separable stretch, not a content-preserving mesh warp; Fill Edges is diffusion,+ not patch synthesis.-- *Create Stack*: LightCraft has no stacks yet; the result's caption lists its sources.++- *Create Stack*: the result goes on top of a collapsed stack of its sources (`Catalog::stack_with_ops`); its++ caption also lists them.+ - Panorama output is limited to `maxMegapixels` (default 40) — blending memory is ~25 bytes/pixel.+ - The browser build has no file access for merges yet.diff --cc docs/parity.mdindex dc1a3ccdc,cd80f25df..19d1af2d2--- a/docs/parity.md+++ b/docs/parity.md@@@ -45,10 -45,10 +45,10 @@@ and prints the summary; `cargo xtask pa| V. Preferences (PREF) | 0 | 3 | 5 | 3 | 0/1 (0%) | 0/4 (0%) || W. Cloud & AI infrastructure (CLOUD / AI) | 0 | 1 | 1 | 2 | — | — || X. Cross-cutting behaviours (BEHAV) | 10 | 2 | 5 | 1 | 7/8 (88%) | 3/5 (60%) |-| Y. Menus | 42 | 19 | 24 | 8 | 37/47 (79%) | 3/23 (13%) |-| Z. Keyboard shortcuts (desktop) | 45 | 16 | 19 | 1 | 39/52 (75%) | 6/23 (26%) |-| Lightroom Classic extras | 1 | 17 | 61 | 9 | — | 1/21 (5%) |-| **Total** | 190 | 107 | 203 | 37 | 150/198 (76%) | 34/144 (24%) |+| Y. Menus | 46 | 18 | 21 | 8 | 37/47 (79%) | 7/23 (30%) |+| Z. Keyboard shortcuts (desktop) | 46 | 16 | 18 | 1 | 39/52 (75%) | 7/23 (30%) |+| Lightroom Classic extras | 4 | 19 | 56 | 9 | — | 3/21 (14%) |- | **Total** | 205 | 103 | 192 | 37 | 152/198 (77%) | 48/144 (33%) |++| **Total** | 208 | 103 | 189 | 37 | 152/198 (77%) | 48/144 (33%) |<!-- /parity:summary -->## Top gaps@@@ -401,9 -407,9 +401,9 @@@ under the UI command that wraps it (a n| Id | Feature | Tier | Status | Evidence | Missing / notes ||---|---|---|---|---|---|- | LR-MERGE-HDR | HDR merge | P2 | ⬜ | | |- | LR-MERGE-PANO | Panorama | P2 | ⬜ | | |- | LR-MERGE-HDRPANO | HDR panorama | P2 | ⬜ | | |-| LR-MERGE-HDR | HDR merge | P2 | ✅ | `cmd:merge.hdr`, `cmd:dialog.mergeHdr` | auto align, deghost None–High + overlay, auto settings, float DNG; no Create Stack yet (no stacks), JPEG brackets treated as linear |++| LR-MERGE-HDR | HDR merge | P2 | ✅ | `cmd:merge.hdr`, `cmd:dialog.mergeHdr` | auto align, deghost None–High + overlay, auto settings, float DNG, Create Stack; JPEG brackets treated as linear |+ | LR-MERGE-PANO | Panorama | P2 | ✅ | `cmd:merge.panorama`, `cmd:dialog.mergePanorama` | spherical/cylindrical/perspective + auto, boundary warp, auto crop, fill edges (diffusion), DNG; no lens model / 360° wrap |+ | LR-MERGE-HDRPANO | HDR panorama | P2 | ✅ | `cmd:merge.hdrPanorama`, `cmd:dialog.mergeHdrPanorama` | brackets grouped by EXIF || LR-MERGE-HEADLESS | Merge with last settings | P2 | ⬜ | | |## P. Enhance (ENH)