diff --git a/.gitignore b/.gitignore index 12f5e90d92..215d7e03b4 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,6 @@ # model weights are never committed (SAM 3: docs/ai-masks.md) *.safetensors *.safetensors.part + +# aider +.aider* diff --git a/apps/app/src/hdr_display.rs b/apps/app/src/hdr_display.rs index 71d33e9582..069d444b53 100644 --- a/apps/app/src/hdr_display.rs +++ b/apps/app/src/hdr_display.rs @@ -333,6 +333,9 @@ impl WindowHdr { } impl lcc_ui_egui::HdrOutput for WindowHdr { + fn extended(&self) -> bool { + self.extended + } fn headroom(&mut self) -> Option { let info = self.state.display_hdr_info.read().clone(); let l = levels(Platform::current(), info.as_ref(), self.headroom_override, self.paper_white_override); diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index ec5452b78c..7e8ae2838a 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -427,15 +427,18 @@ pub fn edit_specs() -> Vec { has_active, edit_external ), - cmd!( - "photo.renderToDng", - "Render to DNG", - ["Photo"], - None, - "{ids?, colorSpace?: proPhoto (default) | rec2020 | adobeRgb | displayP3 | srgb, dir?} — render each selected photo (or `ids`, at most 500) with its edits as a linear 16-bit float DNG `-Rendered.dng` next to it (a demo photo into `dir`), add each stacked on its original and select them; a batch shows in the activity stack and can be cancelled between photos → {copies: [{path, id, original}], failed: [{id, error}], cancelled}", - has_selection, - render_to_dng - ), + CommandSpec { + explicit_targets: true, + ..cmd!( + "photo.renderToDng", + "Render to DNG", + ["Photo"], + None, + "{ids?, colorSpace?: proPhoto (default) | rec2020 | adobeRgb | displayP3 | srgb, dir?} — render each selected photo (or `ids`, at most 500) with its edits as a linear 16-bit float DNG `-Rendered.dng` next to it (a demo photo into `dir`), add each stacked on its original and select them; a batch shows in the activity stack and can be cancelled between photos → {copies: [{path, id, original}], failed: [{id, error}], cancelled}", + has_selection, + render_to_dng + ) + }, ] } @@ -639,4 +642,44 @@ mod tests { assert!(s.activity.list().is_empty()); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn render_to_dng_uses_hdr_options() { + let dir = scratch("hdr"); + let mut s = Session::with_demo(); + let id = s.visible()[0]; + // Enable HDR editing on the photo + s.execute("develop.hdr", &json!({"id": id.0, "enabled": true})).unwrap(); + // Render to DNG should succeed with HDR enabled + let r = s.execute("photo.renderToDng", &json!({"ids": [id.0], "dir": dir.to_string_lossy()})).unwrap(); + let path = r["copies"][0]["path"].as_str().unwrap(); + // The DNG should be encoded (not an error) + assert!(std::path::Path::new(path).exists(), "DNG file was written"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn render_to_dng_accepts_explicit_ids_without_selection() { + let dir = scratch("explicit"); + let mut s = Session::with_demo(); + let ids: Vec<_> = s.visible().iter().copied().take(2).collect(); + // Clear selection + s.execute("library.select", &json!({"ids": []})).unwrap(); + assert!(s.selection.ids.is_empty(), "selection was cleared"); + // renderToDng with explicit ids should still work (explicit_targets: true) + let r = s.execute("photo.renderToDng", &json!({"ids": [ids[0].0, ids[1].0], "dir": dir.to_string_lossy()})).unwrap(); + let copies = r["copies"].as_array().unwrap(); + assert_eq!(copies.len(), 2, "both explicit targets were rendered: {r}"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn library_generation_changes_when_library_changes() { + let s1 = Session::default(); + let gen1 = s1.library_generation(); + let s2 = Session::default(); + let gen2 = s2.library_generation(); + // Each session should have a unique generation + assert_ne!(gen1, gen2, "different sessions have different library generations"); + } } diff --git a/crates/engine/src/cmd/edit_in/link.rs b/crates/engine/src/cmd/edit_in/link.rs index 61fd10cf4a..1811444ef7 100644 --- a/crates/engine/src/cmd/edit_in/link.rs +++ b/crates/engine/src/cmd/edit_in/link.rs @@ -236,6 +236,11 @@ pub fn file_xmp(path: &Path) -> Option { } } +/// A file an external editor writes (TIFF, PSD): only these carry an edit's link back to its source. +fn is_editable(p: &Path) -> bool { + matches!(p.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).as_deref(), Some("tif" | "tiff" | "psd" | "psb")) +} + /// After an import: stack each new TIFF/PSD whose XMP says it was derived from a photo in the /// library on that photo (found by file name in the same folder, else by document id), as Edit In /// would have. Photos already stacked with their source are left alone. → the photos stacked @@ -245,7 +250,7 @@ pub fn stack_derived(s: &mut Session, imported: &[PhotoId]) -> Vec { let Some(ph) = s.catalog.photo(*id) else { continue }; let Source::File { path } = &ph.source else { continue }; let p = Path::new(path); - if !matches!(p.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).as_deref(), Some("tif" | "tiff" | "psd" | "psb")) { + if !is_editable(p) { continue; } let Some(link) = file_xmp(p).map(|x| read_link(&x)) else { continue }; @@ -261,16 +266,38 @@ pub fn stack_derived(s: &mut Session, imported: &[PhotoId]) -> Vec { // (folder, file name) and document id → photo, built once let mut by_name: HashMap<(String, String), PhotoId> = HashMap::new(); let mut by_doc: HashMap = HashMap::new(); + let mut editable: Vec<(PhotoId, std::path::PathBuf)> = Vec::new(); for ph in s.catalog.photos().filter(|p| !p.deleted && p.copy_of.is_none()) { if let Source::File { path } = &ph.source { let p = Path::new(path); let dir = p.parent().map(|d| d.to_string_lossy().to_string()).unwrap_or_default(); by_name.entry((dir, ph.file_name.clone())).or_insert(ph.id); + if is_editable(p) { + editable.push((ph.id, p.to_path_buf())); + } } if let Some(d) = hash_document_id(ph) { by_doc.entry(d).or_insert(ph.id); } } + // An edit of an edit names its source by the document ID embedded in that file, which the + // catalog doesn't keep: read it only when a link is left unresolved, and only from the files + // an editor writes (an edit's source is itself one). + let unresolved = wanted.iter().any(|(_, dir, link)| { + let by_path = link + .derived_path + .as_ref() + .and_then(|n| Path::new(n).file_name()) + .is_some_and(|n| by_name.contains_key(&(dir.clone(), n.to_string_lossy().to_string()))); + !by_path && link.derived_document.as_ref().is_some_and(|d| !by_doc.contains_key(d)) + }); + if unresolved { + for (id, p) in editable { + if let Some(d) = file_xmp(&p).and_then(|x| read_link(&x).document_id) { + by_doc.entry(d).or_insert(id); + } + } + } let mut pairs: Vec<(PhotoId, PhotoId)> = Vec::new(); for (id, dir, link) in wanted { let src = link @@ -368,4 +395,48 @@ mod tests { assert!(file_xmp(&p).is_none(), "{name}"); } } + #[test] + fn renamed_parent_restacks_via_embedded_id() { + use serde_json::json; + // Scenario: parent file is renamed/moved, child's DerivedFrom names the parent's embedded + // xmpMM:DocumentID (not the hash). stack_derived must find the parent via the embedded ID. + let dir = std::env::temp_dir().join(format!("edit-link-embedded-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + // Create parent TIFF with embedded document ID + let parent = dir.join("parent.tif"); + let parent_bytes = lcc_codecs::encode_tiff( + &lcc_codecs::EncodeImage::rgba8(&lcc_raster::Rgba8 { width: 10, height: 10, data: vec![[200, 50, 50, 255]; 100] }), + lcc_codecs::TiffCompression::Deflate, + &lcc_codecs::EncodeMeta { icc: None, exif: None, xmp: Some(&add_link(PACKET, "xmp.did:parent-embedded", "", "")), ppi: None }, + ) + .unwrap(); + std::fs::write(&parent, &parent_bytes).unwrap(); + // Create child TIFF with DerivedFrom pointing to parent's embedded ID + let child = dir.join("child.tif"); + let child_xmp = add_link(PACKET, "xmp.did:child-embedded", "xmp.did:parent-embedded", "original.tif"); + let child_bytes = lcc_codecs::encode_tiff( + &lcc_codecs::EncodeImage::rgba8(&lcc_raster::Rgba8 { width: 10, height: 10, data: vec![[50, 200, 50, 255]; 100] }), + lcc_codecs::TiffCompression::Deflate, + &lcc_codecs::EncodeMeta { icc: None, exif: None, xmp: Some(&child_xmp), ppi: None }, + ) + .unwrap(); + std::fs::write(&child, &child_bytes).unwrap(); + // Import into fresh catalog + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [parent.to_string_lossy(), child.to_string_lossy()]})).unwrap(); + let ids: Vec = r["imported"].as_array().unwrap().iter().filter_map(|v| v.as_u64()).collect(); + assert_eq!(ids.len(), 2); + let child_id = ids + .iter() + .find(|&&id| s.catalog.photo(PhotoId(id)).map(|p| p.file_name.contains("child")).unwrap_or(false)) + .copied() + .expect("child imported"); + let parent_id = ids.iter().find(|&&id| id != child_id).copied().expect("parent imported"); + // Import calls stack_derived automatically; the child should be stacked on the parent + // via the embedded document ID index + let st = s.catalog.stack_of(PhotoId(child_id)).expect("child stacked after import"); + assert!(st.photos.contains(&PhotoId(parent_id)), "parent in same stack as child"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/engine/src/lightroom_smart.rs b/crates/engine/src/lightroom_smart.rs index b06d2cfaed..0ab5512e84 100644 --- a/crates/engine/src/lightroom_smart.rs +++ b/crates/engine/src/lightroom_smart.rs @@ -145,12 +145,11 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { _ => Err(unsupported()), } } - "rating" | "isoSpeedRating" | "focalLength" | "aperture" => { + "rating" | "isoSpeedRating" | "focalLength" => { let target = match name { "rating" => "rating", "isoSpeedRating" => "iso", - "focalLength" => "focalLength", - _ => "aperture", + _ => "focalLength", }; let n = num(value).ok_or_else(unsupported)?; if op == "in" { @@ -160,6 +159,18 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { let op = number_op(op).ok_or_else(unsupported)?; Ok(field(target, op, json!(n))) } + "aperture" => { + // Lightroom stores aperture in APEX; convert to f-number for our native rules + let apex = num(value).ok_or_else(unsupported)?; + let f_number = 2.0_f64.powf(apex / 2.0); + if op == "in" { + let apex_hi = num(c.get("value2")).ok_or_else(unsupported)?; + let f_number_hi = 2.0_f64.powf(apex_hi / 2.0); + return Ok(field("aperture", "between", json!([f_number, f_number_hi]))); + } + let op = number_op(op).ok_or_else(unsupported)?; + Ok(field("aperture", op, json!(f_number))) + } "pick" => { let flag = match num(value).map(|n| n as i64) { Some(1) => "pick", @@ -197,6 +208,20 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { _ => Err(unsupported()), } } + "fileFormat" => { + let raw = value.and_then(Lua::str).unwrap_or_default(); + let raw_upper = raw.to_ascii_uppercase(); + if raw_upper == "RAW" { + // Lightroom's generic "RAW" matches our raw originals (ARW, NEF, CR2, …) + match op { + "==" | "" => Ok(field("kind", "is", json!("raw"))), + "!=" => Ok(field("kind", "isNot", json!("raw"))), + _ => Err(unsupported()), + } + } else { + text_rule("format", op, raw).ok_or_else(unsupported) + } + } _ => { let target = match name { "keywords" => "keywords", @@ -212,7 +237,6 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result { "country" => "country", "location" => "location", "state" => "state", - "fileFormat" => "format", _ => return Err(unsupported()), }; text_rule(target, op, value.and_then(Lua::str).unwrap_or_default()).ok_or_else(unsupported) @@ -228,7 +252,10 @@ fn text_rule(target: &str, op: &str, value: &str) -> Option { "notEmpty" => field(target, "isNotEmpty", Value::Null), _ if words.is_empty() => return None, // Every word must appear: what "contains" already means here. - "all" | "words" => field(target, "contains", json!(value)), + // "all": each word must appear (as a separate keyword); "words": one keyword contains all + "all" if words.len() == 1 => field(target, "contains", json!(value)), + "all" => Rule::Group { group: RuleSet { mode: Match::All, rules: words.iter().map(|w| field(target, "contains", json!(w))).collect() } }, + "words" => field(target, "contains", json!(value)), "any" if words.len() == 1 => field(target, "contains", json!(value)), "any" => Rule::Group { group: RuleSet { mode: Match::Any, rules: words.iter().map(|w| field(target, "contains", json!(w))).collect() } }, "noneOf" => { @@ -327,4 +354,55 @@ mod tests { } assert!(smart_rules(&s, &[]).is_err()); } + + #[test] + fn keywords_contains_all_splitted() { + // "all" must create separate keyword rules joined by All, not one rule + // matching a single keyword containing the whole string. + let set = smart_rules(r#"s = { { criteria = "keywords", operation = "all", value = "beach sunset" } }"#, &[]).unwrap(); + let Rule::Group { group } = &set.rules[0] else { panic!("expected All group") }; + assert_eq!(group.mode, Match::All); + assert_eq!(group.rules.len(), 2); + assert_eq!(group.rules[0], field("keywords", "contains", json!("beach"))); + assert_eq!(group.rules[1], field("keywords", "contains", json!("sunset"))); + } + + #[test] + fn fileformat_raw_maps_to_kind_raw() { + // Lightroom's generic "RAW" must map to kind=raw, not format=RAW. + let set = smart_rules(r#"s = { { criteria = "fileFormat", operation = "==", value = "RAW" } }"#, &[]).unwrap(); + assert_eq!(set.rules[0], field("kind", "is", json!("raw"))); + } + + #[test] + fn fileformat_jpeg_stays_as_format() { + // Specific formats (JPEG, TIFF, …) still map to the format field. + let set = smart_rules(r#"s = { { criteria = "fileFormat", operation = "==", value = "JPEG" } }"#, &[]).unwrap(); + assert_eq!(set.rules[0], field("format", "is", json!("JPEG"))); + } + + #[test] + fn aperture_apex_converted_to_fnumber() { + // APEX 6 = f/8 (f-number = 2^(APEX/2)). + let set = smart_rules(r#"s = { { criteria = "aperture", operation = "==", value = 6 } }"#, &[]).unwrap(); + if let Rule::Field { value, .. } = &set.rules[0] { + let fnum = value.as_f64().unwrap(); + assert!((fnum - 8.0).abs() < 1e-6, "expected f/8, got {fnum}"); + } else { + panic!("expected Field rule"); + } + } + + #[test] + fn aperture_range_apex_converted() { + // Range endpoints must also be converted. + let set = smart_rules(r#"s = { { criteria = "aperture", operation = "in", value = 6, value2 = 8 } }"#, &[]).unwrap(); + if let Rule::Field { value, .. } = &set.rules[0] { + let arr = value.as_array().unwrap(); + assert!((arr[0].as_f64().unwrap() - 8.0).abs() < 1e-6); // APEX 6 → f/8 + assert!((arr[1].as_f64().unwrap() - 16.0).abs() < 1e-6); // APEX 8 → f/16 + } else { + panic!("expected Field rule"); + } + } } diff --git a/crates/engine/src/render_dng.rs b/crates/engine/src/render_dng.rs index 0e1efce59b..96bc0343cd 100644 --- a/crates/engine/src/render_dng.rs +++ b/crates/engine/src/render_dng.rs @@ -60,6 +60,7 @@ pub fn prepare(s: &mut Session, p: &Value) -> Result { color_space: space, naming: "{name}-Rendered".into(), conflict: Conflict::Unique, + hdr: true, ..Default::default() }; let mut items = Vec::with_capacity(ids.len()); diff --git a/crates/engine/src/tests_custom_order.rs b/crates/engine/src/tests_custom_order.rs index 23c684b37b..25cc2364ce 100644 --- a/crates/engine/src/tests_custom_order.rs +++ b/crates/engine/src/tests_custom_order.rs @@ -162,3 +162,22 @@ fn new_album_from_selection_keeps_the_shown_order() { let got: Vec = s.catalog.album_photo_order(AlbumId(b)).iter().map(|p| p.0).collect(); assert_eq!(got, rev); } + +/// Custom order drag-drop with descending sort: dropping on the left side of a photo means +/// "after" in the saved order (PR #1155). +#[test] +fn descending_sort_inverts_drop_position() { + let mut s = Session::with_demo(); + let (a, ids) = album(&mut s); + s.execute("album.setPhotoOrder", &json!({"album": a, "ids": ids[0..4].to_vec()})).unwrap(); + s.execute("library.sort", &json!({"key": "custom", "ascending": false})).unwrap(); + let o = shown(&mut s); + // o is [ids[3], ids[2], ids[1], ids[0]] (descending) + // In descending sort, left side visually = after in saved order. + // "After ids[2]" in saved order means before ids[1]. + let r = s.execute("album.orderPhotos", &json!({"album": a, "ids": [o[3]], "before": o[2]})).unwrap(); + let new_order = order(&r); + let pos_moved = new_order.iter().position(|p| *p == o[3]).unwrap(); + let pos_target = new_order.iter().position(|p| *p == o[2]).unwrap(); + assert!(pos_moved < pos_target, "photo should be before target in saved order: {new_order:?}"); +} diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index d0035667c3..bb7a9dfbe3 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -622,7 +622,7 @@ pub struct PlaneSigmas { pub chroma: Option, } -/// Sharpening blur radius in output pixels before clamping: Radius (source pixels) times the +/// Sharpening blur radius in output pixels before the floor of [`sharpen_sigma`]: Radius (source pixels) times the /// output pixels per source pixel (`src_long` = the oriented source's long edge), so a preview and /// an export show the same detail at the same displayed scale. pub fn sharpen_sigma_raw(s: &DevelopSettings, px_per_long: f64, src_long: f64) -> f32 { @@ -631,13 +631,13 @@ pub fn sharpen_sigma_raw(s: &DevelopSettings, px_per_long: f64, src_long: f64) - (radius * px_per_long / src_long.max(1.0)) as f32 } -/// Smallest and largest sigma (px) of the sharpening blur. +/// Smallest sigma (px) of the sharpening blur. There is no ceiling: an enlarged export scales +/// the radius with it, so distinct radii stay distinct at every scale. pub const SHARPEN_SIGMA_MIN: f32 = 0.3; -pub const SHARPEN_SIGMA_MAX: f32 = 4.0; /// The sharpening blur's sigma for a raw value of [`sharpen_sigma_raw`]. pub fn sharpen_sigma(raw: f32) -> f32 { - raw.clamp(SHARPEN_SIGMA_MIN, SHARPEN_SIGMA_MAX) + raw.max(SHARPEN_SIGMA_MIN) } /// How much of the sharpening survives at a raw sigma: none at or below 0.3 px, all from 0.5 px diff --git a/crates/pipeline/src/tests_sharpen.rs b/crates/pipeline/src/tests_sharpen.rs index 8a60378107..0ee9e84d33 100644 --- a/crates/pipeline/src/tests_sharpen.rs +++ b/crates/pipeline/src/tests_sharpen.rs @@ -196,3 +196,16 @@ fn photos_on_older_processes_keep_their_sharpening() { v4.process = ProcessVersion::LATEST; assert!(rms(&render_at(&src, &v4, 256), &render_at(&src, &sharp(60.0, 3.0, 100.0, 0.0), 256)) > 0.1); } + +#[test] +fn different_radii_differ_at_upscale() { + // Regression for PR762: at 2x export scale, Radius 2 and 3 must produce different + // output. Before the fix, the ceiling clamp in sharpen_sigma made them identical. + let src = scene(512); + let s2 = sharp(60.0, 2.0, 25.0, 0.0); + let s3 = sharp(60.0, 3.0, 25.0, 0.0); + let r2 = render_at(&src, &s2, 1024); + let r3 = render_at(&src, &s3, 1024); + let diff = rms(&r2, &r3); + assert!(diff > 0.1, "Radius 2 and 3 should differ at 2x scale (got {})", diff); +} diff --git a/crates/raw/src/kelvin_presets.rs b/crates/raw/src/kelvin_presets.rs index f22158a4c0..8fe5647a4a 100644 --- a/crates/raw/src/kelvin_presets.rs +++ b/crates/raw/src/kelvin_presets.rs @@ -92,12 +92,15 @@ pub fn covers(make: Option<&str>, model: &str) -> bool { sony && !model.is_empty() && !WITHOUT_PRESETS.iter().any(|m| m.eq_ignore_ascii_case(model)) } -/// [`covers`] for make and model joined by a space, as the catalog keeps them (`"SONY ILCA-99M2"`). +/// [`covers`] for make and model joined by a space, as the catalog keeps them (`"SONY ILCA-99M2"`). Every split +/// into make and model is tried, then the whole string as a model alone; this matches [`crate::spectral::find_camera`] +/// and the catalog's own lookup. pub fn covers_camera(camera: &str) -> bool { - match camera.split_once(char::is_whitespace) { - Some((make, model)) => covers(Some(make), model), - None => covers(None, camera), + let words: Vec<&str> = camera.split_whitespace().collect(); + if words.is_empty() { + return false; } + (1..words.len()).any(|i| covers(Some(&words[..i].join(" ")), &words[i..].join(" "))) || covers(None, camera) } /// Most points a curve keeps (Canon writes about seven at a stated temperature, Sony five). @@ -339,4 +342,16 @@ mod tests { assert!(covers(Some("SONY"), "ILCA-99M2") && covers(None, "ILCA-99M2") && !covers(Some("NIKON CORPORATION"), "ILCA-99M2")); assert!(!covers(Some("SONY"), " ") && !covers(Some("HASSELBLAD"), "Lunar") && !covers(None, "ILC")); } + + /// The catalog keeps joined camera names; Nikon Z5II's make-model split is not at the first word, + /// so covers_camera must try every split, not just the first. + #[test] + fn joined_nikon_z5ii_covers_camera() { + // Direct lookup works + assert!(covers(Some("NIKON CORPORATION"), "NIKON Z5_2")); + // Joined catalog string must also work (regression for PR #2006) + assert!(covers_camera("NIKON CORPORATION NIKON Z5_2")); + // D850 has no Kelvin presets; still not covered through the joined path + assert!(!covers_camera("NIKON CORPORATION NIKON D850")); + } } diff --git a/crates/ui-egui/src/edit_in.rs b/crates/ui-egui/src/edit_in.rs index fa0d3eb1a0..c61cd87071 100644 --- a/crates/ui-egui/src/edit_in.rs +++ b/crates/ui-egui/src/edit_in.rs @@ -202,7 +202,8 @@ pub(crate) fn after_command(app: &mut LccApp, id: &str, r: &Value) { if let Some(f) = app.services.open_with.as_mut() && let Err(e) = f(path, &editor) { - app.ui.status = format!("{}: {e}", tr("Couldn't open the editor")); + let now = app.last_time; + app.ui.toast = Some((crate::i18n::tr_format!("Couldn't open the editor: {e}", e = e), now + 1.4, None)); } } @@ -343,7 +344,7 @@ pub(crate) fn pump(app: &mut LccApp, ctx: &egui::Context) { }); for m in msgs { match m { - Msg::Event(EditorEvent::Saved(p)) | Msg::Exited(p) => { + Msg::Event(EditorEvent::Saved(p)) => { let ids = ROUND_TRIP.with_borrow_mut(|rt| { let ids = rt.watched.ids(&p); rt.watched.mark_seen(&p); @@ -351,6 +352,14 @@ pub(crate) fn pump(app: &mut LccApp, ctx: &egui::Context) { }); reload(app, ctx, ids); } + Msg::Exited(p) => { + let ids = ROUND_TRIP.with_borrow_mut(|rt| { + let ids = rt.watched.ids(&p); + rt.watched.remove(&p); + ids + }); + reload(app, ctx, ids); + } Msg::Event(EditorEvent::Closed(p)) => ROUND_TRIP.with_borrow_mut(|rt| rt.watched.remove(&p)), Msg::NoEvents(port, why) => { log::info!("edit in: no editor events on port {port} ({why}); polling for saves instead"); @@ -802,4 +811,71 @@ mod tests { assert_eq!(h.app.session.catalog.photo(id).unwrap().width, 32, "reloaded on document.saved"); let _ = std::fs::remove_dir_all(&dir); } + /// RT.B3 (P2 #1): when the host's open_with fails, an error toast is shown instead of + /// silently succeeding (the toast appears in app.ui.toast, not just app.ui.status). + #[test] + fn open_failure_shows_an_error_toast() { + let dir = temp("fail"); + let src = dir.join("fail.png"); + png(&src, 20, 12, 1); + let failed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let f = failed.clone(); + let services = crate::Services { + open_with: Some(Box::new( + move |_path: &str, _app: &str| { + if f.load(std::sync::atomic::Ordering::SeqCst) { Err("no such editor".into()) } else { Ok(()) } + }, + )), + ..Default::default() + }; + let mut h = crate::headless::Headless::new(LccApp::new(lcc_engine::Session::with_demo().with_fs(), services), [900.0, 600.0], 1.0); + // Simulate after_command being called with a successful editIn result + let result = json!({ + "path": "/tmp/fake-edit.tif", + "id": 1, + "original": 1, + "opened": null, + "openWith": { + "path": "/tmp/fake-edit.tif", + "app": "nonexistent-editor", + "args": [], + "reload": [1], + "preset": "", + "control": null + } + }); + // First try succeeds (no error toast) + after_command(&mut h.app, "photo.editIn", &result); + assert!(h.app.ui.toast.is_none(), "no error toast on success: {:?}", h.app.ui.toast); + // Second try fails + failed.store(true, std::sync::atomic::Ordering::SeqCst); + after_command(&mut h.app, "photo.editIn", &result); + let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + assert!(toast.contains("Couldn't open the editor") && toast.contains("no such editor"), "{toast:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// RT.B4 (P2 #3): when an editor process exits, the watched entry is removed from the table + /// so the 256-entry limit isn't reached by completed edits. + #[test] + fn editor_exit_removes_the_watched_entry() { + let dir = temp("exit-clean"); + let src = dir.join("clean.png"); + png(&src, 20, 12, 1); + let mut h = headless(&dir); + h.app.session.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap(); + let id = h.app.session.active().unwrap(); + watch(&mut h.app, &src, &[id.0]); + assert_eq!(watched_files(), 1, "the file is out for editing"); + // Simulate the editor exiting + ROUND_TRIP.with_borrow(|rt| { + assert_eq!(rt.watched.len(), 1); + }); + // Send an Exited message via the channel + let tx = ROUND_TRIP.with_borrow(|rt| rt.tx.clone()); + tx.send(Msg::Exited(src.clone())).unwrap(); + // Pump to process the message + h.step(); + assert_eq!(watched_files(), 0, "the exited file is removed from the watch table"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b077e0f6bd..a358727456 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -302,6 +302,11 @@ pub trait HdrOutput { /// Upload a linear-light render (3 floats per pixel, row-major, SDR white = 1, sRGB /// primaries) as the loupe's HDR texture, replacing the previous one. fn upload(&mut self, width: usize, height: usize, rgb: &[f32]) -> Result; + /// Whether the window surface is extended linear sRGB (macOS EDR / Windows scRGB): when + /// true, the renderer should skip monitor profile conversion (P2-3). + fn extended(&self) -> bool { + false + } } /// Grades a playing clip's frames on the window's GPU (desktop: the egui-wgpu device, through @@ -465,6 +470,8 @@ pub struct LccApp { screenshot_token: u64, /// Offscreen context for headless screenshots of the windowed app. shadow: Option, + /// True while rendering a headless (CPU) screenshot: don't use GPU-only textures. + headless_screenshotting: bool, /// Synthetic input events (from the control channel) injected one step per frame. pub synthetic: Vec, /// The text the UI last put on the clipboard (`ui.inspect` → `copied`). @@ -641,6 +648,7 @@ impl LccApp { pending_screenshots: vec![], screenshot_token: 0, shadow: None, + headless_screenshotting: false, synthetic: vec![], copied: None, pending_picks: vec![], @@ -1156,6 +1164,7 @@ impl LccApp { // same scroll offsets, open sections, style… as the window let memory = main.memory(|m| m.clone()); view.ctx.memory_mut(|m| *m = memory); + self.headless_screenshotting = true; view.run(headless::HeadlessView::raw_input(size, ppp, time, vec![]), |ui| self.ui(ui)); let img = capture.then(|| { let mut tex = self.renderer.cpu_textures(); @@ -1164,6 +1173,7 @@ impl LccApp { } view.paint(&tex) }); + self.headless_screenshotting = false; self.shadow = Some(view); img } diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index bda3969ea4..bda3fa8d42 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -156,12 +156,19 @@ impl CropView { } /// Lay the crop tool's view out in `area`: held as `layout` says while the crop is being changed, -/// otherwise the turned photo fitted into `area`. `frame` is the uncropped frame the loupe renders. -pub(crate) fn crop_view(frame: &Frame, crop: lcc_geom::CropGeometry, area: Rect, layout: Option) -> CropView { +/// otherwise the turned photo at `zoom` (fitted into `area` unless a percentage) and `pan`. `frame` is the uncropped frame the loupe renders. +pub(crate) fn crop_view( + frame: &Frame, + crop: lcc_geom::CropGeometry, + area: Rect, + layout: Option, + zoom: Zoom, + ppp: f32, + pan: (f32, f32), +) -> CropView { let cf = Frame { crop, ..frame.clone() }; let (nw, nh) = cf.native_size(); let (nw, nh) = ((nw as f32).max(1e-3), (nh as f32).max(1e-3)); - // the uncropped render's corners, as normalized photo points (its flips included) let uv_to_norm = frame.out_to_norm(1, 1); let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| uv_to_norm.apply(Point::new(u, v))); let finite = |k: f32| k.is_finite() && k > 0.0; @@ -172,12 +179,18 @@ pub(crate) fn crop_view(frame: &Frame, crop: lcc_geom::CropGeometry, area: Rect, Some(CropLayout::Pinned { centre, k }) if centre.is_finite() && finite(k) => (centre, k), _ => { // the turned photo at one point per pixel around a box centred on the origin, - // scaled and placed to fit the area + // scaled to the zoom asked for (or to fit the area) and placed as `pan` says let unit = CanvasMap::new(&cf, Rect::from_center_size(Pos2::ZERO, vec2(nw, nh))); let b = Rect::from_points(&corners.map(|c| unit.screen(c))); - let k = (area.width() / b.width()).min(area.height() / b.height()); + let k = match zoom { + Zoom::Percent(p) if finite(p) && finite(ppp) => p / 100.0 / ppp, + _ => (area.width() / b.width()).min(area.height() / b.height()), + }; let k = if finite(k) { k } else { 1.0 }; - (area.center() - b.center().to_vec2() * k, k) + let size = b.size() * k; + let pan = bounded_pan(area, size, pan); + let shift = vec2((pan.0 - 0.5) * size.x, (pan.1 - 0.5) * size.y); + (area.center() - shift - b.center().to_vec2() * k, k) } }; CanvasMap::new(&cf, Rect::from_center_size(centre, vec2(nw * k, nh * k))) @@ -726,7 +739,7 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { if !crop_tool || app.session.interaction.is_none() { app.crop_layout = None; } - let crop_view = crop_tool.then(|| crop_view(&frame, d.crop.geometry, main_area, app.crop_layout)); + let crop_view = crop_tool.then(|| crop_view(&frame, d.crop.geometry, main_area, app.crop_layout, app.ui.zoom, ppp, app.ui.pan)); if let Some(v) = &crop_view { if app.session.interaction.is_some() && app.crop_layout.is_none() { app.crop_layout = Some(CropLayout::Pinned { centre: v.centre, k: v.k }); @@ -809,7 +822,12 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { .then(|| app.session.render_job(id, rw.max(8), rh.max(8), false, !crop_tool)) .flatten() .map(|job| { - let job = hdr_view_job(job.with_hidden_grading(app.ui.grading_hidden_for(id))); + let headroom = app.services.hdr_output.as_mut().and_then(|o| o.headroom()); + // Tell the renderer whether to skip monitor profile conversion (P2-3). + if let Some(o) = app.services.hdr_output.as_ref() { + app.renderer.set_surface_extended_linear(o.extended()); + } + let job = hdr_view_job(job.with_hidden_grading(app.ui.grading_hidden_for(id)), headroom); let key = job.key; if app.renderer.hdr_view.is_none_or(|v| v.key != key) { app.renderer.request(Slot::HdrView, job, 98); @@ -948,9 +966,10 @@ pub fn show(app: &mut LccApp, ui: &mut egui::Ui) { // between photos, and the full render replaces them in place) let hdr_view = app.renderer.hdr_view.filter(|v| v.photo == id && Some(v.key) == hdr_key); let draw = |slot: Slot, r: Rect, clip: Rect| -> &'static str { - if slot == Slot::Main - && let Some(v) = hdr_view - { + // For headless (CPU) screenshots, the HDR texture is GPU-only and not available in the + // CPU texture map, so fall back to the SDR texture (P2-2). + let use_hdr = hdr_view.is_some() && !app.headless_screenshotting && slot == Slot::Main; + if use_hdr && let Some(v) = hdr_view { let image_rect = fit_texture_rect(r, v.size); p.with_clip_rect(clip).image(v.tex, image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); return "hdr"; @@ -1653,8 +1672,9 @@ fn targeted_drag(app: &mut LccApp, resp: &egui::Response, map: &CanvasMap, targe } /// The loupe's HDR render for an HDR display: `job` (a whole-frame render of the open photo, no -/// caches) as linear float with the HDR range ([`Slot::HdrView`]). Its own result key. -pub(crate) fn hdr_view_job(mut job: lcc_engine::media::RenderJob) -> lcc_engine::media::RenderJob { +/// caches) as linear float with the HDR range ([`Slot::HdrView`]). Its own result key, including the +/// headroom used for encoding so a headroom change re-uploads. +pub(crate) fn hdr_view_job(mut job: lcc_engine::media::RenderJob, headroom: Option) -> lcc_engine::media::RenderJob { job.request.depth = lcc_pipeline::OutputDepth::F32Hdr; job.request.space = lcc_pipeline::OutputSpace::Srgb; job.cache = None; @@ -1663,6 +1683,10 @@ pub(crate) fn hdr_view_job(mut job: lcc_engine::media::RenderJob) -> lcc_engine: job.display = None; job.request.display = None; job.key ^= 0x4844_525f_5649_4557; + // Include headroom in the key so a headroom change re-uploads the texture (P2-4). + if let Some(h) = headroom { + job.key ^= h.to_bits() as u64; + } job } @@ -3370,6 +3394,53 @@ mod tests { assert_eq!(flipped_corners(&v, false, true), screen); assert_eq!(flipped_corners(&hv, true, true), screen); } + + #[test] + fn hdr_view_job_key_includes_headroom() { + // A headroom change must produce a different render key so the texture is re-uploaded (P2-4). + let base = lcc_engine::media::RenderJob { + cache_generation: 0, + request_id: 1, + source_key: None, + photo: lcc_catalog::PhotoId(42), + level: lcc_engine::media::SourceLevel::Full, + source: lcc_engine::media::SourceRef::File { + path: "/tmp/test.jpg".to_string(), + max_edge: 100, + loader: None, + fallback: None, + denoise: None, + outliers: false, + }, + origin: lcc_catalog::Source::File { path: "/tmp/test.jpg".to_string() }, + info: Default::default(), + settings: Default::default(), + request: lcc_pipeline::RenderRequest { + max_w: 100, + max_h: 100, + quality: Default::default(), + apply_crop: false, + overlay: Default::default(), + space: Default::default(), + depth: Default::default(), + proof: None, + window: None, + display: None, + }, + key: 0, + cache: None, + view_cache: None, + stages: None, + display: None, + slide: None, + preview_cut: None, + }; + let k1 = super::hdr_view_job(base.clone(), Some(2.0)).key; + let k2 = super::hdr_view_job(base.clone(), Some(4.0)).key; + let k3 = super::hdr_view_job(base.clone(), None).key; + assert_ne!(k1, k2, "different headroom values must produce different keys"); + assert_ne!(k1, k3, "Some(headroom) must differ from None"); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 75e1dd9810..08b4320698 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -914,15 +914,14 @@ pub(crate) fn reorder_drop(app: &mut LccApp, ui: &mut egui::Ui, id: PhotoId, r: let Some(pos) = pos.filter(|p| r.contains(*p) && ui.clip_rect().contains(*p)) else { return }; let t = Tokens::get(ui.ctx()); let left = pos.x < r.center().x; - // inside the cell: the strip's cells touch + let ascending = app.session.sort.ascending; let x = if left { r.left() + 1.5 } else { r.right() - 1.5 }; - // above the thumbnails (the filmstrip paints a cell after deciding its drop) let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("reorder-drop"))).with_clip_rect(ui.clip_rect()); painter.line_segment([egui::pos2(x, r.top()), egui::pos2(x, r.bottom())], Stroke::new(3.0, t.accent)); if !released { return; } - let before = if left { + let before = if left == ascending { Some(id) } else { let vis = app.session.visible_cloned(); diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index 56eaad0e19..7d1b02604e 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -300,6 +300,9 @@ pub struct Renderer { /// Since when nothing has been pending, and whether the GPU pool was trimmed since. #[cfg(not(target_arch = "wasm32"))] idle: Option<(std::time::Instant, bool)>, + /// Surface is extended linear sRGB (macOS EDR / Windows scRGB): skip monitor profile + /// conversion, let the compositor do it (P2-3). + surface_is_extended_linear: bool, } /// After this long without renders the GPU renderer's pool of recycled buffers is freed. @@ -366,6 +369,17 @@ impl Renderer { display: None, #[cfg(not(target_arch = "wasm32"))] idle: None, + surface_is_extended_linear: false, + } + } + + /// Set whether the surface is extended linear sRGB (macOS EDR / Windows scRGB). When true, + /// skip monitor profile conversion and let the compositor do it (P2-3). + pub fn set_surface_extended_linear(&mut self, extended: bool) { + if self.surface_is_extended_linear != extended { + self.surface_is_extended_linear = extended; + // Forget all textures so they are re-rendered without the display profile. + self.forget_all(); } } } @@ -433,7 +447,9 @@ impl Renderer { /// `job` as [`Self::request`] would run it for `slot` (its key included): views render for /// the display profile in use. pub fn job_for(&self, slot: Slot, job: RenderJob) -> RenderJob { - if Self::renders_for_display(slot) { job.with_display(self.display.clone()) } else { job } + // When the surface is extended linear sRGB (macOS EDR / Windows scRGB), skip monitor + // profile conversion: the compositor owns it (P2-3). + if Self::renders_for_display(slot) && !self.surface_is_extended_linear { job.with_display(self.display.clone()) } else { job } } /// The display profile in use (id). @@ -1797,3 +1813,55 @@ mod color_image_tests { assert!(color_image(&img).pixels.is_empty()); } } + +#[cfg(test)] +mod extended_linear_tests { + use super::*; + + #[test] + fn job_for_skips_display_profile_for_extended_linear_surface() { + let mut r = Renderer::default(); + r.set_surface_extended_linear(true); + + let job = RenderJob { + cache_generation: 0, + request_id: 1, + source_key: None, + photo: lcc_catalog::PhotoId(1), + level: lcc_engine::media::SourceLevel::Full, + source: lcc_engine::media::SourceRef::File { + path: "/tmp/test.jpg".to_string(), + max_edge: 100, + loader: None, + fallback: None, + denoise: None, + outliers: false, + }, + origin: lcc_catalog::Source::File { path: "/tmp/test.jpg".to_string() }, + info: Default::default(), + settings: Default::default(), + request: lcc_pipeline::RenderRequest { + max_w: 100, + max_h: 100, + quality: Default::default(), + apply_crop: false, + overlay: Default::default(), + space: Default::default(), + depth: Default::default(), + proof: None, + window: None, + display: None, + }, + key: 0, + cache: None, + view_cache: None, + stages: None, + display: None, + slide: None, + preview_cut: None, + }; + + let result = r.job_for(Slot::Main, job.clone()); + assert!(result.display.is_none(), "display profile should be None for extended linear surface"); + } +} diff --git a/crates/ui-egui/src/render_dng_task.rs b/crates/ui-egui/src/render_dng_task.rs index 8c5fce6c7a..eb1c8113b5 100644 --- a/crates/ui-egui/src/render_dng_task.rs +++ b/crates/ui-egui/src/render_dng_task.rs @@ -23,6 +23,7 @@ pub struct RenderDngTask { done: Arc, rx: Receiver<(Vec, bool)>, guard: TaskGuard, + library_generation: u64, } /// Start Render to DNG for `p` on a worker → `{background: true, total}`; `None` when this app @@ -32,6 +33,7 @@ pub fn start(app: &mut LccApp, p: &Value) -> Option> { if app.render_dng.is_some() { return Some(Err("Render to DNG is already running".into())); } + let library_generation = app.session.library_generation(); let job = match render_dng::prepare(&mut app.session, p) { Ok(j) => j, Err(e) => return Some(Err(e.to_string())), @@ -60,7 +62,7 @@ pub fn start(app: &mut LccApp, p: &Value) -> Option> { } #[cfg(target_arch = "wasm32")] work(); - app.render_dng = Some(RenderDngTask { total, done, rx, guard }); + app.render_dng = Some(RenderDngTask { total, done, rx, guard, library_generation }); Some(Ok(json!({"background": true, "total": total}))) } @@ -69,8 +71,12 @@ pub fn poll(app: &mut LccApp, ctx: &egui::Context) { let Some(task) = &app.render_dng else { return }; match task.rx.try_recv() { Ok((done, cancelled)) => { - let total = task.total; + let (total, generation) = (task.total, task.library_generation); app.render_dng = None; + if app.session.library_generation() != generation { + app.toast(ctx, crate::i18n::tr("Render to DNG finished in a different library; DNGs were not imported")); + return; + } let msg = match render_dng::finish(&mut app.session, done, cancelled) { Ok(r) => { let ok = r["copies"].as_array().map_or(0, Vec::len); diff --git a/crates/ui-egui/src/tests_crop_frame.rs b/crates/ui-egui/src/tests_crop_frame.rs index fb5912e5e6..db458cad67 100644 --- a/crates/ui-egui/src/tests_crop_frame.rs +++ b/crates/ui-egui/src/tests_crop_frame.rs @@ -131,3 +131,25 @@ fn dragging_inside_the_box_moves_the_photo() { assert!(start.iter().zip(&now).all(|(a, b)| near(*a, *b)), "the box stays put: {start:?} → {now:?}"); release(&mut h, at + egui::vec2(40.0, 0.0)); } + +/// Zooming in the crop tool respects the requested zoom level (PR #1699). +#[test] +fn crop_respects_zoom_level() { + let mut h = cropped(); + let fit_rect = h.app.image_rect.unwrap(); + let r = h.request("engine.execute", json!({"command": "view.zoomLevel", "params": {"level": "2:1"}}), T); + assert_eq!(r["ok"], true, "{r}"); + h.settle(T); + let zoomed_rect = h.app.image_rect.unwrap(); + assert!( + zoomed_rect.width() > fit_rect.width() * 1.5 || zoomed_rect.height() > fit_rect.height() * 1.5, + "photo should be larger at 200% zoom: fit={fit_rect:?} zoomed={zoomed_rect:?}" + ); + h.app.ui.pan = (0.75, 0.5); + h.settle(T); + let panned_rect = h.app.image_rect.unwrap(); + assert!( + panned_rect.center().x < zoomed_rect.center().x - 5.0, + "photo should move left when panning right: zoomed={zoomed_rect:?} panned={panned_rect:?}" + ); +} diff --git a/crates/video-export/src/sequence.rs b/crates/video-export/src/sequence.rs index 731c899c52..6ac7479ea2 100644 --- a/crates/video-export/src/sequence.rs +++ b/crates/video-export/src/sequence.rs @@ -2,7 +2,8 @@ //! //! Same encoders and muxer as [`crate::export_clip`]; the frames come from the caller instead of //! a decoded clip. The file is written to `.partial` and renamed by [`SequenceWriter::finish`]; -//! dropping the writer unfinished (an error, a cancel) removes the partial file. +//! dropping the writer unfinished (an error, a cancel) removes the partial file. The writer holds a +//! lock on its partial file: one left by a crash is reused, one another export is writing is not. //! //! Sources: own design over FilmCraft's public crate APIs. @@ -15,6 +16,37 @@ use lcc_raster::Rgb32f; use crate::native::{ClipFormat, ClipReport, ExportClipError, MAX_FRAMES, MAX_SIDE, Result, VideoOut, enc, io, partial_path, ycbcr_with}; +/// Most partial files tried for one output (`.partial`, `.2.partial`, …). +const PARTIAL_SLOTS: u32 = 16; + +/// Open and lock a partial file for `out`: `.partial` unless another writer holds it (then +/// `.2.partial` and on), truncating a stale one a crashed export left. The lock lasts as long +/// as the file is open. +fn open_partial(out: &Path) -> Result<(PathBuf, File)> { + let first = partial_path(out)?; + for n in 1..=PARTIAL_SLOTS { + let path = if n == 1 { + first.clone() + } else { + let mut name = out.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".{n}.partial")); + out.with_file_name(name) + }; + // (no truncate on open: the file may be another writer's until the lock says otherwise) + let file = File::options().read(true).write(true).create(true).truncate(false).open(&path).map_err(io)?; + match file.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => continue, + // a file system without locks: take the file as before + Err(std::fs::TryLockError::Error(e)) if e.kind() == std::io::ErrorKind::Unsupported => {} + Err(std::fs::TryLockError::Error(e)) => return Err(io(e)), + } + file.set_len(0).map_err(io)?; + return Ok((path, file)); + } + Err(ExportClipError::BadOptions(format!("{} is being written by {PARTIAL_SLOTS} other exports", out.display()))) +} + /// Writes frames of one fixed size at a fixed rate to an H.264 MP4 or ProRes MOV (no audio). pub struct SequenceWriter { mux: Option>>, @@ -58,13 +90,12 @@ impl SequenceWriter { if fps_num == 0 || fps_den == 0 || f64::from(fps_num) / f64::from(fps_den) > 240.0 || f64::from(fps_num) / f64::from(fps_den) < 0.1 { return bad(format!("frame rate {fps_num}/{fps_den} is out of range")); } - let partial = partial_path(out)?; let brand = match format { ClipFormat::H264Mp4 => Brand::Mp4, ClipFormat::ProResMov => Brand::Mov, }; let video = VideoOut::new(format, quality.clamp(1, 100), width, height, fps_num, fps_den)?; - let file = File::create(&partial).map_err(io)?; + let (partial, file) = open_partial(out)?; let made = (|| { let mut mux = Mp4Writer::new(BufWriter::new(file), WriterOptions::new(brand)).map_err(enc)?; let track = mux.add_track(video.track_config()).map_err(enc)?; @@ -121,17 +152,22 @@ impl SequenceWriter { if self.frames == 0 { return Err(ExportClipError::BadOptions("no frames".into())); } - let mut mux = self.mux.take().ok_or(ExportClipError::Internal)?; + // Don't take mux yet; keep it in self.mux so Drop removes the partial + // file if any write fails. for p in self.video.flush() { + let mux = self.mux.as_mut().ok_or(ExportClipError::Internal)?; mux.write_sample(self.track, WriteSample { data: &p.data, duration: self.fps_den, composition_offset: p.cto, is_sync: p.key }) .map_err(enc)?; } let has_audio = self.audio.is_some(); if let Some((tr, a)) = self.audio.take() { for p in &a.packets { + let mux = self.mux.as_mut().ok_or(ExportClipError::Internal)?; mux.write_sample(tr, WriteSample { data: &p.data, duration: p.duration, composition_offset: 0, is_sync: true }).map_err(enc)?; } } + // All writes succeeded; now finalize and take the mux. + let mux = self.mux.take().ok_or(ExportClipError::Internal)?; let mut out = mux.finish().map_err(enc)?; out.flush().map_err(io)?; let file = out.into_inner().map_err(|e| io(e.error()))?; @@ -209,4 +245,52 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + /// A partial file a crashed export left behind is reused, not an error. + #[test] + fn a_stale_partial_file_is_reused() { + let dir = std::env::temp_dir().join(format!("lcc-seq-stale-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("t.mp4"); + std::fs::write(dir.join("t.mp4.partial"), b"leftover").unwrap(); + let w = SequenceWriter::create(&out, ClipFormat::H264Mp4, 80, 32, 16, 24, 1).unwrap(); + assert_eq!(w.partial, dir.join("t.mp4.partial")); + drop(w); + assert!(!dir.join("t.mp4.partial").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Two exports to one output write separate partial files; neither truncates the other's. + #[test] + fn a_partial_file_in_use_gets_a_second_name() { + let dir = std::env::temp_dir().join(format!("lcc-seq-busy-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("t.mp4"); + let mut a = SequenceWriter::create(&out, ClipFormat::H264Mp4, 80, 32, 16, 24, 1).unwrap(); + let b = SequenceWriter::create(&out, ClipFormat::H264Mp4, 80, 32, 16, 24, 1).unwrap(); + assert_eq!(a.partial, dir.join("t.mp4.partial")); + assert_eq!(b.partial, dir.join("t.mp4.2.partial")); + drop(b); + let img = Rgb32f::new(32, 16); + a.push_encoded(&img).unwrap(); + a.finish().unwrap(); + assert!(out.exists() && !dir.join("t.mp4.partial").exists() && !dir.join("t.mp4.2.partial").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn finish_with_no_frames_removes_partial_file() { + let dir = std::env::temp_dir().join(format!("lcc-seq-noframes-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("t.mp4"); + let w = SequenceWriter::create(&out, ClipFormat::H264Mp4, 80, 32, 16, 24, 1).unwrap(); + // Don't push any frames + let result = w.finish(); + assert!(result.is_err(), "expected error on no frames"); + // The partial file should be removed (not left behind) + let partial = dir.join("t.mp4.partial"); + assert!(!partial.exists(), "partial file should be removed on finish() error"); + assert!(!out.exists(), "output file should not exist on error"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/vendor/egui-wgpu/src/capture.rs b/vendor/egui-wgpu/src/capture.rs index 54ddeb884c..70f7aacb10 100644 --- a/vendor/egui-wgpu/src/capture.rs +++ b/vendor/egui-wgpu/src/capture.rs @@ -82,7 +82,7 @@ impl CaptureState { view_formats: &[], }); - let padding = BufferPadding::new(surface_texture.width()); + let padding = BufferPadding::new(surface_texture.width(), surface_texture.format()); let view = texture.create_view(&Default::default()); @@ -194,12 +194,13 @@ impl CaptureState { let format = self.texture.format(); let tex_extent = self.texture.size(); let padding = self.padding; + let is_float = matches!(format, wgpu::TextureFormat::Rgba16Float); let to_rgba = match format { - wgpu::TextureFormat::Rgba8Unorm => [0, 1, 2, 3], + wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba16Float => [0, 1, 2, 3], wgpu::TextureFormat::Bgra8Unorm => [2, 1, 0, 3], _ => { log::error!( - "Screen can't be captured unless the surface format is Rgba8Unorm or Bgra8Unorm. Current surface format is {format:?}" + "Screen can't be captured unless the surface format is Rgba8Unorm, Bgra8Unorm, or Rgba16Float. Current surface format is {format:?}" ); return; } @@ -221,13 +222,24 @@ impl CaptureState { }; for padded_row in mapped_range.chunks(padding.padded_bytes_per_row as usize) { let row = &padded_row[..padding.unpadded_bytes_per_row as usize]; - for color in row.chunks(4) { - pixels.push(epaint::Color32::from_rgba_premultiplied( - color[to_rgba[0]], - color[to_rgba[1]], - color[to_rgba[2]], - color[to_rgba[3]], - )); + if is_float { + // Rgba16Float holds extended linear sRGB: encode to gamma sRGB bytes (HDR + // highlights above SDR white clip) + for color in row.chunks(8) { + let c = |i: usize| f16_to_f32(u16::from_le_bytes([color[i], color[i + 1]])); + let [r, g, b] = [c(0), c(2), c(4)].map(epaint::ecolor::gamma_u8_from_linear_f32); + let a = epaint::ecolor::linear_u8_from_linear_f32(c(6)); + pixels.push(epaint::Color32::from_rgba_premultiplied(r, g, b, a)); + } + } else { + for color in row.chunks(4) { + pixels.push(epaint::Color32::from_rgba_premultiplied( + color[to_rgba[0]], + color[to_rgba[1]], + color[to_rgba[2]], + color[to_rgba[3]], + )); + } } } drop(mapped_range); @@ -247,6 +259,20 @@ impl CaptureState { } } +/// Decode a half float (f16) bit pattern. Subnormals flush to zero and NaN to zero; infinities keep +/// their sign (the byte encoders clamp them). +fn f16_to_f32(bits: u16) -> f32 { + let sign = if bits >> 15 == 1 { -1.0 } else { 1.0 }; + let exp = i32::from((bits >> 10) & 31); + let mantissa = f32::from(bits & 0x3FF); + match exp { + 0 => 0.0, + 31 if mantissa == 0.0 => sign * f32::INFINITY, + 31 => 0.0, + _ => sign * (1.0 + mantissa / 1024.0) * 2f32.powi(exp - 15), + } +} + #[derive(Copy, Clone)] struct BufferPadding { unpadded_bytes_per_row: u32, @@ -254,8 +280,8 @@ struct BufferPadding { } impl BufferPadding { - fn new(width: u32) -> Self { - let bytes_per_pixel = core::mem::size_of::() as u32; + fn new(width: u32, format: wgpu::TextureFormat) -> Self { + let bytes_per_pixel = format.block_copy_size(None).unwrap_or(4); let unpadded_bytes_per_row = width * bytes_per_pixel; let padded_bytes_per_row = wgpu::util::align_to(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT); @@ -265,3 +291,33 @@ impl BufferPadding { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buffer_padding_uses_format_bytes_per_pixel() { + // u32 (Rgba8Unorm) = 4 bytes per pixel + let p8 = BufferPadding::new(1280, wgpu::TextureFormat::Rgba8Unorm); + assert_eq!(p8.unpadded_bytes_per_row, 5120); + + // Rgba16Float = 8 bytes per pixel + let p16 = BufferPadding::new(1280, wgpu::TextureFormat::Rgba16Float); + assert_eq!(p16.unpadded_bytes_per_row, 10240); + } + + #[test] + fn f16_decodes_sign_range_and_specials() { + assert_eq!(f16_to_f32(0x0000), 0.0); + assert_eq!(f16_to_f32(0x3C00), 1.0); + assert_eq!(f16_to_f32(0x3800), 0.5); + assert_eq!(f16_to_f32(0x4000), 2.0); + assert_eq!(f16_to_f32(0xB800), -0.5); + assert_eq!(f16_to_f32(0x7C00), f32::INFINITY); + assert_eq!(f16_to_f32(0x7E00), 0.0); + // negative (out-of-gamut scRGB) and above-white values clamp when encoded + assert_eq!(epaint::ecolor::gamma_u8_from_linear_f32(f16_to_f32(0xB800)), 0); + assert_eq!(epaint::ecolor::gamma_u8_from_linear_f32(f16_to_f32(0x4000)), 255); + } +}