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
42 changes: 39 additions & 3 deletions crates/engine/src/camera_profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,19 @@ pub fn save(profile: &CameraProfile, dir: &Path) -> Result<PathBuf, String> {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let path = dir.join(file_name(&profile.model));
let json = serde_json::to_vec_pretty(profile).map_err(|e| e.to_string())?;
// Other spellings of the model map to the same file (`Foo Bar` and `Foo_Bar`), so every cached lookup of that file
// is dropped. Both locks are held across the write, the invalidation and the render-cache key refresh, so a
// concurrent lookup or render key cannot pair the new profile with the old key. Lock order: cache, then key.
let saved_name = file_name(&profile.model);
let mut cache_guard = cache().lock().unwrap_or_else(PoisonError::into_inner);
let mut key_guard = cache_key_slot().lock().unwrap_or_else(PoisonError::into_inner);
// a fresh temp file renamed over the profile: never a fixed `.tmp` name, which a planted link
// would have written through
lcc_catalog::safe_file::write_atomic(&path, &json).map_err(|e| format!("{}: {e}", path.display()))?;
// Drop any cached lookup for this model: an earlier miss must not hide the profile just saved (upstream #3938).
cache().lock().unwrap_or_else(PoisonError::into_inner).remove(profile.model.trim());
cache_guard.retain(|model, _| file_name(model) != saved_name);
// The key always describes dir(), not the directory this save wrote to.
*key_guard = Some(cache_key_for(self::dir().as_deref()));
Ok(path)
}

Expand Down Expand Up @@ -180,8 +188,19 @@ pub fn get(model: &str) -> Option<Arc<CameraProfile>> {
/// Changes when the profiles folder's contents change (per process): part of the render cache
/// keys, so thumbnails rendered before a profile existed are not reused after.
pub fn cache_key() -> u64 {
static KEY: OnceLock<u64> = OnceLock::new();
*KEY.get_or_init(|| cache_key_for(dir().as_deref()))
let slot = cache_key_slot();
if let Some(key) = *slot.lock().unwrap_or_else(PoisonError::into_inner) {
return key;
}
// Scan the folder without holding the lock, so a refresh is not blocked on the IO.
let key = cache_key_for(dir().as_deref());
let mut guard = slot.lock().unwrap_or_else(PoisonError::into_inner);
*guard.get_or_insert(key)
}

fn cache_key_slot() -> &'static Mutex<Option<u64>> {
static KEY: OnceLock<Mutex<Option<u64>>> = OnceLock::new();
KEY.get_or_init(|| Mutex::new(None))
}

