LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Merge storytold/main into fix/2682-video-thumbnails
insideTheFlux746917e8353e
diff --cc crates/engine/src/media/session.rsindex 000000000,d160b216d..47db7837bmode 000000,100644..100644--- a/crates/engine/src/media/session.rs+++ b/crates/engine/src/media/session.rs@@@ -1,0 -1,476 +1,480 @@@+ use super::quick::{QuickJob, content_key, source_info};+ use super::render::{RenderJob, RenderResult};+ use super::source::{PreviewLoader, RENDER_CACHE_VERSION, SourceLevel, SourceRef, THUMB_SIZES, face_edge, source_edge_needed, thumb_bucket};+ use super::*;++ impl crate::Session {+ /// Build a render job for `id` fitting `max_w × max_h`. `before` renders the unedited look.+ pub fn render_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, before: bool, apply_crop: bool) -> Option<RenderJob> {+ self.build_job(id, max_w, max_h, before, apply_crop, None)+ }++ /// A grid/filmstrip thumbnail job: the long edge is rounded up to one of [`THUMB_SIZES`]+ /// (≥ `long_edge`) and the result comes from / goes to the thumbnail cache (memory + disk).++ /// `None` for a video: the image decoders can't read one, so none is asked to (issue #2682).+ pub fn thumb_job(&mut self, id: PhotoId, long_edge: usize) -> Option<RenderJob> {++ if self.catalog.photo(id).is_some_and(|p| p.is_video()) {++ return None;++ }+ let b = thumb_bucket(long_edge);+ let mut job = self.build_job(id, b, b, false, true, Some(b))?;+ // (a thumbnail may develop a smaller copy of the raw image that the file keeps)+ if let SourceRef::File { reduced, .. } = &mut job.source {+ reduced.clone_from(&self.media.reduced_loader);+ }+ Some(job)+ }++ fn build_job(+ &mut self,+ id: PhotoId,+ max_w: usize,+ max_h: usize,+ before: bool,+ apply_crop: bool,+ thumb_bucket: Option<usize>,+ ) -> Option<RenderJob> {+ let p = self.catalog.photo(id)?.clone();+ let settings = if before { Arc::new(self.before_settings(&p)) } else { p.develop.clone() };+ let level = SourceLevel::for_size(if thumb_bucket.is_some() {+ max_w.max(max_h) // (grid thumbnails of tight crops stay cheap)+ } else {+ source_edge_needed(&p, &settings, apply_crop, max_w.max(max_h))+ });+ let source = self.media.source_ref(&p, level);+ let request = RenderRequest { apply_crop, ..RenderRequest::fit(max_w, max_h) };+ // the photo id is part of the key: two photos with the same settings and size must not+ // share a result (a view slot showing photo A would otherwise look current for photo B)+ // …and so is the file's content: a file changed on disk (Reload) renders afresh+ let content_key = content_key(&p);+ let source_key = Hasher128::new().str(&content_key).finish();+ let content = source_key.0 as u64;+ // Temporary "before" settings must not replace the photo's cached develop hash.+ let settings_hash = if before { settings.hash64() } else { self.media.settings_hashes.get(id, &settings) };+ let salt = self.media.denoise_salt(id, &settings);+ let key = settings_hash+ ^ ((max_w as u64) << 40)+ ^ ((max_h as u64) << 20)+ ^ (apply_crop as u64)+ ^ (level as u64) << 60+ ^ id.0.wrapping_mul(0x9e37_79b9_7f4a_7c15)+ ^ content.rotate_left(17)+ ^ salt;+ let cache = thumb_bucket.map(|b| {+ let mut k = Hasher128::new();+ k.str(&content_key).u64(settings_hash).u64(b as u64).u64(RENDER_CACHE_VERSION).u64(crate::camera_profiles::cache_key());+ // (only a render that uses a denoised picture has it in its key, so every other thumbnail stays valid)+ if salt != 0 {+ k.u64(salt);+ }+ (self.media.rendered.clone(), k.finish())+ });+ Some(RenderJob {+ request_id: 0,+ cache_generation: self.media.rendered.generation(),+ source_key: Some(source_key),+ photo: id,+ level,+ source,+ origin: p.source.clone(),+ info: source_info(&p),+ settings,+ request,+ key,+ cache,+ stages: None,+ view_cache: None,+ display: None,+ slide: None,+ preview_cut: None,+ display_fit: None,+ })+ }++ /// A render of `id` with `settings` in place of its own, fitting `max_w × max_h` (the loupe's+ /// temporary preview while hovering a preset or profile; nothing is committed or cached).+ pub fn preview_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool, settings: &DevelopSettings) -> Option<RenderJob> {+ let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;+ job.settings = Arc::new(settings.clone());+ job.key = settings.hash64() ^ ((max_w as u64) << 40) ^ ((max_h as u64) << 20) ^ (apply_crop as u64) ^ (job.level as u64) << 60;+ Some(job)+ }++ /// Cache key of a variant thumbnail ([`Self::variant_job`]).+ pub fn variant_key(p: &Photo, settings: &DevelopSettings, edge: usize) -> Hash128 {+ Hasher128::new()+ .str(&content_key(p))+ .str("variant")+ .u64(settings.hash64())+ .u64(edge as u64)+ .u64(RENDER_CACHE_VERSION)+ .u64(crate::camera_profiles::cache_key())+ .finish()+ }++ /// A thumbnail of `id` rendered with `settings` instead of its own (profile and preset+ /// browsers): from the thumbnail-level source, long edge `edge` (≤ 512), cropped. The result+ /// is cached (memory + the library's disk cache) under the photo's content and the settings+ /// hash, so a variant renders once; `key` is derived from the same hash, so a frontend can+ /// keep one texture per variant.+ pub fn variant_job(&mut self, id: PhotoId, settings: &DevelopSettings, edge: usize) -> Option<RenderJob> {+ let p = self.catalog.photo(id)?.clone();+ let edge = edge.clamp(16, SourceLevel::Thumb.max_edge());+ let level = SourceLevel::Thumb;+ let source = self.media.source_ref(&p, level);+ let ck = Self::variant_key(&p, settings, edge);+ Some(RenderJob {+ request_id: 0,+ cache_generation: self.media.rendered.generation(),+ source_key: Some(Hasher128::new().str(&content_key(&p)).finish()),+ photo: id,+ level,+ source,+ origin: p.source.clone(),+ info: source_info(&p),+ settings: Arc::new(settings.clone()),+ request: RenderRequest { apply_crop: true, ..RenderRequest::fit(edge, edge) },+ key: (ck.0 as u64) ^ ((ck.0 >> 64) as u64),+ cache: Some((self.media.rendered.clone(), ck)),+ stages: None,+ view_cache: None,+ display: None,+ slide: None,+ preview_cut: None,+ display_fit: None,+ })+ }++ /// A square close-up of `face` (normalized, in the photo's upright frame) for a People card: the+ /// photo's own look with its crop replaced by a square around the face (room for hair and chin),+ /// at least `edge` pixels across (rounded up to [`FACE_EDGE_STEP`], ≤ 512, so a tile size+ /// between two steps reuses the cached one). An unedited raw's tile is cut from the camera's+ /// embedded preview when that holds the square at [`crate::face_tiles::SOFT_LIMIT`] of the+ /// size asked or more ([`crate::face_tiles`]); else, and for every other photo, the source+ /// level is the smallest that keeps the face sharp, up to the preview. Cached (memory and the+ /// library's thumbnail cache on disk) like [`Self::variant_job`], and `key` likewise follows+ /// the content: a later launch shows the tile without reading the original.+ pub fn face_job(&mut self, id: PhotoId, face: lightcraft_geom::Rect, edge: usize) -> Option<RenderJob> {+ let p = self.catalog.photo(id)?.clone();+ // `face` is on the upright (EXIF-oriented) photo; the crop below is in the frame after the+ // user's Rotate Left/Right, so carry the box (and the photo's size) over to it.+ let orient = p.develop.orientation;+ let face = orient.map_norm_rect(face);+ let (w, h) = (f64::from(p.width.max(1)), f64::from(p.height.max(1)));+ let (w, h) = if orient.swaps_axes() { (h, w) } else { (w, h) };+ let side = ((face.x1 - face.x0) * w).max((face.y1 - face.y0) * h) * 1.7;+ // finite, within the photo, and never wider than its short side (so the clamps below are valid)+ let side = if side.is_finite() { side.clamp(1.0, w.min(h)) } else { w.min(h) };+ let (cx, cy) = ((face.x0 + face.x1) / 2.0 * w, (face.y0 + face.y1) / 2.0 * h);+ let (cx, cy) = (if cx.is_finite() { cx } else { w / 2.0 }, if cy.is_finite() { cy } else { h / 2.0 });+ let (x0, y0) = (cx.clamp(side / 2.0, w - side / 2.0) - side / 2.0, cy.clamp(side / 2.0, h - side / 2.0) - side / 2.0);+ let rect = lightcraft_geom::Rect { x0: x0 / w, y0: y0 / h, x1: (x0 + side) / w, y1: (y0 + side) / h };+ let mut settings = (*p.develop).clone();+ settings.crop = lightcraft_develop::Crop { geometry: lightcraft_geom::CropGeometry { rect, angle: 0.0 }, ..Default::default() };+ let edge = face_edge(edge);+ // pixels along the long edge that leave `edge` across the crop+ let needed = (edge as f64 * w.max(h) / side).ceil().min(SourceLevel::Preview.max_edge() as f64);+ let level = SourceLevel::for_size(needed as usize);+ let source = self.media.source_ref(&p, level);+ let ck = Self::variant_key(&p, &settings, edge);+ let preview_cut = self.face_preview_cut(&p, rect, edge, needed as usize);+ Some(RenderJob {+ request_id: 0,+ cache_generation: self.media.rendered.generation(),+ source_key: Some(Hasher128::new().str(&content_key(&p)).finish()),+ photo: id,+ level,+ source,+ origin: p.source.clone(),+ info: source_info(&p),+ settings: Arc::new(settings),+ request: RenderRequest { apply_crop: true, ..RenderRequest::fit(edge, edge) },+ key: (ck.0 as u64) ^ ((ck.0 >> 64) as u64),+ cache: Some((self.media.rendered.clone(), ck)),+ stages: None,+ view_cache: None,+ display: None,+ slide: None,+ preview_cut,+ display_fit: None,+ })+ }++ /// How a face tile of `p` can come from its embedded preview ([`crate::face_tiles`]): only an+ /// unedited raw (whose grid thumbnail is that preview too) not known to be offline, upright as+ /// imported, with a preview loader installed. `rect` is the square around the face, `edge` the+ /// tile, `needed` the source's long edge the develop render would ask for.+ fn face_preview_cut(&self, p: &Photo, rect: lightcraft_geom::Rect, edge: usize, needed: usize) -> Option<crate::face_tiles::PreviewCut> {+ let (path, loader) = self.embedded_of(p)?;+ if p.develop.orientation != lightcraft_geom::Orientation::Normal || self.media.availability.is_offline(&path) || p.width == 0 || p.height == 0+ {+ return None;+ }+ let want = needed.max(edge).max(1);+ let min = (want as f64 * crate::face_tiles::SOFT_LIMIT).ceil() as usize;+ let aspect = f64::from(p.width) / f64::from(p.height);+ Some(crate::face_tiles::PreviewCut { path, loader, want, min, rect, aspect, edge })+ }++ /// Size-independent cache key of a photo's view render (loupe) for its current settings.+ fn view_key(p: &Photo, apply_crop: bool) -> Hash128 {+ Hasher128::new()+ .str(&content_key(p))+ .str("view")+ .u64(p.develop.hash64())+ .u64(apply_crop as u64)+ .u64(RENDER_CACHE_VERSION)+ .u64(crate::camera_profiles::cache_key())+ .finish()+ }++ /// The loupe's render job: like [`Self::render_job`], and a full-quality result is kept as the+ /// photo's view preview (memory, and disk with a library) for [`Self::quick_view_job`].+ pub fn loupe_job(&mut self, id: PhotoId, max_w: usize, max_h: usize, apply_crop: bool) -> Option<RenderJob> {+ let mut job = self.render_job(id, max_w, max_h, false, apply_crop)?;+ let p = self.catalog.photo(id)?;+ job.view_cache = Some((self.media.rendered.clone(), Self::view_key(p, apply_crop)));+ Some(job)+ }++ /// A render of one window of the loupe's frame, for a view zoomed past what one whole-frame+ /// render can hold: the frame is `full_w × full_h` (the size the loupe would draw it at) and+ /// the result is `window`'s pixels of it, at that scale, from the source level that size needs.+ /// Nothing is cached here (a window is only worth keeping while it is on screen). `None`: no+ /// such photo, or the window reads (spots, Auto Mask strokes) more than one render can hold.+ pub fn region_job(+ &mut self,+ id: PhotoId,+ full_w: usize,+ full_h: usize,+ window: lightcraft_pipeline::PixelWindow,+ apply_crop: bool,+ ) -> Option<RenderJob> {+ self.region_job_of(id, full_w, full_h, window, apply_crop, false)+ }++ /// [`Self::region_job`] of the photo without its edits (its crop kept): the Before side.+ pub fn region_job_before(+ &mut self,+ id: PhotoId,+ full_w: usize,+ full_h: usize,+ window: lightcraft_pipeline::PixelWindow,+ apply_crop: bool,+ ) -> Option<RenderJob> {+ self.region_job_of(id, full_w, full_h, window, apply_crop, true)+ }++ fn region_job_of(+ &mut self,+ id: PhotoId,+ full_w: usize,+ full_h: usize,+ window: lightcraft_pipeline::PixelWindow,+ apply_crop: bool,+ before: bool,+ ) -> Option<RenderJob> {+ let mut job = self.render_job(id, full_w, full_h, before, apply_crop)?;+ // what the window's spots and Auto Mask strokes read must fit in one render: else the+ // caller keeps the whole-frame render (a window alone would come out wrong)+ let p = self.catalog.photo(id)?;+ let frame = lightcraft_pipeline::geometry::Frame::with_lens(+ p.width.max(1) as usize,+ p.height.max(1) as usize,+ &job.settings,+ apply_crop,+ p.embedded_lens.as_ref(),+ );+ let ppl = frame.px_per_long(full_w);+ lightcraft_pipeline::spots::window_for_reads_checked(&job.settings, &frame, full_w, full_h, ppl, window.clamped(full_w, full_h))?;+ job.request.window = Some(window);+ job.key = Hasher128::new()+ .u64(job.key)+ .str("window")+ .u64(window.x as u64)+ .u64(window.y as u64)+ .u64(window.w as u64)+ .u64(window.h as u64)+ .finish()+ .0 as u64;+ Some(job)+ }++ /// The embedded preview of an unedited raw (path, loader), when the app installed a loader.+ fn embedded_of(&self, p: &Photo) -> Option<(String, PreviewLoader)> {+ match (&p.source, &self.media.preview_loader) {+ (Source::File { path }, Some(l)) if p.kind == MediaKind::Raw && crate::import::has_import_look(p) => Some((path.clone(), l.clone())),+ _ => None,+ }+ }++ /// Whether `p`'s thumbnail can be the camera's own JPEG, so a frontend can skip the sensor+ /// decode behind it.+ ///+ /// The grid shows this JPEG first in any case ([`QuickJob`]: "grid thumbnails of unedited raws+ /// likewise start from the embedded preview"), and then paid for a render of the raw to replace+ /// it. That render decodes the whole sensor — 50 of a 56 MB Fuji RAF's bytes — for a 512 px+ /// thumbnail the 4 416 × 2 944 embedded JPEG already covers, and on a share at 1.2 MB/s it is+ /// 45 s a photo: a 149-photo folder spent 8.3 GB of traffic on thumbnails, and the queue behind+ /// it delayed the render the user was waiting for.+ ///+ /// Only unedited raws answer `true`: any edit must be rendered, and `has_import_look` is what+ /// says the photo still looks the way it did at import. A photo the user edits re-renders+ /// through the ordinary path, because its thumbnail key (settings hash) changes.+ pub fn embedded_thumb_is_final(&self, p: &Photo) -> bool {+ self.embedded_of(p).is_some()+ }++ /// The camera's embedded preview of a raw file, for the face scan. Faces are read from the unedited picture, so the+ /// photo's edits do not matter, and the camera's own JPEG (oriented, display-ready) costs a fraction of decoding the+ /// raw. `None` for anything else, and where the host installed no loader.+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) fn scan_preview_of(&self, p: &Photo) -> Option<(String, PreviewLoader)> {+ match (&p.source, &self.media.preview_loader) {+ (Source::File { path }, Some(l)) if p.kind == MediaKind::Raw => Some((path.clone(), l.clone())),+ _ => None,+ }+ }++ /// Something to show in the loupe right away for `id` (see [`QuickJob`]): its cached view+ /// render, else the embedded preview of an unedited raw, else a cached or fresh thumbnail.+ pub fn quick_view_job(&mut self, id: PhotoId, max_edge: usize, apply_crop: bool) -> Option<QuickJob> {+ let p = self.catalog.photo(id)?.clone();+ let small = self.thumb_job(id, THUMB_SIZES[THUMB_SIZES.len() - 1])?;+ // (the thumbnail job itself starts with the cached thumbnail, after the sharper embedded preview)+ let cached = vec![(self.media.rendered.clone(), Self::view_key(&p, apply_crop))];+ let h = Hasher128::new().str(&content_key(&p)).str("quick").u64(p.develop.hash64()).u64(apply_crop as u64).finish();+ let key = h.0 as u64;+ let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge())));+ Some(QuickJob { request_id: 0, photo: id, key, cached, embedded, small: apply_crop.then(|| Box::new(small)) })+ }++ /// A first grid thumbnail for an unedited raw: the cached render for `job` (the real+ /// thumbnail job, from [`Self::thumb_job`]) if there is one — then the result carries+ /// [`QuickSource::Cached`] and `job.key` and is final — else its embedded preview, else `job`+ /// itself: the grid queues no render behind an unedited raw's quick thumbnail+ /// ([`Self::embedded_thumb_is_final`]), so a preview that can't be read must not leave the+ /// cell empty (issue #1448). `None` for other photos (render them directly).+ pub fn quick_thumb_job(&mut self, job: &RenderJob) -> Option<QuickJob> {+ let p = self.catalog.photo(job.photo)?.clone();+ let (path, l) = self.embedded_of(&p)?;+ let edge = job.request.max_w.max(job.request.max_h);+ Some(QuickJob {+ request_id: 0,+ photo: job.photo,+ key: job.key,+ cached: job.cache.clone().into_iter().collect(),+ embedded: Some((path, l, edge)),+ small: Some(Box::new(job.clone())),+ })+ }++ /// Accept a finished job's loaded source into the cache. What the decode learnt about the file that the catalog+ /// has wrong is corrected too ([`Self::learn_as_shot_wb`]).+ pub fn accept(&mut self, r: &RenderResult) {+ if let Some(src) = &r.loaded+ && r.source_key.is_none_or(|key| self.catalog.photo(r.photo).is_some_and(|p| Hasher128::new().str(&content_key(p)).finish() == key))+ {+ if let Some(info) = &src.info {+ self.learn_as_shot_wb(r.photo, info);+ }+ self.media.insert_source(r.photo, r.level, src.clone());+ }+ }++ /// Record the as-shot white balance a decode of photo `id`'s file read (`info`) when the catalog has another:+ /// a raw imported before its camera's matrices gave it a Kelvin scale keeps 6500 / 0 (the relative scale's+ /// reference) until its file is next decoded (issue #730). Bookkeeping, not an undo step; the look does not+ /// change (the pipeline reads the stored settings against the real as-shot white either way), only what As Shot+ /// says and what a smart preview renders with. Only for raws edited in Kelvin.+ fn learn_as_shot_wb(&mut self, id: PhotoId, info: &SourceInfo) {+ let Some(p) = self.catalog.photo(id) else { return };+ if !info.raw || info.relative_wb || !p.develops_raw() || p.relative_wb() {+ return;+ }+ let read = (info.as_shot_temp, info.as_shot_tint);+ if !(read.0.is_finite() && read.1.is_finite()) || p.as_shot_wb == Some(read) {+ return;+ }+ if let Err(e) = self.apply_system(Op::SetAsShotWb { id, wb: Some(read) }) {+ log::warn!("photo {}: as-shot white balance not recorded: {e}", id.0);+ }+ }++ /// Synchronous render (CLI, MCP, tests).+ pub fn render_now(&mut self, id: PhotoId, max_w: usize, max_h: usize) -> Result<Rendered, String> {+ let job = self.render_job(id, max_w, max_h, false, true).ok_or("no such photo")?;+ let r = job.run();+ self.accept(&r);+ r.rendered+ }++ /// Synchronous render for export: like [`Self::render_now`], into colour space `space` with+ /// sample format `depth`.+ pub fn render_export(+ &mut self,+ id: PhotoId,+ max_w: usize,+ max_h: usize,+ space: lightcraft_pipeline::OutputSpace,+ depth: lightcraft_pipeline::OutputDepth,+ ) -> Result<Rendered, String> {+ let r = self.export_job(id, max_w, max_h, space, depth)?.run();+ self.accept(&r);+ r.rendered+ }++ /// The job [`Self::render_export`] runs, to run elsewhere (e.g. a background export thread).+ pub fn export_job(+ &mut self,+ id: PhotoId,+ max_w: usize,+ max_h: usize,+ space: lightcraft_pipeline::OutputSpace,+ depth: lightcraft_pipeline::OutputDepth,+ ) -> Result<RenderJob, String> {+ let mut job = self.render_job(id, max_w, max_h, false, true).ok_or("no such photo")?;+ // An export renders the full image: never a thumbnail's source developed from a smaller copy of the raw+ // image that the file keeps (Lightroom's merged DNGs)+ let reduced = match &job.source {+ SourceRef::Loaded(s) => s.reduced,+ SourceRef::Fit { from, .. } => from.reduced,+ _ => false,+ };+ if reduced {+ let p = self.catalog.photo(id).ok_or("no such photo")?.clone();+ job.source = self.media.source_ref_uncached(&p, job.level);+ }+ // An export is made from the denoised picture its Denoise amount asks for, made when the job runs if the+ // background queue has not got to it. (A source kept in memory may lack the picture, so the job reads the file.)+ if let Some(wanted) = self.denoise_for_export(id, &job.settings)? {+ let p = self.catalog.photo(id).ok_or("no such photo")?.clone();+ job.source = self.media.source_ref_uncached(&p, job.level);+ if let SourceRef::File { denoise, .. } = &mut job.source {+ *denoise = Some(wanted);+ }+ }+ job.request.space = space;+ job.request.depth = depth;+ job.key ^= (space as u64 + 1).wrapping_mul(0xa076_1d64_78bd_642f) ^ (depth as u64 + 1).wrapping_mul(0xe703_7ed1_a0b4_28db);+ Ok(job)+ }++ /// Prefer decoder facts to header-only metadata for pixel-statistics commands.+ pub fn source_info(&self, id: PhotoId) -> SourceInfo {+ let header = self.catalog.photo(id).map(|p| source_info(p)).unwrap_or_default();+ self.media.source_facts(id, header)+ }++ /// The source proxy for pixel-statistics commands (auto tone/WB), loading synchronously.+ pub fn source_now(&mut self, id: PhotoId, level: SourceLevel) -> Result<Arc<Rgb32f>, String> {+ let p = self.catalog.photo(id).ok_or("no such photo")?.clone();+ let r = self.media.source_ref(&p, level).load_source()?;+ let image = r.image.clone();+ if let Some(info) = &r.info {+ self.learn_as_shot_wb(id, info);+ }+ self.media.insert_source(id, level, r);+ Ok(image)+ }+ }diff --cc crates/ui-egui/src/render/thumbnail_tests.rsindex 000000000,984ce0462..6705a5ad2mode 000000,100644..100644--- a/crates/ui-egui/src/render/thumbnail_tests.rs+++ b/crates/ui-egui/src/render/thumbnail_tests.rs@@@ -1,0 -1,768 +1,801 @@@+ use super::*;+ use lightcraft_catalog::{Catalog, Op, Photo, Source};++ #[test]+ fn render_failures_identify_the_file_for_thumbnail_and_view_slots() {+ let source = Source::File { path: "/photos/trip/IMG_0042.nef".into() };+ for slot in [Slot::Thumb(PhotoId(42)), Slot::Main, Slot::Before, Slot::Compare(1), Slot::Region] {+ let message = render_failure_message(slot, PhotoId(42), Some(&source), "unsupported compression");+ assert!(message.contains("/photos/trip/IMG_0042.nef"), "{message}");+ assert!(message.contains("PhotoId(42)"), "{message}");+ assert!(message.ends_with(": unsupported compression"), "{message}");+ }+ }++ #[test]+ fn render_failure_paths_are_escaped_and_missing_sources_still_identified() {+ let source = Source::File { path: "line\nbreak.nef".into() };+ let message = render_failure_message(Slot::Main, PhotoId(42), Some(&source), "decode failed");+ assert!(!message.contains('\n'));+ assert!(message.contains("line\\nbreak.nef"));+ assert!(render_failure_message(Slot::Main, PhotoId(42), None, "decode failed").contains("PhotoId(42), source unavailable"));+ let demo = Source::Demo { scene: 7 };+ assert!(render_failure_message(Slot::Main, PhotoId(42), Some(&demo), "decode failed").contains("demo scene 7"));+ }++ struct Blocked;+ impl RenderOffload for Blocked {+ fn try_start(&mut self, _: Slot, job: RenderJob) -> Option<RenderJob> {+ Some(job)+ }+ fn finished(&mut self) -> Vec<(Slot, RenderResult, f64)> {+ vec![]+ }+ }+ fn photo() -> Arc<Photo> {+ Arc::new(Photo::new(PhotoId(1), Source::File { path: "audit.jpg".into() }, "audit.jpg", "JPEG", 6000, 4000, "2026-01-01"))+ }+ #[test]+ fn snapshot_tracks_cow_edits_undo_reload_and_replacement() {+ let mut catalog = Catalog::default();+ catalog.apply(Op::AddPhoto { photo: Box::new((*photo()).clone()) }).unwrap();+ let old = catalog.photo(PhotoId(1)).unwrap().clone();+ let mut r = Renderer::default();+ r.remember_thumb(&old, 384, 77, false);+ r.pending.insert(Slot::Thumb(PhotoId(1)), (77, 10));+ assert!(r.thumb_current(&old, 384, 10));+ assert!(!r.thumb_current(&old, 512, 10));+ let mut settings = lightcraft_develop::DevelopSettings::default();+ settings.light.exposure = 1.0;+ let undo = catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(settings), label: "edit".into(), edited: None }).unwrap();+ assert!(!r.thumb_current(catalog.photo(PhotoId(1)).unwrap(), 384, 10));+ catalog.apply(undo).unwrap();+ assert!(!r.thumb_current(catalog.photo(PhotoId(1)).unwrap(), 384, 10));+ catalog+ .apply(Op::SetContent {+ id: PhotoId(1),+ width: 6000,+ height: 4000,+ file_size: 99,+ content_hash: Some("changed".into()),+ preview_only: None,+ preview_checked: String::new(),+ })+ .unwrap();+ assert!(!r.thumb_current(catalog.photo(PhotoId(1)).unwrap(), 384, 10));+ assert!(!r.thumb_current(&photo(), 384, 10));+ r.forget_all();+ assert!(r.thumb_inputs.is_empty());+ }+ #[test]+ fn queue_promotions_running_work_and_cancellation() {+ let p = photo();+ let slot = Slot::Thumb(p.id);+ let mut session = Session::new();+ session.catalog.apply(Op::AddPhoto { photo: Box::new((*p).clone()) }).unwrap();+ let job = session.thumb_job(p.id, 384).unwrap();+ let key = job.key;+ let mut r = Renderer::default();+ r.set_offload(Box::new(Blocked));+ r.remember_thumb(&p, 384, key, false);+ r.request(slot, job, 5);+ assert!(r.thumb_current(&p, 384, 5));+ assert!(!r.thumb_current(&p, 384, 10));+ r.request(slot, session.thumb_job(p.id, 384).unwrap(), 10);+ assert_eq!(r.pending.get(&slot), Some(&(key, 10)));+ r.queue.clear(); // running work: cannot reprioritize, just as Renderer::request+ assert!(r.thumb_current(&p, 384, 5));+ r.pending.clear();+ assert!(!r.thumb_current(&p, 384, 10));+ r.evict_thumbs(&Default::default(), 600);+ assert!(r.thumb_inputs.is_empty());+ }+ fn queued_quick_thumbnail(id: PhotoId) -> (Arc<Photo>, QuickJob) {+ let mut session = Session::new();+ session.media.preview_loader = Some(Arc::new(|_, _| Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] })));+ let mut raw = (*photo()).clone();+ raw.id = id;+ raw.kind = lightcraft_catalog::MediaKind::Raw;+ raw.develop = Arc::new(raw.camera_defaults());+ session.catalog.apply(Op::AddPhoto { photo: Box::new(raw) }).unwrap();+ let p = session.catalog.photo(id).unwrap().clone();+ let job = session.thumb_job(id, 384).unwrap();+ (p, session.quick_thumb_job(&job).unwrap())+ }++ #[test]+ fn queued_standin_promotes_from_prefetch_to_visible_without_restarting() {+ let (p, quick) = queued_quick_thumbnail(PhotoId(1));+ let (_, other) = queued_quick_thumbnail(PhotoId(2));+ let slot = Slot::ThumbQuick(p.id);+ // Deterministic queue: no native worker starts.+ let mut r = Renderer { pool: JobPool::new(0), ..Default::default() };+ r.remember_thumb(&p, 384, quick.key, true);+ r.request_quick(slot, quick.clone(), 6); // grid prefetch: 5 + 1+ r.request_quick(Slot::ThumbQuick(PhotoId(2)), other, 9); // filmstrip: 8 + 1+ let request_id = r.requests[&slot].id;+ assert!(r.thumb_current(&p, 384, 5));+ assert!(!r.thumb_current(&p, 384, 10));+ r.request_quick(slot, quick.clone(), 11); // visible grid: 10 + 1+ assert!(r.thumb_current(&p, 384, 10));+ r.request_quick(slot, quick.clone(), 11);+ assert_eq!(r.requests[&slot].id, request_id);+ assert_eq!(r.pool.queued(), 2);+ r.pool.run_inline(1);+ let done = r.pool.try_recv().unwrap();+ assert_eq!(done.slot, slot);+ assert_eq!(done.result.result.request_id, request_id);+ assert_eq!(done.result.result.quick, Some(QuickSource::Embedded));+ // A finished result awaiting collection also must not start another extraction.+ r.request_quick(slot, quick, 6);+ assert!(r.thumb_current(&p, 384, 5));+ assert_eq!(r.pool.queued(), 1);+ }++ #[test]+ fn queued_standin_demotes_when_it_leaves_the_visible_grid() {+ let (p, quick) = queued_quick_thumbnail(PhotoId(1));+ let (_, other) = queued_quick_thumbnail(PhotoId(2));+ let slot = Slot::ThumbQuick(p.id);+ let mut r = Renderer { pool: JobPool::new(0), ..Default::default() };+ r.remember_thumb(&p, 384, quick.key, true);+ r.request_quick(slot, quick.clone(), 11);+ r.request_quick(Slot::ThumbQuick(PhotoId(2)), other, 9);+ assert!(!r.thumb_current(&p, 384, 5));+ r.request_quick(slot, quick, 6);+ assert!(r.thumb_current(&p, 384, 5));+ r.pool.run_inline(1);+ assert_eq!(r.pool.try_recv().unwrap().slot, Slot::ThumbQuick(PhotoId(2)));+ }++ #[test]+ fn failures_retry_after_revision_and_quick_only_is_not_final() {+ let p = photo();+ let slot = Slot::Thumb(p.id);+ let mut r = Renderer::default();+ r.remember_thumb(&p, 384, 77, false);+ r.pending.insert(Slot::ThumbQuick(p.id), (77, 11));+ assert!(!r.thumb_current(&p, 384, 10));+ r.failed.insert(slot, (77, "no decoder".into(), 0, p.id));+ assert!(r.thumb_current(&p, 384, 10));+ assert_eq!(r.failure_of(slot, p.id), Some("no decoder"));+ assert_eq!(r.failure_of(slot, PhotoId(p.id.0 + 1)), None, "another photo's error");+ r.catalog_rev = 1;+ assert!(!r.thumb_current(&p, 384, 10));+ }++ #[test]+ fn a_fast_draft_is_drawn_in_the_frame_that_asked_for_it() {+ let mut s = Session::new();+ s.media.file_loader = Some(Arc::new(|_, _| Ok((lightcraft_raster::Rgb32f::new(8, 8), Default::default()))));+ s.catalog.apply(Op::AddPhoto { photo: Box::new((*photo()).clone()) }).unwrap();+ let mut r = Renderer::with_worker_threads(1);+ let ctx = egui::Context::default();+ let budget = std::time::Duration::from_secs(10);+ // the last loupe render took longer than the budget (a CPU render): not waited for+ r.last_main_ms = 1e6;+ r.request(Slot::Main, s.render_job(PhotoId(1), 64, 64, false, true).unwrap(), 100);+ r.wait_for_draft(&ctx, &mut s, budget);+ assert!(r.is_pending(Slot::Main) && !r.textures.contains_key(&Slot::Main));+ // a fast one (GPU drafts): the texture is the new render when the wait returns+ r.last_main_ms = 1.0;+ r.request(Slot::Main, s.render_job(PhotoId(1), 32, 32, false, true).unwrap(), 100);+ let want = r.wanted(Slot::Main);+ r.wait_for_draft(&ctx, &mut s, budget);+ assert!(!r.is_pending(Slot::Main));+ assert_eq!(r.textures.get(&Slot::Main).map(|t| t.key), want);+ }++ #[derive(Default)]+ struct Work {+ jobs: Vec<(Slot, RenderJob)>,+ finished: Vec<(Slot, RenderResult, f64)>,+ }+ struct Manual(std::rc::Rc<std::cell::RefCell<Work>>);+ impl RenderOffload for Manual {+ fn try_start(&mut self, slot: Slot, job: RenderJob) -> Option<RenderJob> {+ self.0.borrow_mut().jobs.push((slot, job));+ None+ }+ fn finished(&mut self) -> Vec<(Slot, RenderResult, f64)> {+ std::mem::take(&mut self.0.borrow_mut().finished)+ }+ }+ fn fixture() -> (crate::LightcraftApp, std::rc::Rc<std::cell::RefCell<Work>>, egui::Context) {+ fixture_with(Session::new(), (*photo()).clone())+ }+ fn fixture_with(mut s: Session, photo: Photo) -> (crate::LightcraftApp, std::rc::Rc<std::cell::RefCell<Work>>, egui::Context) {+ s.media.file_loader = Some(Arc::new(|_, _| {+ let mut image = lightcraft_raster::Rgb32f::new(8, 8);+ image.data.fill([0.3, 0.2, 0.1]);+ Ok((image, Default::default()))+ }));+ // (`with_fs` sets the file system's thumbnail loader, which wins over `file_loader`: thumbnails use the stub too)+ s.media.reduced_loader = None;+ s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();+ let mut app = crate::LightcraftApp::new(s, crate::Services::default());+ app.renderer.keep_pixels = true;+ let work = std::rc::Rc::new(std::cell::RefCell::new(Work::default()));+ app.renderer.set_offload(Box::new(Manual(work.clone())));+ let ctx = egui::Context::default();+ app.renderer.poll(&ctx, &mut app.session);+ (app, work, ctx)+ }+ fn take_job(work: &std::rc::Rc<std::cell::RefCell<Work>>) -> (Slot, RenderJob) {+ work.borrow_mut().jobs.pop().unwrap()+ }+ fn finish(app: &mut crate::LightcraftApp, work: &std::rc::Rc<std::cell::RefCell<Work>>, ctx: &egui::Context, slot: Slot, result: RenderResult) {+ work.borrow_mut().finished.push((slot, result, 0.0));+ app.renderer.poll(ctx, &mut app.session);+ }+ fn request(app: &mut crate::LightcraftApp) {+ crate::panels::grid::request_thumb(app, PhotoId(1), 256, 10);+ }++ fn relink_destination() -> std::path::PathBuf {+ let path = std::env::temp_dir().join(format!("lc-render-relinked-{}-{}.nef", std::process::id(), lightcraft_preview::next_tick()));+ std::fs::write(&path, b"replacement source").unwrap();+ path+ }++ #[test]+ fn completed_failure_keeps_requested_source_after_relink() {+ let replacement = relink_destination();+ for slot in [Slot::Thumb(PhotoId(1)), Slot::Main, Slot::Before, Slot::Compare(1), Slot::Region] {+ let (mut app, work, ctx) = fixture();+ app.session.media.file_loader = Some(Arc::new(|_, _| Err("simulated decode failure".into())));+ let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap();+ app.renderer.request(slot, job, 100);+ let (submitted, job) = take_job(&work);+ assert_eq!(submitted, slot);+ let result = job.run();+ assert!(result.rendered.is_err(), "the old request has already failed");+ app.session.execute("photo.relink", &serde_json::json!({"id": 1, "path": replacement})).unwrap();+ assert!(+ matches!(&app.session.catalog.photo(PhotoId(1)).unwrap().source, Source::File { path } if path.ends_with(replacement.file_name().unwrap().to_str().unwrap()))+ );+ finish(&mut app, &work, &ctx, slot, result);+ assert_eq!(app.renderer.failure(slot), Some("simulated decode failure"));+ assert!(!app.renderer.is_pending(slot));+ let message = app.renderer.failure_messages.last().expect("the collector emitted a diagnostic");+ assert!(message.contains("audit.jpg"), "{message}");+ assert!(!message.contains("lc-render-relinked-"), "the failed request did not read the replacement: {message}");+ assert!(message.ends_with(": simulated decode failure"), "{message}");+ }+ std::fs::remove_file(replacement).unwrap();+ }++ #[test]+ fn superseded_failure_does_not_take_the_new_requests_source() {+ let replacement = relink_destination();+ let (mut app, work, ctx) = fixture();+ app.session.media.file_loader = Some(Arc::new(|_, _| Err("simulated decode failure".into())));+ let slot = Slot::Main;+ let old_job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap();+ app.renderer.request(slot, old_job, 100);+ let (_, old_job) = take_job(&work);+ let old_result = old_job.run();+ app.session.execute("photo.relink", &serde_json::json!({"id": 1, "path": replacement})).unwrap();+ let new_job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap();+ app.renderer.request(slot, new_job, 100);+ let (_, new_job) = take_job(&work);+ finish(&mut app, &work, &ctx, slot, old_result);+ assert!(app.renderer.failure_messages.is_empty(), "obsolete failures stay suppressed");+ assert!(app.renderer.is_pending(slot));+ finish(&mut app, &work, &ctx, slot, new_job.run());+ let message = app.renderer.failure_messages.last().expect("new failure is reported");+ assert!(message.contains("lc-render-relinked-"), "{message}");+ assert!(!message.contains("audit.jpg"), "{message}");+ assert!(app.renderer.requests.is_empty(), "completed request identity is released");+ std::fs::remove_file(replacement).unwrap();+ }++ #[test]+ fn grid_queued_standin_changes_priority_without_restarting() {+ let mut s = Session::new();+ s.media.preview_loader = Some(Arc::new(|_, _| Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] })));+ let mut raw = (*photo()).clone();+ raw.kind = lightcraft_catalog::MediaKind::Raw;+ raw.develop = Arc::new(raw.camera_defaults());+ let (mut app, work, ctx) = fixture_with(s, raw);+ app.renderer.pool = JobPool::new(0); // deterministic: no quick job starts until run_inline+ let id = PhotoId(1);+ let slot = Slot::ThumbQuick(id);++ crate::panels::grid::request_thumb(&mut app, id, 384, 5);+ let request_id = app.renderer.requests[&slot].id;+ assert_eq!(app.renderer.pending[&slot].1, 6);+ assert_eq!(app.renderer.pool.queued(), 1);+ crate::panels::grid::request_thumb(&mut app, id, 384, 10);+ assert_eq!(app.renderer.pending[&slot].1, 11, "the grid must promote its queued stand-in");+ assert_eq!(app.renderer.requests[&slot].id, request_id);+ assert_eq!(app.renderer.pool.queued(), 1);++ crate::panels::grid::request_thumb(&mut app, id, 384, 5);+ assert_eq!(app.renderer.pending[&slot].1, 6, "the grid must demote its queued stand-in");+ assert_eq!(app.renderer.requests[&slot].id, request_id);+ assert_eq!(app.renderer.pool.queued(), 1);+ let built = app.renderer.thumb_jobs_built;+ app.renderer.pool.run_inline(1);+ crate::panels::grid::request_thumb(&mut app, id, 384, 10);+ assert_eq!(app.renderer.pending[&slot].1, 6, "completed work must not be restarted");+ assert_eq!(app.renderer.requests[&slot].id, request_id);+ assert_eq!(app.renderer.pool.queued(), 0);+ app.renderer.poll(&ctx, &mut app.session);+ assert_eq!(app.renderer.textures[&slot].quick, Some(QuickSource::Embedded));++ crate::panels::grid::request_thumb(&mut app, id, 384, 10);+ crate::panels::grid::request_thumb(&mut app, id, 384, 5);+ assert_eq!(app.renderer.thumb_jobs_built, built);+ assert_eq!(app.renderer.pool.queued(), 0);+ assert!(!app.renderer.is_pending(Slot::Thumb(id)));+ assert!(!app.renderer.textures.contains_key(&Slot::Thumb(id)));+ assert!(work.borrow().jobs.is_empty(), "the final embedded thumbnail needs no real render");+ }++ #[test]+ fn unchanged_ready_and_running_frames_build_no_jobs() {+ let (mut app, work, ctx) = fixture();+ request(&mut app);+ assert_eq!(app.renderer.thumb_jobs_built, 1);+ for _ in 0..180 {+ request(&mut app);+ }+ assert_eq!(app.renderer.thumb_jobs_built, 1);+ let (slot, job) = take_job(&work);+ finish(&mut app, &work, &ctx, slot, job.run());+ for _ in 0..180 {+ request(&mut app);+ }+ assert_eq!(app.renderer.thumb_jobs_built, 1);+ assert!(work.borrow().jobs.is_empty());+ }++ #[test]+ fn a_slider_drag_leaves_the_edited_photos_thumbnail_until_it_ends() {+ let (mut app, work, ctx) = fixture();+ request(&mut app);+ let (slot, job) = take_job(&work);+ finish(&mut app, &work, &ctx, slot, job.run());+ app.session.execute("library.select", &serde_json::json!({"ids": [1], "active": 1})).unwrap();+ app.session.execute("develop.beginInteraction", &serde_json::json!({"label": "Exposure"})).unwrap();+ for v in [0.1, 0.2, 0.3] {+ app.session.execute("develop.set", &serde_json::json!({"control": "light.exposure", "value": v})).unwrap();+ app.renderer.poll(&ctx, &mut app.session);+ request(&mut app);+ }+ assert_eq!(app.renderer.thumb_jobs_built, 1, "the drag's frames render no thumbnail of the photo");+ assert!(work.borrow().jobs.is_empty());+ app.session.execute("develop.endInteraction", &serde_json::json!({})).unwrap();+ request(&mut app);+ assert_eq!(app.renderer.thumb_jobs_built, 2, "the thumbnail follows once the drag ends");+ }++ #[test]+ fn unchanged_queued_frames_build_no_jobs() {+ let (mut app, _, _) = fixture();+ app.renderer.set_offload(Box::new(Blocked));+ request(&mut app);+ for _ in 0..180 {+ request(&mut app);+ }+ assert_eq!(app.renderer.thumb_jobs_built, 1);+ assert_eq!(app.renderer.queue.len(), 1);+ }+++/// Issue #2682: the grid sent each video to the image decoder for a thumbnail, which failed with++/// "unrecognised image format", and asked again on every pass. A video is known by its kind, by++/// the format a Lightroom catalog gives it, or by its extension; none asks for a render, so none++/// fails and its cell keeps the plain placeholder.++#[test]++fn a_video_asks_the_decoders_for_no_thumbnail() {++ use lightcraft_catalog::MediaKind;++ let clip = |name: &str, format: &str, kind: MediaKind| {++ let mut p = Photo::new(PhotoId(1), Source::File { path: name.into() }, name, format, 1920, 1080, "2022-11-25");++ p.kind = kind;++ p++ };++ for video in [++ clip("VID_20221125_083409_527.mp4", "MP4", MediaKind::Video),++ clip("clip.MOV", "VIDEO", MediaKind::Image),++ clip("20221223_100006.mp4", "", MediaKind::Image),++ ] {++ let name = video.file_name.clone();++ let (mut app, work, ctx) = fixture_with(Session::new(), video);++ for _ in 0..30 {++ request(&mut app);++ app.renderer.poll(&ctx, &mut app.session);++ }++ assert_eq!(app.renderer.thumb_jobs_built, 0, "{name}");++ assert!(work.borrow().jobs.is_empty() && app.renderer.queue.is_empty(), "{name}: nothing is decoded");++ assert_eq!(app.renderer.failure(Slot::Thumb(PhotoId(1))), None, "{name}: nothing failed, so the cell has no \"!\"");++ }++ // a photo is still asked for++ let (mut app, _, _) = fixture();++ request(&mut app);++ assert_eq!(app.renderer.thumb_jobs_built, 1);++}+++ #[test]+ fn resizing_the_disk_cache_keeps_textures_and_skips_rebuilds() {+ let lib = std::env::temp_dir().join(format!("lc-ui-thumb-resize-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&lib);+ let mut s = Session::new().with_fs();+ s.open_library(&lib, false).unwrap();+ let (mut app, work, ctx) = fixture_with(s, (*photo()).clone());+ request(&mut app);+ let (slot, job) = take_job(&work);+ finish(&mut app, &work, &ctx, slot, job.run());+ assert!(app.renderer.thumb(PhotoId(1)).is_some());+ let cache = app.session.media.rendered.clone();+ app.session.execute("library.preferences", &serde_json::json!({"cacheMb": 300})).unwrap();+ app.renderer.poll(&ctx, &mut app.session);+ // thumbnails are keyed by content: a new budget leaves them (and the cache) valid+ assert!(app.renderer.thumb(PhotoId(1)).is_some());+ assert!(Arc::ptr_eq(&cache, &app.session.media.rendered));+ for _ in 0..30 {+ request(&mut app);+ }+ assert_eq!(app.renderer.thumb_jobs_built, 1);+ assert!(work.borrow().jobs.is_empty());+ // an explicit clear still drops them+ app.session.execute("library.clearPreviews", &serde_json::json!({})).unwrap();+ app.renderer.poll(&ctx, &mut app.session);+ assert!(app.renderer.thumb(PhotoId(1)).is_none());+ drop(app);+ let _ = std::fs::remove_dir_all(&lib);+ }++ /// A render that panics (a decoder bug) is a failure like any other: the slot stops waiting,+ /// the error is kept (not retried every frame), and the pool's workers live on. Before, the+ /// worker died without an answer and the slot stayed pending forever.+ #[test]+ fn a_panicking_render_is_a_failure_not_a_dead_worker() {+ let (mut app, _, ctx) = fixture_with(Session::new(), (*photo()).clone());+ app.session.media.file_loader = Some(Arc::new(|_, _| panic!("decoder bug")));+ app.renderer.offload = None; // the real job pool+ let slot = Slot::Thumb(PhotoId(1));+ let ask = |app: &mut crate::LightcraftApp| {+ if let Some(job) = app.session.thumb_job(PhotoId(1), 256) {+ app.renderer.request(slot, job, 30);+ }+ app.renderer.poll(&ctx, &mut app.session);+ };+ ask(&mut app);+ let t0 = std::time::Instant::now();+ while app.renderer.is_pending(slot) {+ assert!(t0.elapsed() < std::time::Duration::from_secs(20), "the render never answered");+ std::thread::sleep(std::time::Duration::from_millis(5));+ app.renderer.poll(&ctx, &mut app.session);+ }+ assert_eq!(app.renderer.failure(slot), Some("the render failed unexpectedly: decoder bug"));+ let workers = app.renderer.live_workers();+ assert!(workers > 0, "the worker that panicked is still there");+ let done = app.renderer.completed;+ for _ in 0..30 {+ ask(&mut app);+ }+ assert!(!app.renderer.is_pending(slot) && app.renderer.completed == done, "no retry loop");+ assert_eq!(app.renderer.live_workers(), workers);+ }++ #[test]+ fn raw_quick_path_frames_build_no_jobs() {+ // an unedited raw: the grid shows its embedded preview (held here until released) and stops+ // there — the camera JPEG at 4 416 × 2 944 already covers a 512 px thumbnail, so decoding the+ // whole raw behind it only costs the file read (45 s a photo on a 1.2 MB/s share)+ let gate = Arc::new(std::sync::Mutex::new(()));+ let held = gate.lock().unwrap();+ let mut s = Session::new();+ let g = gate.clone();+ s.media.preview_loader = Some(Arc::new(move |_: &str, _| {+ drop(g.lock().unwrap_or_else(std::sync::PoisonError::into_inner));+ Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] })+ }));+ let mut raw = (*photo()).clone();+ raw.kind = lightcraft_catalog::MediaKind::Raw;+ raw.develop = Arc::new(raw.camera_defaults());+ let (mut app, _, ctx) = fixture_with(s, raw);+ app.renderer.set_offload(Box::new(Blocked));+ let quick = Slot::ThumbQuick(PhotoId(1));+ // the stand-in is running+ for _ in 0..180 {+ request(&mut app);+ }+ assert!(app.renderer.is_pending(quick));+ assert_eq!(app.renderer.thumb_jobs_built, 1);+ drop(held);+ let t0 = std::time::Instant::now();+ while !app.renderer.textures.contains_key(&quick) {+ assert!(t0.elapsed() < std::time::Duration::from_secs(20), "the embedded preview never arrived");+ std::thread::sleep(std::time::Duration::from_millis(5));+ app.renderer.poll(&ctx, &mut app.session);+ }+ // the embedded preview is the thumbnail: no real render is queued behind it, and the grid+ // asking every frame neither rebuilds the job nor re-requests the preview+ for _ in 0..180 {+ request(&mut app);+ }+ assert_eq!(app.renderer.thumb_jobs_built, 1, "an unedited raw's embedded preview is the thumbnail");+ assert!(app.renderer.queue.is_empty(), "nothing is decoded behind it");+ assert!(!app.renderer.is_pending(Slot::Thumb(PhotoId(1))));++ // an edit takes the embedded preview out of the picture: the real thumbnail is rendered then+ let mut edited = (*photo()).clone();+ edited.kind = lightcraft_catalog::MediaKind::Raw;+ edited.develop = Arc::new({+ let mut d = edited.camera_defaults();+ d.light.exposure = 0.5;+ d+ });+ let (mut app, _, _ctx) = fixture_with(Session::new(), edited);+ app.renderer.set_offload(Box::new(Blocked));+ for _ in 0..180 {+ request(&mut app);+ }+ assert_eq!(app.renderer.thumb_jobs_built, 1);+ assert!(app.renderer.is_pending(Slot::Thumb(PhotoId(1))) || !app.renderer.queue.is_empty(), "an edited raw renders its thumbnail");+ }++ #[test]+ fn closing_import_review_cancels_queued_and_running_identities() {+ let (mut app, work, ctx) = fixture();+ let job = app.session.thumb_job(PhotoId(1), 256).unwrap();+ app.renderer.request(Slot::Import(0), job.clone(), 10);+ let (slot, running) = take_job(&work);+ app.renderer.set_offload(Box::new(Blocked));+ app.renderer.request(Slot::Import(1), job, 10);+ app.renderer.forget_imports();+ assert!(!app.renderer.is_pending(Slot::Import(0)));+ assert!(!app.renderer.is_pending(Slot::Import(1)));+ assert!(app.renderer.queue.is_empty());+ work.borrow_mut().finished.push((slot, running.run(), 0.0));+ app.renderer.set_offload(Box::new(Manual(work.clone())));+ app.renderer.poll(&ctx, &mut app.session);+ assert!(!app.renderer.textures.contains_key(&slot));+ assert_eq!(app.session.media.source_usage().0, 0);+ }++ #[test]+ fn loupe_shows_superseded_drafts_newer_than_its_pixels_during_a_drag() {+ let (mut app, work, ctx) = fixture();+ let mut jobs = Vec::new();+ for exposure in [0.0, 1.0, 2.0] {+ let mut edit = lightcraft_develop::DevelopSettings::default();+ edit.light.exposure = exposure;+ app.session.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edit), label: "drag".into(), edited: None }).unwrap();+ let job = app.session.loupe_job(PhotoId(1), 8, 8, true).unwrap().draft();+ app.renderer.request(Slot::Main, job, 100);+ jobs.push(take_job(&work).1);+ }+ let keys: Vec<u64> = jobs.iter().map(|j| j.key).collect();+ let mut jobs = jobs.into_iter();+ let (first, second, last) = (jobs.next().unwrap(), jobs.next().unwrap(), jobs.next().unwrap());+ // the first draft lands while the newest is still rendering: the loupe moves on+ finish(&mut app, &work, &ctx, Slot::Main, first.run());+ assert_eq!(app.renderer.textures.get(&Slot::Main).map(|t| t.key), Some(keys[0]));+ assert!(app.renderer.is_pending(Slot::Main));+ finish(&mut app, &work, &ctx, Slot::Main, last.run());+ assert_eq!(app.renderer.textures.get(&Slot::Main).map(|t| t.key), Some(keys[2]));+ // a draft older than the pixels shown never replaces them+ finish(&mut app, &work, &ctx, Slot::Main, second.run());+ assert_eq!(app.renderer.textures.get(&Slot::Main).map(|t| t.key), Some(keys[2]));+ assert!(!app.renderer.is_pending(Slot::Main));+ }++ #[test]+ fn a_drag_gets_its_live_hdr_histogram_beside_the_drafts() {+ let (mut app, work, ctx) = fixture();+ let mut jobs = Vec::new();+ for exposure in [1.0, 2.0] {+ let mut edit = lightcraft_develop::DevelopSettings::default();+ edit.hdr.enabled = true;+ edit.light.exposure = exposure;+ app.session.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edit), label: "drag".into(), edited: None }).unwrap();+ let job = app.session.render_job(PhotoId(1), 32, 32, false, true).unwrap();+ app.renderer.request(Slot::HdrHistogram, job, 95);+ jobs.push(take_job(&work).1);+ }+ let keys: Vec<u64> = jobs.iter().map(|j| j.key).collect();+ let mut jobs = jobs.into_iter();+ let (first, last) = (jobs.next().unwrap(), jobs.next().unwrap());+ // superseded while the drag goes on, it still lands: the histogram keeps moving+ finish(&mut app, &work, &ctx, Slot::HdrHistogram, first.run());+ let live = app.renderer.live_hdr_histogram.clone().expect("a live HDR histogram");+ assert_eq!((live.0, live.1), (PhotoId(1), keys[0]));+ assert!(live.2.hdr.is_some(), "HDR bins");+ finish(&mut app, &work, &ctx, Slot::HdrHistogram, last.run());+ assert_eq!(app.renderer.live_hdr_histogram.as_ref().map(|l| l.1), Some(keys[1]));+ // only the histogram is kept: no texture+ assert!(!app.renderer.textures.contains_key(&Slot::HdrHistogram));+ }++ #[test]+ fn library_reset_rejects_old_job_even_when_photo_id_and_key_are_reused() {+ let (mut app, work, ctx) = fixture();+ request(&mut app);+ let (slot, old) = take_job(&work);+ let old_result = old.run();+ app.renderer.forget_all();+ let photo = app.session.catalog.photo(PhotoId(1)).unwrap().as_ref().clone();+ app.session = lightcraft_engine::Session::new();+ app.session.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();+ app.session.media.file_loader = Some(Arc::new(|_, _| {+ let mut image = lightcraft_raster::Rgb32f::new(8, 8);+ image.data.fill([0.1, 0.2, 0.9]);+ Ok((image, Default::default()))+ }));+ app.renderer.poll(&ctx, &mut app.session);+ request(&mut app);+ let (_, new) = take_job(&work);+ assert_eq!(old_result.key, new.key);+ assert_ne!(old_result.request_id, new.request_id);+ let expected = new.clone().run().rendered.unwrap().image.as_bytes();+ finish(&mut app, &work, &ctx, slot, new.run());+ finish(&mut app, &work, &ctx, slot, old_result);+ assert_eq!(+ app.renderer.thumb(PhotoId(1)).unwrap().pixels.as_ref().unwrap().pixels.iter().flat_map(|c| c.to_array()).collect::<Vec<_>>(),+ expected+ );+ }++ #[test]+ fn late_results_and_errors_cannot_replace_newest_pixels_or_sources() {+ for order in [0, 1, 2] {+ let (mut app, work, ctx) = fixture();+ request(&mut app);+ let (slot, old) = take_job(&work);+ let mut edit = lightcraft_develop::DevelopSettings::default();+ edit.light.exposure = 1.0;+ app.session.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edit), label: "edit".into(), edited: None }).unwrap();+ request(&mut app);+ let (_, new) = take_job(&work);+ let expected = new.clone().run().rendered.unwrap().image.as_bytes();+ if order != 0 {+ finish(&mut app, &work, &ctx, slot, new.run());+ // An obsolete source and error must not poison the current successful request.+ let mut stale = old.run();+ if order == 2 {+ stale.rendered = Err("old failure".into());+ }+ finish(&mut app, &work, &ctx, slot, stale);+ } else {+ finish(&mut app, &work, &ctx, slot, old.run());+ assert!(app.renderer.thumb(PhotoId(1)).is_none());+ assert_eq!(app.session.media.source_usage().0, 0);+ finish(&mut app, &work, &ctx, slot, new.run());+ }+ assert_eq!(+ app.renderer.thumb(PhotoId(1)).unwrap().pixels.as_ref().unwrap().pixels.iter().flat_map(|c| c.to_array()).collect::<Vec<_>>(),+ expected+ );+ assert!(app.renderer.failure(slot).is_none());+ }+ }++ #[test]+ fn undo_to_existing_texture_supersedes_pending_edit() {+ let (mut app, work, ctx) = fixture();+ request(&mut app);+ let (slot, first) = take_job(&work);+ let key = first.key;+ finish(&mut app, &work, &ctx, slot, first.run());+ let original = app.renderer.thumb(PhotoId(1)).unwrap().pixels.clone().unwrap();+ let mut edit = lightcraft_develop::DevelopSettings::default();+ edit.light.exposure = 1.0;+ let undo = app.session.catalog.apply(Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edit), label: "edit".into(), edited: None }).unwrap();+ request(&mut app);+ let (_, edited) = take_job(&work);+ app.session.catalog.apply(undo).unwrap();+ request(&mut app);+ let (_, restored) = take_job(&work);+ assert_eq!(restored.key, key);+ finish(&mut app, &work, &ctx, slot, restored.run());+ finish(&mut app, &work, &ctx, slot, edited.run());+ assert_eq!(app.renderer.thumb(PhotoId(1)).unwrap().pixels.as_ref().unwrap().pixels, original.pixels);+ }++ #[test]+ fn explicit_clear_repairs_same_key_bad_pixels_and_rejects_old_same_key_job() {+ let (mut app, work, ctx) = fixture();+ let job = app.session.thumb_job(PhotoId(1), 256).unwrap();+ let expected = job.clone().run().rendered.unwrap().image;+ let (cache, key) = job.cache.clone().unwrap();+ let mut bad = expected.clone();+ bad.data.fill([255, 0, 255, 255]);+ cache.put(key, Arc::new(bad.clone()));+ request(&mut app);+ let (slot, corrupt) = take_job(&work);+ finish(&mut app, &work, &ctx, slot, corrupt.run());+ assert_eq!(app.renderer.thumb(PhotoId(1)).unwrap().pixels.as_ref().unwrap().pixels[0].to_array(), [255, 0, 255, 255]);+ // An old job can have the SAME render key and stale decoded pixels.+ let mut old = job.clone();+ old.source = lightcraft_engine::media::SourceRef::Loaded(Box::new(lightcraft_engine::media::DecodedSource::new(+ Arc::new(lightcraft_raster::Rgb32f::new(8, 8)),+ None,+ )));+ app.renderer.textures.clear();+ app.renderer.request(slot, old, 10);+ let (_, old) = take_job(&work);+ app.session.execute("library.clearPreviews", &serde_json::json!({})).unwrap();+ app.renderer.poll(&ctx, &mut app.session);+ assert!(app.renderer.thumb(PhotoId(1)).is_none());+ request(&mut app);+ let (_, repaired) = take_job(&work);+ assert_eq!(repaired.key, job.key);+ finish(&mut app, &work, &ctx, slot, repaired.run());+ finish(&mut app, &work, &ctx, slot, old.run());+ assert_eq!(cache.get(key).unwrap().as_bytes(), expected.as_bytes());+ assert_eq!(+ app.renderer.thumb(PhotoId(1)).unwrap().pixels.as_ref().unwrap().pixels.iter().flat_map(|c| c.to_array()).collect::<Vec<_>>(),+ expected.as_bytes()+ );+ }++ #[test]+ fn undo_to_embedded_thumb_rejects_late_full_render() {+ let mut s = Session::new();+ s.media.preview_loader = Some(Arc::new(|_, _| Some(lightcraft_raster::Rgba8 { width: 4, height: 4, data: vec![[200, 100, 50, 255]; 16] })));+ let mut raw = (*photo()).clone();+ raw.kind = lightcraft_catalog::MediaKind::Raw;+ raw.develop = Arc::new(raw.camera_defaults());+ let (mut app, work, ctx) = fixture_with(s, raw);+ app.renderer.pool = JobPool::new(0);+ let id = PhotoId(1);+ let quick_slot = Slot::ThumbQuick(id);+ let full_slot = Slot::Thumb(id);+ let settings_a = app.session.catalog.photo(id).unwrap().develop.clone();++ crate::panels::grid::request_thumb(&mut app, id, 384, 10);+ assert_eq!(app.renderer.pool.run_inline(1), 1);+ app.renderer.poll(&ctx, &mut app.session);+ let (key_a, pixels_a) = {+ let shown = app.renderer.thumb(id).unwrap();+ assert_eq!(shown.quick, Some(QuickSource::Embedded));+ (shown.key, shown.pixels.as_ref().unwrap().pixels.clone())+ };+ assert!(app.renderer.textures.contains_key(&quick_slot));+ assert!(!app.renderer.textures.contains_key(&full_slot));+ assert!(work.borrow().jobs.is_empty());++ let mut settings_b = (*settings_a).clone();+ settings_b.light.exposure += 0.5;+ app.session.commit("Exposure", Op::SetDevelop { id, settings: Arc::new(settings_b), label: "Exposure".into(), edited: None }).unwrap();+ assert!(!app.session.embedded_thumb_is_final(app.session.catalog.photo(id).unwrap()));+ crate::panels::grid::request_thumb(&mut app, id, 384, 10);+ // Manual owns dispatched jobs: hold B until the real Undo command restores A.+ let (slot, held_b) = take_job(&work);+ assert_eq!(slot, full_slot);+ let key_b = held_b.key;+ assert_ne!(key_b, key_a);+ assert!(app.renderer.is_pending(full_slot));++ app.run("edit.undo", serde_json::json!({})).unwrap();+ assert_eq!(app.session.catalog.photo(id).unwrap().develop.as_ref(), settings_a.as_ref());+ assert!(app.session.embedded_thumb_is_final(app.session.catalog.photo(id).unwrap()));+ crate::panels::grid::request_thumb(&mut app, id, 384, 10);+ {+ let restored = app.renderer.thumb(id).unwrap();+ assert_eq!(restored.key, key_a);+ assert_eq!(restored.pixels.as_ref().unwrap().pixels, pixels_a);+ assert_eq!(restored.quick, Some(QuickSource::Embedded));+ }+ assert!(work.borrow().jobs.is_empty(), "restoring embedded-final A needs no full render");+ assert_eq!(app.renderer.pool.queued(), 0);++ let result_b = held_b.run();+ assert_eq!(result_b.key, key_b);+ let rendered_b = result_b.rendered.as_ref().expect("held edited thumbnail must render before the stale-result oracle");+ assert_ne!(color_image(&rendered_b.image).pixels, pixels_a, "the held result must be distinguishable from A");+ finish(&mut app, &work, &ctx, slot, result_b);++ let shown = app.renderer.thumb(id).unwrap();+ assert_eq!(shown.key, key_a, "late edited Thumb(B) must not replace restored embedded ThumbQuick(A)");+ assert_eq!(shown.pixels.as_ref().unwrap().pixels, pixels_a);+ assert_eq!(shown.quick, Some(QuickSource::Embedded));+ let quick = app.renderer.textures.get(&quick_slot).expect("the correct embedded thumbnail must remain installed");+ assert_eq!(quick.key, key_a);+ assert_eq!(quick.quick, Some(QuickSource::Embedded));+ assert_eq!(quick.pixels.as_ref().unwrap().pixels, pixels_a);+ assert!(!app.renderer.is_pending(full_slot));+ }diff --cc docs/whats-new.mdindex bb101d7b8,c6c259200..a8db5cfdd--- a/docs/whats-new.md+++ b/docs/whats-new.md@@@ -1,16 -1,26 +1,35 @@@# What's new in LightCraft+ ## 2026-10-24++ ### Relative-date filters and smart albums follow the clock+ - A current view or source count using “in the last” rules now refreshes when the session clock moves into a new+ minute, even when no catalog edit occurred. This fixes stale photos remaining in the grid and stale counts for+ direct or nested smart albums. Held views keep photos that expired until Refresh View while admitting photos that+ newly match; expiry itself does not create an undo step.++ ### The histogram's tonal zones adjust the Basic tones+ - The histogram is a control surface again, as in Lightroom Classic: hovering one of its five zones (Blacks, Shadows,+ Exposure, Highlights, Whites) tints it and shows its name and value under the plot ("Exposure: +0.45 EV"). Dragging one+ sideways moves that control — the zone you pressed stays locked while the pointer crosses the others, Shift drags a+ tenth as far, and the whole drag is one undo step. Double-clicking a zone puts its control back to its default.++ ### Drag the parametric Tone Curve+ - In the Tone Curve's parametric mode the graph is now drawn from the renderer's own curve, so it always matches the+ photo, and the line can be dragged: pressing it picks the region under the pointer (Highlights, Lights, Darks or+ Shadows) and moving up or down changes that slider, as one undo step. Hovering the line names the region first.+## 2026-10-23+### Videos in the grid are no longer sent to the image decoders+- A video in the library (an MP4 or MOV brought in from a Lightroom catalog) no longer asks the image decoders for a+ grid thumbnail (issue #2682). They can't read one, so each video failed with "unrecognised image format", showed a+ "!" and was tried again whenever the library changed, filling the log. Its cell now keeps the plain placeholder until+ LightCraft can show video frames. The background face search skips videos too, instead of failing on each one at+ every launch. A video is recognised by its type, by the format `VIDEO` that Lightroom catalogs+ give videos, or by its extension (`.mp4`, `.mov`, `.m4v`, `.avi`, `.mts`, `.m2ts`, `.3gp`, `.mkv`, `.webm`, `.wmv`,+ `.mpg`, `.mpeg`).+### Tab leaves the name field in New Album, New Smart Album and the name prompts- In New Album, New Smart Album, Save Metadata Preset and the other dialogs with one name field, the field has thekeyboard focus when the dialog opens, and Tab now moves on to the check box, Cancel and OK (Shift+Tab goes back).