Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@
# model weights are never committed (SAM 3: docs/ai-masks.md)
*.safetensors
*.safetensors.part

# aider
.aider*
3 changes: 3 additions & 0 deletions apps/app/src/hdr_display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,9 @@ impl WindowHdr {
}

impl lcc_ui_egui::HdrOutput for WindowHdr {
fn extended(&self) -> bool {
self.extended
}
fn headroom(&mut self) -> Option<f32> {
let info = self.state.display_hdr_info.read().clone();
let l = levels(Platform::current(), info.as_ref(), self.headroom_override, self.paper_white_override);
Expand Down
61 changes: 52 additions & 9 deletions crates/engine/src/cmd/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,15 +427,18 @@ pub fn edit_specs() -> Vec<CommandSpec> {
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 `<name>-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 `<name>-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
)
},
]
}

Expand Down Expand Up @@ -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");
}
}
73 changes: 72 additions & 1 deletion crates/engine/src/cmd/edit_in/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,11 @@ pub fn file_xmp(path: &Path) -> Option<String> {
}
}

/// 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
Expand All @@ -245,7 +250,7 @@ pub fn stack_derived(s: &mut Session, imported: &[PhotoId]) -> Vec<PhotoId> {
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 };
Expand All @@ -261,16 +266,38 @@ pub fn stack_derived(s: &mut Session, imported: &[PhotoId]) -> Vec<PhotoId> {
// (folder, file name) and document id → photo, built once
let mut by_name: HashMap<(String, String), PhotoId> = HashMap::new();
let mut by_doc: HashMap<String, PhotoId> = 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
Expand Down Expand Up @@ -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<u64> = 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);
}
}
88 changes: 83 additions & 5 deletions crates/engine/src/lightroom_smart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,11 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result<Rule, String> {
_ => 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" {
Expand All @@ -160,6 +159,18 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result<Rule, String> {
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",
Expand Down Expand Up @@ -197,6 +208,20 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result<Rule, String> {
_ => 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",
Expand All @@ -212,7 +237,6 @@ fn criterion(c: &Lua, collections: &[(&str, AlbumId)]) -> Result<Rule, String> {
"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)
Expand All @@ -228,7 +252,10 @@ fn text_rule(target: &str, op: &str, value: &str) -> Option<Rule> {
"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" => {
Expand Down Expand Up @@ -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");
}
}
}
1 change: 1 addition & 0 deletions crates/engine/src/render_dng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub fn prepare(s: &mut Session, p: &Value) -> Result<RenderDngJob> {
color_space: space,
naming: "{name}-Rendered".into(),
conflict: Conflict::Unique,
hdr: true,
..Default::default()
};
let mut items = Vec::with_capacity(ids.len());
Expand Down
19 changes: 19 additions & 0 deletions crates/engine/src/tests_custom_order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,22 @@ fn new_album_from_selection_keeps_the_shown_order() {
let got: Vec<u64> = 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:?}");
}
8 changes: 4 additions & 4 deletions crates/pipeline/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ pub struct PlaneSigmas {
pub chroma: Option<f32>,
}

/// 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 {
Expand All @@ -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
Expand Down
Loading