fn cache_key_for(directory: Option<&Path>) -> u64 {
Expand Down Expand Up @@ -626,6 +645,23 @@ mod tests {
assert_ne!(before_key, after_key, "a changed profile must not reuse the previous render cache");
}

#[test]
fn saving_a_profile_drops_cached_misses_of_other_spellings() {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
let alias = format!("TESTALIAS {} {stamp}", std::process::id());
let saved_model = alias.replace(' ', "_");
assert_eq!(file_name(&alias), file_name(&saved_model));
cache().lock().unwrap_or_else(PoisonError::into_inner).insert(alias.clone(), None);
let folder = std::env::temp_dir().join(format!("lc-camera-profile-alias-{}-{stamp}", std::process::id()));
let mut saved = profile();
saved.model = saved_model;
let saved_ok = save(&saved, &folder).is_ok();
let still_cached = cache().lock().unwrap_or_else(PoisonError::into_inner).contains_key(&alias);
let _ = std::fs::remove_dir_all(&folder);
assert!(saved_ok);
assert!(!still_cached, "saving a profile must invalidate the cached miss for {alias:?}, which maps to the same file");
}

#[test]
fn saved_profile_is_found_after_earlier_miss() {
let model = format!(
Expand Down
37 changes: 37 additions & 0 deletions crates/engine/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1547,6 +1547,21 @@ fn file_modified(path: &str) -> Option<String> {
lcc_catalog::dates::local(secs)
}

/// Whether the file at `path` is as it was when `info` probed it: still a file, the same size and the same
/// modification time (to the second, as the probe records it). A file edited in place keeps its size when only
/// a few bytes change (an embedded XMP packet rewritten at the same length), so the size alone can't tell; for
/// the same reason a file whose modification time isn't known, now or then, counts as changed (upstream #3607).
pub(crate) fn probe_still_valid(path: &str, info: &ProbeInfo) -> bool {
let Ok(meta) = std::fs::metadata(path) else { return false };
if !meta.is_file() || meta.len() != info.file_size {
return false;
}
match (file_modified(path), info.file_modified.as_deref()) {
(Some(now), Some(then)) => now == then,
_ => false,
}
}

impl crate::Session {
/// Install the filesystem file hooks (desktop, CLI, MCP headless), and on macOS the Apple Photos
/// runner ([`crate::apple_photos::osascript`]; installed, not run).
Expand Down Expand Up @@ -2095,6 +2110,28 @@ pub(crate) mod tests {
assert!(window.starts_with(&[0xff, 0xd8]), "and hands on the JPEG");
}

/// A scan's probe is reused only for a file as it was: a file rewritten at the same size has another
/// modification time, and a file with no known time on either side counts as changed (upstream #3607).
#[test]
fn a_probe_is_reused_only_for_a_file_with_the_same_size_and_modification_time() {
let dir = std::env::temp_dir().join(format!("lcc-probe-valid-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("a.jpg");
std::fs::write(&path, [0u8; 10]).unwrap();
let path = path.to_string_lossy().to_string();
let now = file_modified(&path);
assert!(now.is_some());
let probed = |size: u64, modified: Option<String>| ProbeInfo { file_size: size, file_modified: modified, ..ProbeInfo::default() };
assert!(probe_still_valid(&path, &probed(10, now.clone())));
assert!(!probe_still_valid(&path, &probed(9, now.clone())), "another size");
assert!(!probe_still_valid(&path, &probed(10, None)), "no time when probed");
let earlier = std::fs::metadata(&path).unwrap().modified().unwrap() - std::time::Duration::from_secs(3600);
let earlier_secs = earlier.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
assert!(!probe_still_valid(&path, &probed(10, lcc_catalog::dates::local(earlier_secs as i64))), "rewritten since");
assert!(!probe_still_valid(&dir.join("gone.jpg").to_string_lossy(), &probed(10, now)), "gone");
let _ = std::fs::remove_dir_all(&dir);
}

/// A JPEG with no date in its metadata (an export saved without it) takes the file's date, as
/// in Lightroom, instead of grouping under "Unknown Date"; a dated one keeps its capture time.
#[test]
Expand Down
11 changes: 5 additions & 6 deletions crates/engine/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1034,7 +1034,7 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &Sc
let by_path = library_files(&input.library, &files);
let todo: Vec<String> = files.iter().filter(|f| !by_path.contains_key(Path::new(f))).cloned().collect();
progress.total.store(todo.len(), Relaxed);
// probes from a preceding `scan` are reused when the file is unchanged (same size)
// probes from a preceding `scan` are reused when the file is unchanged (same size and modification time)
let cached: Vec<Option<ProbeInfo>> = todo
.iter()
.map(|f| {
Expand All @@ -1044,8 +1044,9 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &Sc
if progress.cancel.load(Relaxed) {
return None;
}
let size = std::fs::metadata(f).map(|m| m.len()).ok();
(size.is_none() || size == Some(info.file_size)).then_some(info)
// (a file that can't be looked at counts as unchanged; one that can is reused only as it was,
// size and modification time)
(std::fs::metadata(f).is_err() || crate::files::probe_still_valid(f, &info)).then_some(info)
})
.collect();
let missing: Vec<String> = todo.iter().zip(&cached).filter(|(_, c)| c.is_none()).map(|(f, _)| f.clone()).collect();
Expand Down Expand Up @@ -1441,9 +1442,7 @@ impl ImportJob {
.iter()
.map(|f| {
// (the web's files are not std::fs files: kept as probed)
self.cache
.remove(f)
.filter(|info| cfg!(target_arch = "wasm32") || std::fs::metadata(f).is_ok_and(|m| m.is_file() && m.len() == info.file_size))
self.cache.remove(f).filter(|info| cfg!(target_arch = "wasm32") || crate::files::probe_still_valid(f, info))
})
.collect();
let missing: Vec<String> = todo.iter().zip(&cached).filter(|(_, c)| c.is_none()).map(|(f, _)| f.clone()).collect();
Expand Down
20 changes: 19 additions & 1 deletion crates/engine/src/preset_import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,13 @@ pub(crate) fn build(props: &Props, values: &crate::crs_masks::Values, name: Stri
if let Some(look) = crate::profile_refs::look_ref(props)
&& let Some(o) = settings.as_object_mut()
{
o.insert("profile".into(), serde_json::json!({"look": look}));
// next to the profile settings the preset already sets (`camera_local_tone`), not in place of them (upstream #3752)
let profile = o.entry("profile").or_insert_with(|| serde_json::json!({}));
if let Some(p) = profile.as_object_mut() {
p.insert("look".into(), look);
} else {
*profile = serde_json::json!({"look": look});
}
}
if settings.as_object().is_none_or(Map::is_empty) {
return None;
Expand Down Expand Up @@ -772,6 +778,18 @@ text]], z = ZSTR "loc" }"#,
assert_eq!(d.light.exposure, 0.35);
}

/// A ProRAW preset keeps the camera local tone mapping its "Apple ProRaw" look turns on, next to the look it names.
#[test]
fn apple_proraw_preset_keeps_the_local_tone_mapping_with_its_look() {
let t = r#"s = { title = "ProRaw", value = { settings = { Exposure2012 = 0.2,
Look = { Name = "Apple ProRaw", Amount = 1, UUID = "D866CAE82BD24C3F896B6762BDDA6C50",
Parameters = { Version = "18.5.1", ProfileGainTableMap = 100 } } } } }"#;
let v = read_presets("ProRaw.lrtemplate", t.as_bytes(), None).unwrap();
let profile = &v[0].preset.settings["profile"];
assert_eq!(profile["camera_local_tone"], true, "{profile}");
assert_eq!(profile["look"]["name"], "Apple ProRaw", "{profile}");
}

#[test]
fn lrtemplate_keeps_the_profile_it_names() {
let t = r#"s = { title = "Film", value = { settings = { Exposure2012 = 0.2,
Expand Down
Loading