Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Merge edit-panel parity (Point Color, Calibration, curve refine saturation + targeted adjustment, red/pet eye, visualize spots)

Brandon Thomas64dfa8adbdd4
diff --cc crates/engine/src/cmd/mod.rs
index 623313490,d4c811bf0..5d48e7d88
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@@ -102,8 -102,8 +103,9 @@@ pub fn command_specs() -> &'static [Com
v.extend(edit::specs());
v.extend(library::specs());
v.extend(develop::specs());
+ v.extend(color::specs());
v.extend(masks::specs());
+ v.extend(merge::specs());
v.extend(query::specs());
v.extend(xmp::specs());
v.extend(preset_files::specs());
diff --cc crates/engine/src/media.rs
index 91e13b3aa,99fd35214..f0b579c03
--- a/crates/engine/src/media.rs
+++ b/crates/engine/src/media.rs
@@@ -246,6 -228,17 +246,21 @@@ impl RenderJob
self
}
+ /// Draw a diagnostic overlay over the result (e.g. Point Color's visualized range). Gets its
+ /// own result key.
+ pub fn with_overlay(mut self, overlay: lightcraft_pipeline::Overlay) -> Self {
+ if self.request.overlay != overlay {
+ self.key ^= self.request.overlay.key().wrapping_mul(0x9e37_79b9_7f4a_7c15);
+ self.request.overlay = overlay;
+ self.key ^= overlay.key().wrapping_mul(0x9e37_79b9_7f4a_7c15);
+ }
++ // a diagnostic view (visualized range / spots) must never become the photo's cached preview
++ if overlay != lightcraft_pipeline::Overlay::None {
++ self.view_cache = None;
++ }
+ self
+ }
+
/// Reuse `stages` across this view's renders.
pub fn with_stages(mut self, stages: Arc<StageCache>) -> Self {
self.stages = Some(stages);
diff --cc crates/engine/src/merge.rs
index 608928edc,000000000..f12ff9408
mode 100644,000000..100644
--- a/crates/engine/src/merge.rs
+++ b/crates/engine/src/merge.rs
@@@ -1,408 -1,0 +1,408 @@@
+//! 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`).
+ 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 req = RenderRequest { quality: Quality::Full, apply_crop: false, ..RenderRequest::fit(edge, edge) };
+ 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)))?;
+ 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/ui-egui/src/panels/detail.rs
index 012c4479c,e8c6b1935..dc3aaad8f
--- a/crates/ui-egui/src/panels/detail.rs
+++ b/crates/ui-egui/src/panels/detail.rs
@@@ -156,39 -151,13 +165,40 @@@ pub fn show(app: &mut LightcraftApp, ui
let scale = if interacting { 0.6 } else { 1.0 };
let want = (img_rect.width().max(img_rect.height()) * ppp * scale).min(2560.0) as usize;
let (rw, rh) = if aspect >= 1.0 { (want, (want as f32 / aspect) as usize) } else { ((want as f32 * aspect) as usize, want) };
- if let Some(job) = app.session.render_job(id, rw.max(8), rh.max(8), false, !crop_tool) {
+ if let Some(job) = app.session.loupe_job(id, rw.max(8), rh.max(8), !crop_tool) {
let job = if interacting { job.draft() } else { job };
+ let job = job.with_overlay(view_overlay(app, &d));
app.renderer.request(Slot::Main, job, 100);
}
+ // once this photo is on screen: prepare its neighbours in filmstrip order (source decoded and
+ // kept, view render cached) so stepping to them is instant
+ if !interacting && !app.renderer.is_pending(Slot::Main) && app.renderer.textures.get(&Slot::Main).is_some_and(|t| t.photo == id) {
+ let ids = app.session.visible_cloned();
+ if let Some(i) = ids.iter().position(|p| *p == id) {
+ let next = ids.get(i + 1).copied();
+ let prev = i.checked_sub(1).and_then(|j| ids.get(j)).copied();
+ for (n, nid) in [next, prev].into_iter().enumerate() {
+ let Some(nid) = nid else { continue };
+ let Some(np) = app.session.catalog.photo(nid).cloned() else { continue };
+ let nf = Frame::with_lens(np.width.max(1) as usize, np.height.max(1) as usize, &np.develop, !crop_tool, np.embedded_lens.as_ref());
+ let na = nf.aspect() as f32;
+ let nr = fit_rect(main_area, na, app.ui.zoom, [np.width.max(1) as usize, np.height.max(1) as usize], ppp, app.ui.pan);
+ let nw = (nr.width().max(nr.height()) * ppp).min(2560.0) as usize;
+ let (w, h) = if na >= 1.0 { (nw, (nw as f32 / na) as usize) } else { ((nw as f32 * na) as usize, nw) };
+ if let Some(job) = app.session.loupe_job(nid, w.max(8), h.max(8), !crop_tool) {
+ app.renderer.prefetch(Slot::Prefetch(n as u8), job, PREFETCH_PRIORITY);
+ }
+ }
+ }
+ }
+ // until the loupe has this photo: show its cached render / embedded preview / a thumbnail
+ if app.renderer.textures.get(&Slot::Main).is_none_or(|t| t.photo != id)
+ && let Some(q) = app.session.quick_view_job(id, want.max(8), !crop_tool)
+ {
+ app.renderer.request_quick(Slot::Preview, q, 110);
+ }
let show_before = app.ui.before_after == BeforeAfter::Original || ui.input(|i| i.key_down(egui::Key::Backslash));
- if (split || show_before || app.ui.before_after == BeforeAfter::Split)
+ if (split || show_before || split_view)
&& let Some(job) = app.session.render_job(id, rw.max(8), rh.max(8), true, !crop_tool)
{
app.renderer.request(Slot::Before, job, 90);
@@@ -258,18 -210,51 +269,63 @@@
resp.context_menu(|ui| super::grid::context_menu(app, ui, id));
}
+/// Neighbour prefetch: below on-screen thumbnails, above background thumbnail refreshes.
+const PREFETCH_PRIORITY: u32 = 4;
+
+fn quick_name(q: lightcraft_engine::media::QuickSource) -> &'static str {
+ use lightcraft_engine::media::QuickSource;
+ match q {
+ QuickSource::Cached => "cached",
+ QuickSource::Embedded => "embedded",
+ QuickSource::Small => "small",
+ }
+}
+
+ /// Targeted adjustment tool: dragging up/down on the photo raises/lowers the tone-curve region or
+ /// the colour-mixer bands under the press point (`develop.targeted`, one call per whole step, all
+ /// in one interaction = one undo step).
+ fn targeted_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, resp: &egui::Response, map: &CanvasMap, target: &str) {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
+ if resp.drag_started()
+ && let Some(q) = resp.interact_pointer_pos()
+ {
+ let _ = app.run("develop.beginInteraction", json!({"label": "Targeted Adjustment"}));
+ app.gesture = Some(Gesture::Targeted { at: map.norm(q), acc: 0.0 });
+ }
+ if resp.dragged()
+ && let Some(Gesture::Targeted { at, acc }) = &mut app.gesture
+ {
+ *acc -= resp.drag_delta().y * 0.5;
+ let step = acc.trunc();
+ if step != 0.0 {
+ *acc -= step;
+ let at = *at;
+ let mut p = json!({"target": target, "x": at.x, "y": at.y, "delta": step});
+ if target == "curve" && app.ui.curve_channel != "parametric" {
+ p["channel"] = json!(app.ui.curve_channel);
+ }
+ let _ = app.run("develop.targeted", p);
+ }
+ }
+ if resp.drag_stopped() && matches!(app.gesture, Some(Gesture::Targeted { .. })) {
+ app.gesture = None;
+ let _ = app.run("develop.endInteraction", json!({}));
+ }
+ }
+
+ /// The diagnostic overlay the loupe shows (Point Color's visualized range).
+ fn view_overlay(app: &LightcraftApp, d: &DevelopSettings) -> lightcraft_pipeline::Overlay {
+ use lightcraft_pipeline::Overlay;
+ if app.ui.right == RightPanel::Remove && app.ui.visualize_spots {
+ return Overlay::Spots(app.ui.spots_threshold.clamp(0.0, 100.0).round() as u8);
+ }
+ let edit = app.ui.right == RightPanel::Edit;
+ if edit && app.ui.point_color_visualize && app.ui.flyout_open("pointColor") && app.ui.point_color < d.point_colors.len() {
+ return Overlay::PointColorRange(app.ui.point_color as u8);
+ }
+ Overlay::None
+ }
+
fn clipping_overlay(app: &LightcraftApp, p: &egui::Painter, r: Rect) {
// Highlight clipped regions using the histogram's extremes isn't spatial; show a subtle frame hint.
if let Some(h) = app.renderer.textures.get(&Slot::Main).and_then(|t| t.histogram.as_ref()) {