Merge main (85c38c487b) into pr/upright-posts

Conflicts:
docs/parity-checklist.md

Ported: the locale and docs conflicts keep both sides' entries.
This commit is contained in:
FredApps committed 2026-11-27 00:31:05 +07:00
commit ce0dd7e03a
83 files changed
+3571 -307

No files matched your search

Generated
+53
View File
@@ -3576,6 +3576,58 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jiff"
version = "0.2.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f"
dependencies = [
"jiff-core",
"jiff-static",
"jiff-tzdb-platform",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
]
[[package]]
name = "jiff-core"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b"
dependencies = [
"log",
]
[[package]]
name = "jiff-static"
version = "0.2.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba"
dependencies = [
"jiff-core",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "jiff-tzdb"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2"
[[package]]
name = "jiff-tzdb-platform"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"
dependencies = [
"jiff-tzdb",
]
[[package]]
name = "jixel"
version = "0.3.4"
@@ -4130,6 +4182,7 @@ dependencies = [
"crc32fast",
"fs4",
"harfrust 0.13.3",
"jiff",
"libc",
"lightcraft-catalog",
"lightcraft-codecs",
+6
View File
@@ -101,6 +101,12 @@ libm = "0.2" # pure-Rust maths for lightcraft-film (target-independent results)
libc = "0.2" # dev-only: process CPU time in benches
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
# The host's time zone: the catalog stores local civil times, so a file's modification time and
# the session clock need the UTC offset in force at that instant (DST included). Native only; the
# web build keeps its fixed clock. Zero dependencies on Unix (it reads the system tzdb); on Windows
# it embeds one, since Windows has no canonical copy.
jiff = { version = "0.2", default-features = false, features = ["std", "tz-system", "tzdb-zoneinfo", "tzdb-bundle-platform"] }
# formats
miniz_oxide = "0.9"
+2 -2
View File
@@ -62,8 +62,8 @@ BIZ UDPGothic Regular, Noto Sans Thai Regular, Noto Sans Georgian Regular and No
Regular, and loads Noto Sans CJK SC separately. Release packages include each font's licence as
OFL-<family>.txt; Windows installers include their texts in FONT-LICENCES.txt.
Place names for reverse geocoding (Photo > Fill Location from GPS) are not part of LightCraft and
are never distributed with it. On the user's request (Photo > Download Place Names) the app
Place names for reverse geocoding (Photo > Metadata > Fill Location from GPS) are not part of LightCraft and
are never distributed with it. On the user's request (Photo > Metadata > Download Place Names) the app
downloads cities15000.zip, admin1CodesASCII.txt and countryInfo.txt from GeoNames
(https://download.geonames.org/export/dump/) into the settings folder. GeoNames data is licensed
under Creative Commons Attribution 4.0 (https://creativecommons.org/licenses/by/4.0/);
+4
View File
@@ -190,6 +190,10 @@ impl Store for FilesStore {
self.0.truncate(name, len as usize);
Ok(())
}
/// The browser always runs the newest build, and its storage is small.
fn keeps_replaced_formats(&self) -> bool {
false
}
fn describe(&self) -> String {
"browser storage".into()
}
+6 -2
View File
@@ -76,7 +76,7 @@ use launch::{
};
#[cfg(test)]
use platform::{explorer_select_arg, explorer_select_command, windows_open_url_command};
use prefs::{PrefsWriter, as_remembered, load_prefs, prefs_path};
use prefs::{MAXIMIZE_LATER, PrefsWriter, as_remembered, load_prefs, prefs_path};
#[cfg(test)]
use prefs::{load_prefs_at, write_atomic};
use session::{open_session, services};
@@ -555,7 +555,7 @@ fn main() -> eframe::Result {
let opens_as = prefs.as_ref().and_then(|ui| ui.window).and_then(lightcraft_ui_egui::window_place::WindowPlace::checked);
let options = eframe::NativeOptions {
renderer,
viewport: as_remembered(egui::ViewportBuilder::default().with_title(lightcraft_ui_egui::channel::name()), opens_as)
viewport: as_remembered(egui::ViewportBuilder::default().with_title(lightcraft_ui_egui::channel::name()), opens_as, MAXIMIZE_LATER)
.with_min_inner_size(lightcraft_ui_egui::window_place::MIN_SIZE)
.with_drag_and_drop(true)
.with_transparent(window_gpu::composes_window(compose_window, window_renderer))
@@ -640,6 +640,10 @@ fn main() -> eframe::Result {
written: serde_json::to_vec_pretty(&app.ui).unwrap_or_default(),
library: app.ui.settings.library_path.clone(),
keep_file: keep_prefs_file,
start: Some(
lightcraft_ui_egui::window_place::StartPlace::new(MAXIMIZE_LATER && opens_as.is_some_and(|w| w.zoomed))
.remembered(opens_as.map(|w| w.size)),
),
..Default::default()
};
// a library opened from its catalog file is the one in use from now on, as Open Library makes it
+34 -3
View File
@@ -24,13 +24,24 @@ pub(crate) fn config_dir() -> Option<std::path::PathBuf> {
/// The window at the size it was last used at, zoomed if it was (`window`), or at the usual size
/// when nothing is remembered. A zoomed window is given the size it goes back to. Where it
/// opens is the system's to say.
pub(crate) fn as_remembered(builder: egui::ViewportBuilder, window: Option<lightcraft_ui_egui::window_place::WindowPlace>) -> egui::ViewportBuilder {
///
/// Windows: a window built maximized could open covering half the screen while
/// the system took it for maximized, so there (`maximize_later`) it is built at its size and
/// maximized once it shows ([`lightcraft_ui_egui::window_place::StartPlace`]).
pub(crate) fn as_remembered(
builder: egui::ViewportBuilder,
window: Option<lightcraft_ui_egui::window_place::WindowPlace>,
maximize_later: bool,
) -> egui::ViewportBuilder {
let builder = builder.with_inner_size(window.map_or(lightcraft_ui_egui::window_place::DEFAULT_SIZE, |w| w.size));
// (only ever asked to zoom: asked not to, macOS un-zooms a window whose size fills the screen
// to a size of its own choosing)
if window.is_some_and(|w| w.zoomed) { builder.with_maximized(true) } else { builder }
if window.is_some_and(|w| w.zoomed) && !maximize_later { builder.with_maximized(true) } else { builder }
}
/// Windows maximizes a remembered maximized window once it shows (see [`as_remembered`]).
pub(crate) const MAXIMIZE_LATER: bool = cfg!(target_os = "windows");
/// `<config>/ui.json`, the saved UI state and app settings — `None` when nothing is read or
/// written: `LIGHTCRAFT_NO_PREFS` (tests, scripts) or no home folder.
pub(crate) fn prefs_path() -> Option<std::path::PathBuf> {
@@ -161,6 +172,9 @@ pub(crate) struct PrefsWriter {
/// When the window was first looked at: its watch goes by the clock from then on, not by
/// the interface's time, which stands still while the window is hidden.
pub(crate) window_since: Option<std::time::Instant>,
/// The window as it first shows: maximized then on Windows, fitted to a smaller screen.
/// `None` once done, and in tests.
pub(crate) start: Option<lightcraft_ui_egui::window_place::StartPlace>,
}
impl PrefsWriter {
@@ -221,7 +235,24 @@ impl PrefsWriter {
// `run_logic` pass has no fresh content rect: keep the last known placement.
let remembered = app.ui.window.and_then(lightcraft_ui_egui::window_place::WindowPlace::checked);
let at = self.window_since.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64();
if !hidden {
// (while the window is being placed it is not remembered: it may not be as it will be; a
// hidden pass's stale size places nothing)
let placing = self.start.is_some();
if let Some(start) = &mut self.start {
if !hidden {
for command in start.step(&seen, at, zoom) {
ctx.send_viewport_cmd(command);
}
} else {
// (hidden: nothing to place by, but the time limit still runs)
start.idle(at);
}
match start.waits() {
Some(wait) => ctx.request_repaint_after(wait),
None => self.start = None,
}
}
if !hidden && !placing {
app.ui.window = self.window.note(remembered, &seen, at);
}
if let Some(wait) = self.window.waits(at) {
+6 -3
View File
@@ -660,12 +660,15 @@ fn ui_json_is_written_atomically() {
#[test]
fn the_window_opens_as_it_was() {
use lightcraft_ui_egui::window_place::{DEFAULT_SIZE, WindowPlace};
let fresh = as_remembered(egui::ViewportBuilder::default(), None);
let fresh = as_remembered(egui::ViewportBuilder::default(), None, false);
assert_eq!((fresh.inner_size, fresh.position, fresh.maximized), (Some(egui::Vec2::from(DEFAULT_SIZE)), None, None));
let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: true }));
let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: true }), false);
assert_eq!((b.inner_size, b.position, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None, Some(true)));
// Windows: built at its size, maximized once it shows
let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: true }), true);
assert_eq!((b.inner_size, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None));
// (not asked to un-zoom: macOS would then resize a window that fills its screen)
let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: false }));
let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: false }), false);
assert_eq!((b.inner_size, b.position, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None, None));
}
@@ -0,0 +1,5 @@
{"seq":4,"crc":2044174370,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"Temperature","edited":"2026-10-10T14:00:00"}}
{"seq":5,"crc":1983535997,"op":{"op":"pushHistory","id":8,"step":{"label":"Temperature","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}}}}
{"seq":6,"crc":3297692306,"op":{"op":"setMeta","id":8,"meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"Harbour","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":["boats"]}}}
{"seq":7,"crc":4123692544,"op":{"op":"setRating","id":9,"rating":3}}
{"seq":8,"crc":1875893688,"op":{"op":"setVersions","id":9,"versions":[{"name":"Rich","created":"2026-10-10T14:05:00","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibrLine truncated
@@ -0,0 +1 @@
{"format":"lightcraft-catalog","version":6,"seq":3,"catalog":{"photos":{"7":{"id":7,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0007.jpg"},"file_name":"IMG_0007.jpg","kind":"raw","format":"JPEG","width":4032,"height":3024,"file_size":25000000,"captured":"2019-07-14T15:21:07","imported":"2026-10-10T12:00:00","meta":{"camera":"Camera Model X","lens":"24-70mm f/2.8","focal_mm":35.0,"aperture":4.0,"shutter":"1/250","iso":400,"location":"Old harbour","city":"Lisbon","state":"Lisboa","country":"Portugal","gps":[38.7,-9.1],"title":"Harbour","caption":"Boats at dusk","alt_text":"Three boats","extended_description":"Three boats moored at dusk","copyright":"(c) Someone","copyright_status":"copyrighted","usage_terms":"All rights reserved","copyright_url":"https://example.org/rights","creator":"Someone","keywords":["Places|Lisbon","boats"],"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.3,"y1":0.4},"kind":"Face","name":"Ana","description":null}]},"rating":4,"flag":"pick","label":"green","develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"Line truncated
+300 -20
View File
@@ -47,7 +47,9 @@
//! # Format versions
//!
//! The snapshot's `version` is the catalog format, and it covers the log beside it: the log has
//! no header of its own, and is only ever appended to under a snapshot of this build's format.
//! no header of its own, and is appended to under a snapshot of this build's format. (Except
//! for a library left in an older format because its files could not be kept or its upgrade
//! written: it goes on as it is, and its log gets this build's ops until a snapshot upgrades it.)
//!
//! | Version | Written by | Adds |
//! |---|---|---|
@@ -75,7 +77,27 @@
//! - **Opening an older format upgrades it**: right after loading, [`Journal::open`] writes a
//! snapshot in this build's format (also for a new library), before anything is appended — so a
//! library is never a mix, and older builds refuse it from then on instead of reading part of it.
//! [`LoadReport::upgraded_from`] says when that happened.
//! (Except where the upgrade can't be written or its files can't be kept: see the next rule.)
//! [`LoadReport::upgraded_from`] says when the upgrade happened at open.
//! - **An upgrade keeps what it replaces**: older builds can't read the upgraded library, so the
//! files it was are first kept beside it as `catalog.snap.v<format>-<seq>` and
//! `catalog.log.v<format>-<seq>` (`seq`: the last change they hold), byte for byte
//! ([`LoadReport::kept`]; a damaged log is kept under its own name instead, as it always was).
//! A file already there under one of the names above is never replaced or removed (a library
//! restored from an older backup can reach the same format and change as a set kept before):
//! other bytes make both names end `-2` (then `-3`, … up to 100 sets, then the upgrade is
//! refused), the same bytes are the copy already. Put back under
//! their own names, they are the library as the older build left it (what a later snapshot
//! keeps is the library as it was at open: a torn tail already cut, and what a session of this
//! build appended while it stayed in its old format, which an older build may refuse). They stay unless the
//! library on disk is known to be in its old format still: an upgrade at open that did not
//! happen leaves none of the copies it wrote (one that was there before stays), and one that was written keeps its copy whatever fails after it.
//! Nothing removes them afterwards: they are the user's to delete. (Not where the store says
//! there is no going back, [`Store::keeps_replaced_formats`].) A library left in its old format
//! at open (its files couldn't be kept, or the upgrade couldn't be written) is upgraded by a
//! later snapshot (compaction, or closing), which first keeps the files as they were at open
//! (the snapshot, and the log up to where it ended then) and is not written when it can't. Those
//! files stay even if that snapshot then fails and the library is still in its old format.
//! - **A newer format is refused, untouched**: a snapshot whose `version` is above [`VERSION`],
//! or a log record whose CRC matches (so it is exactly what was written) but whose op doesn't
//! parse, fails [`Journal::open`] with [`CatalogError::Newer`] before any file is modified — it
@@ -105,6 +127,29 @@ impl Default for SnapshotPolicy {
}
}
/// How much an upgrade to this build's format is needed (see [`Journal::upgrade`]).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Upgrade {
/// The library may go on as it is if it can't be upgraded now.
May,
/// The library can't be used as it is: its damaged log would be appended to after the damage,
/// so the snapshot must also have replaced that log.
Repair,
}
/// The files kept for one upgrade (see [`Journal::keep_replaced`]).
#[derive(Default)]
struct Kept {
/// All of them: the snapshot, then the log.
names: Vec<String>,
/// Those this attempt wrote. The others were there already, byte for byte the same.
created: Vec<String>,
}
/// How many sets of kept files with the same format and change can stand side by side before a
/// further one is refused (an upgrade that can't keep its files is not done).
const MAX_KEPT_COPIES: u32 = 100;
/// What happened while loading.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LoadReport {
@@ -130,6 +175,13 @@ pub struct LoadReport {
pub upgraded_from: Option<u32>,
/// What [`Catalog::repair`] changed in a damaged snapshot (empty for a sound one).
pub repaired: Vec<String>,
/// The files that upgrade replaced, kept beside the library under these names (the snapshot,
/// then the log; a file there was none of has no copy).
pub kept: Vec<String>,
/// The store keeps the files an upgrade replaces ([`Store::keeps_replaced_formats`]): a
/// store that doesn't (the browser's) has no copy of the library as it was, whatever else it
/// set aside (a damaged log).
pub kept_files: bool,
}
/// Where persistence time goes (reported by `library.info` → `persistence`; printed to stderr
@@ -196,6 +248,21 @@ pub struct Journal {
/// `seq` of the last durable op.
seq: u64,
snapshot_seq: u64,
/// The snapshot in the store is still in an older format (`Some(format)`): the library was
/// not upgraded at open, because its files could not be kept or the upgrade could not be
/// written. A later snapshot (a compaction, or closing) writes the upgrade then,
/// and keeps the files first ([`Journal::keep_before_upgrade`]).
behind: Option<u32>,
/// What the library was at open while `behind` is set: the `seq` its files held and the
/// length of its log. Appends only add to the log after that, so the first `log_len` bytes
/// and the snapshot are the library as this session opened it, whatever is appended
/// meanwhile (an earlier session of this build may have appended already, while the library
/// stayed in its old format: that is in them, and an older build may refuse it).
behind_at: (u64, u64),
/// The files [`Journal::keep_before_upgrade`] kept for a snapshot that is not written yet,
/// and, once that snapshot is, the names for [`Journal::take_kept`].
kept_pending: Option<Vec<String>>,
kept_written: Vec<String>,
log_records: u64,
log_bytes: u64,
pub policy: SnapshotPolicy,
@@ -429,23 +496,27 @@ struct SnapFile {
impl Journal {
/// Open (or create) the catalog in `store`: load the snapshot, replay the log, repair a torn
/// tail. Fails only if the snapshot itself is unreadable (then nothing is modified).
/// tail. Fails if the snapshot is unreadable or a newer LightCraft's (then nothing is
/// modified), or if the library is in an older format and its damaged log can't be replaced,
/// its snapshot can't be kept, or it can't be told whether its upgrade was written (see the
/// module docs → *Format versions*).
pub fn open(mut store: Box<dyn Store>) -> Result<(Journal, Catalog, LoadReport)> {
let mut report = LoadReport::default();
let snap = store.read(SNAPSHOT).map_err(io)?;
let log = store.read(LOG).map_err(io)?;
report.created = snap.is_none() && log.is_none();
let (mut catalog, snapshot_seq, snapshot_version) = match snap {
report.kept_files = store.keeps_replaced_formats();
let (mut catalog, snapshot_seq, snapshot_version) = match &snap {
Some(bytes) => {
// the header first: a newer snapshot may not parse as this version's catalog
let h: SnapHeader = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?;
let h: SnapHeader = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?;
if h.format != FORMAT {
return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: not a LightCraft catalog (format {:?})", h.format)));
}
if h.version > VERSION {
return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version)));
}
let s: SnapFile = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?;
let s: SnapFile = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?;
// a seq this high can't come from real use; the next record's seq would wrap
if s.seq > MAX_SEQ {
return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: seq {} is out of range", s.seq)));
@@ -464,6 +535,10 @@ impl Journal {
store,
seq: snapshot_seq,
snapshot_seq,
behind: None,
behind_at: (0, 0),
kept_pending: None,
kept_written: Vec::new(),
log_records: 0,
log_bytes: 0,
policy: SnapshotPolicy::default(),
@@ -545,12 +620,23 @@ impl Journal {
needs_newline = !has_nl;
}
// An older (or snapshot-less) library is brought to this build's format before anything
// is appended: a snapshot in this format makes older builds refuse the library instead
// of misreading ops or dropping fields they don't know.
let older = (!report.created && snapshot_version != Some(VERSION)).then(|| snapshot_version.unwrap_or(0));
if let Some(at) = damaged_at {
let name = format!("{LOG}.damaged-{}", j.seq);
j.store.write_atomic(&name, &log).map_err(io)?;
log::warn!("catalog log damaged at byte {at}; kept as {name}; state recovered up to op {}", j.seq);
report.damaged = Some(name);
j.snapshot(&catalog)?;
match older {
// (its log goes either way: the snapshot it was is kept like any other upgrade's)
Some(from) => {
report.kept = j.upgrade(&catalog, from, snap.as_deref(), &[], Upgrade::Repair)?.unwrap_or_default();
report.upgraded_from = Some(from);
}
None => j.snapshot(&catalog)?,
}
} else {
if good_end < log.len() {
report.torn_bytes = (log.len() - good_end) as u64;
@@ -564,31 +650,210 @@ impl Journal {
j.log_bytes = good_end as u64;
}
}
// Bring an older (or new, or snapshot-less) library to this version's format before
// anything is appended: a snapshot in this format makes older builds refuse the library
// instead of misreading ops or dropping fields they don't know.
if report.created {
// tiny: written directly, not counted as a compaction
let empty = format!("{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":0,\"catalog\":{}}}\n", catalog.to_snapshot());
if let Err(e) = j.store.write_atomic(SNAPSHOT, empty.as_bytes()) {
log::warn!("catalog: can't write the new library's snapshot: {e}");
}
} else if report.damaged.is_none() && snapshot_version != Some(VERSION) {
report.upgraded_from = Some(snapshot_version.unwrap_or(0));
match j.snapshot(&catalog) {
Ok(()) => {
if let Some(v) = report.upgraded_from {
log::info!("catalog: upgraded from format v{v} to v{VERSION}");
}
}
// nothing lost: the old files are intact and still load; retried on next open
Err(e) => log::warn!("catalog: can't write the format v{VERSION} snapshot: {e}"),
} else if let (Some(from), None) = (older, &report.damaged) {
// The library may go on as it is when it can't be upgraded now (the next open tries
// again). Appends are not refused meanwhile: refusing them would leave a library
// whose files can't be copied (little room left) unable to save anything. What is
// appended is this build's ops; the files kept when a later snapshot upgrades it are
// the library as it is here (`behind_at`), which an older build reads.
if let Some(kept) = j.upgrade(&catalog, from, snap.as_deref(), &log, Upgrade::May)? {
report.upgraded_from = Some(from);
report.kept = kept;
} else {
j.behind = Some(from);
j.behind_at = (j.seq, j.log_bytes);
}
}
catalog.revision = 0;
Ok((j, catalog, report))
}
/// Bring a library in format `from` to this build's: keep the files it was (`snap` and `log`,
/// see [`Journal::keep_replaced`]), then write the snapshot. `Some`: upgraded, with the names
/// of the files kept. `None` (only with [`Upgrade::May`]): not upgraded, and as it was, with
/// nothing kept. Otherwise that is an error: the library can't be used as it is.
///
/// The kept files stay unless the library on disk is known to be in its old format still:
/// also when the snapshot was committed and something after it failed (emptying the log),
/// and when what is on disk can't be read to say.
fn upgrade(&mut self, catalog: &Catalog, from: u32, snap: Option<&[u8]>, log: &[u8], how: Upgrade) -> Result<Option<Vec<String>>> {
let refused = |what: &str, e: String| CatalogError::Io(format!("the library is in an older format (v{from}) and {what}: {e}"));
let kept = match self.keep_replaced(from, snap, log) {
Ok(kept) => kept,
Err(e) if how == Upgrade::May => {
// not upgraded without its way back: it opens as it is; retried on next open
log::warn!("catalog: can't keep the format v{from} files, so the library is not upgraded: {e}");
return Ok(None);
}
Err(e) => return Err(refused("its files can't be kept before it is upgraded", e.to_string())),
};
if let Err(e) = self.snapshot(catalog) {
match self.on_disk_version() {
// Committed all the same (the log could not be emptied): the library is upgraded,
// and its way back stays. Its log's records are in the snapshot and are passed
// over when it is read. Not so a damaged log, which would be appended to after
// its damage: the next open has to deal with it first.
Some(Some(VERSION)) if how != Upgrade::Repair => log::warn!("catalog: upgraded to format v{VERSION}, but: {e}"),
Some(Some(VERSION)) => return Err(refused("was upgraded, but its damaged log is still in place", e.to_string())),
// what is on disk can't be read to say: the way back stays
None => return Err(refused("it can't be told whether its upgrade was written", e.to_string())),
// Nothing lost: the old files are intact and still load. No copy of them from this
// attempt stays: there is nothing to go back from.
Some(_) => {
self.forget_kept(&kept.created);
if how != Upgrade::May {
return Err(refused("can't be upgraded", e.to_string()));
}
log::warn!("catalog: can't write the format v{VERSION} snapshot: {e}");
return Ok(None);
}
}
}
log::info!("catalog: upgraded from format v{from} to v{VERSION}; the files it was are kept as {:?}", kept.names);
Ok(Some(kept.names))
}
/// The format of the snapshot in the store: `Some(None)` where there is none, `None` where
/// it can't be read to say.
fn on_disk_version(&mut self) -> Option<Option<u32>> {
match self.store.read(SNAPSHOT) {
Ok(None) => Some(None),
Ok(Some(bytes)) => serde_json::from_slice::<SnapHeader>(&bytes).ok().map(|h| Some(h.version)),
Err(_) => None,
}
}
/// Keep the files of a library in format `from` before an upgrade replaces them: `snap` and
/// `log` as they were read, under names that say their format and the last change they hold.
/// Returns the names (none where the store keeps none). All or nothing: on an error, what
/// this call wrote is removed again.
///
/// A file that is in the way is never replaced or removed: a library restored from an older
/// backup can reach the same format and change as a set kept before, with other bytes. The
/// names then end `-2`, `-3`, … (for both files alike), the first that holds nothing, or
/// these very bytes (that file is reused, and is not this call's to remove).
fn keep_replaced(&mut self, from: u32, snap: Option<&[u8]>, log: &[u8]) -> std::io::Result<Kept> {
let mut kept = Kept::default();
if !self.store.keeps_replaced_formats() {
return Ok(kept);
}
let seq = self.seq;
let files: Vec<(&str, &[u8])> =
[(SNAPSHOT, snap), (LOG, (!log.is_empty()).then_some(log))].into_iter().filter_map(|(name, bytes)| Some((name, bytes?))).collect();
// (nothing is written until every name of the set is known to be free or ours)
let mut plan: Vec<(String, &[u8], bool)> = Vec::new();
'sets: for copy in 1..=MAX_KEPT_COPIES {
plan.clear();
for &(name, bytes) in &files {
let name = if copy == 1 { format!("{name}.v{from}-{seq}") } else { format!("{name}.v{from}-{seq}-{copy}") };
match self.store.read(&name)? {
None => plan.push((name, bytes, true)),
Some(there) if there == bytes => plan.push((name, bytes, false)),
Some(_) => continue 'sets,
}
}
break;
}
if plan.len() != files.len() {
return Err(std::io::Error::other(format!("{MAX_KEPT_COPIES} sets of files kept as format v{from} at change {seq} are in the way")));
}
for (name, bytes, write) in plan {
if write {
if let Err(e) = self.store.write_atomic(&name, bytes) {
// (a write that says it failed may have landed all the same, a network share that
// dropped its answer: the name was free, so what is there now is this call's)
kept.created.push(name);
self.forget_kept(&kept.created);
return Err(e);
}
kept.created.push(name.clone());
}
kept.names.push(name);
}
Ok(kept)
}
/// Remove kept files that keep nothing (the upgrade they were for did not happen): only
/// those a call of [`Journal::keep_replaced`] wrote, never one that was there before.
fn forget_kept(&mut self, created: &[String]) {
for name in created {
if let Err(e) = self.store.remove(name) {
log::warn!("catalog: can't remove {name}: {e}");
}
}
}
/// A library that was left in an older format at open (see `behind`) keeps its files, as
/// they were then, before a snapshot upgrades it: the snapshot as it is (nothing writes it
/// until the upgrade) and the log up to its length at open (what was appended since is this
/// build's, which an older build may refuse). The names are those the open would have kept
/// them under (a name taken since ends `-2`, … as there), so files kept for an upgrade that
/// did not land are not left behind under other names. Kept once: when a snapshot failed and is tried again, they stay as they are
/// (the failed one may have landed all the same, and the snapshot is then no longer what
/// could be kept). A snapshot that is already in this build's format (that landed after its
/// files were kept, or before them, reporting a failure) is the upgrade done, with nothing
/// to keep. An error means they could not be kept (or read): the snapshot is not written, so
/// the library stays as it was, with its way back.
fn keep_before_upgrade(&mut self) -> Result<()> {
let Some(from) = self.behind else { return Ok(()) };
if self.kept_pending.is_some() {
return Ok(());
}
let snap = self.store.read(SNAPSHOT).map_err(io)?;
if let Some(bytes) = snap.as_deref() {
match serde_json::from_slice::<SnapHeader>(bytes).ok().map(|h| h.version) {
Some(v) if v == from => {}
// the upgrade is written already: the snapshot after it is a plain one
Some(VERSION) => {
self.upgraded_later();
return Ok(());
}
_ => return Err(CatalogError::Io(format!("the snapshot is no longer in format v{from}, and can't be kept as it was"))),
}
}
let mut log = self.store.read(LOG).map_err(io)?.unwrap_or_default();
let (seq, log_len) = self.behind_at;
log.truncate(usize::try_from(log_len).unwrap_or(usize::MAX));
let at = std::mem::replace(&mut self.seq, seq);
let kept = self.keep_replaced(from, snap.as_deref(), &log);
self.seq = at;
let kept = kept.map_err(io)?;
log::info!("catalog: the files of format v{from} are kept as {:?} before the upgrade", kept.names);
self.kept_pending = Some(kept.names);
Ok(())
}
/// The snapshot that upgrades a library left behind is durable: the files kept for it are
/// now the library's way back, for [`Journal::take_kept`] to tell.
fn upgraded_later(&mut self) {
self.behind = None;
if let Some(kept) = self.kept_pending.take() {
self.kept_written.extend(kept);
}
}
/// A snapshot reported a failure: one that landed all the same (a share that dropped its answer) and is in this
/// build's format did the upgrade, so the files kept for it are the way back now, to be told without waiting for
/// a later snapshot that succeeds.
fn upgraded_despite_error(&mut self) {
if self.behind.is_some() && self.on_disk_version() == Some(Some(VERSION)) {
self.upgraded_later();
}
}
/// The files a snapshot kept when it upgraded a library that was left in an older format at
/// open (see `behind`), once, after it was written: [`LoadReport::kept`] has only what the
/// open kept. Empty when there are none.
pub fn take_kept(&mut self) -> Vec<String> {
std::mem::take(&mut self.kept_written)
}
/// Append ops (already applied to the live catalog) durably, in order.
pub fn append(&mut self, ops: &[Op]) -> Result<()> {
if ops.is_empty() {
@@ -651,10 +916,17 @@ impl Journal {
}
let t0 = web_time::Instant::now();
let seq = self.seq.checked_add(unlogged).ok_or_else(|| CatalogError::Corrupt(format!("{SNAPSHOT}: op counter overflow")))?;
if let Err(e) = self.keep_before_upgrade() {
// not upgraded without its way back; try again later like any failed snapshot
self.stats.failed_snapshots += 1;
self.retry_at_records = self.log_records + self.policy.max_records;
return Err(e);
}
let mut timing = match write_snapshot(self.store.as_mut(), seq, catalog) {
Ok(t) => t,
Err(e) => {
// nothing lost (the log is whole); don't retry on every append
self.upgraded_despite_error();
self.stats.failed_snapshots += 1;
self.retry_at_records = self.log_records + self.policy.max_records;
return Err(io(e));
@@ -663,6 +935,7 @@ impl Journal {
// the snapshot is durable: it holds every op up to `seq`
self.seq = seq;
self.snapshot_seq = seq;
self.upgraded_later();
let t2 = web_time::Instant::now();
// A crash here leaves old records in the log; they are skipped by seq on load.
self.store.write_atomic(LOG, b"").map_err(io)?;
@@ -687,6 +960,11 @@ impl Journal {
return Ok(());
}
let t0 = web_time::Instant::now();
if let Err(e) = self.keep_before_upgrade() {
self.stats.failed_snapshots += 1;
self.retry_at_records = self.log_records + self.policy.max_records;
return Err(e);
}
let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) };
let copy = catalog.clone();
let seq = self.seq;
@@ -740,6 +1018,7 @@ impl Journal {
Ok(t) => t,
Err(e) => {
// the log still holds every record: nothing lost, retry later
self.upgraded_despite_error();
self.stats.failed_snapshots += 1;
self.retry_at_records = self.log_records + self.policy.max_records;
log::error!("catalog: background snapshot failed: {e}");
@@ -750,6 +1029,7 @@ impl Journal {
// Keep exactly the ones appended since (a crash before this rewrite skips the stale ones).
let t1 = web_time::Instant::now();
self.snapshot_seq = p.seq;
self.upgraded_later();
if let Err(e) = self.store.write_atomic(LOG, &p.tail) {
// the log stays whole (stale records are skipped on load); compact again later
self.retry_at_records = self.log_records + self.policy.max_records;
+41 -9
View File
@@ -31,6 +31,7 @@ pub mod opened_folder;
pub mod query;
pub mod rules;
pub mod safe_file;
pub mod shared;
pub mod stacks;
pub mod store;
pub mod tally;
@@ -388,23 +389,46 @@ impl std::fmt::Debug for PlansMemo {
}
}
/// What [`resolve_grids`] has made of each value with references so far: the value as read (held
/// here so its address stays its own), what it resolved to and how many dangling references it
/// held. Holders that shared a value before resolving share the result, whatever else is between
/// them (a photo's settings and its last history step, with the earlier steps in between).
type ResolvedGrids = std::collections::HashMap<*const DevelopSettings, (Arc<DevelopSettings>, Arc<DevelopSettings>, usize)>;
/// Resolves the shared-grid references of one settings holder (see [`Photo::settings_holders`])
/// against a snapshot's grid table: each referenced mask takes its
/// grid's data and the reference is cleared. A reference past the table (a damaged snapshot)
/// leaves the mask empty — it renders nothing, like any other damaged grid. Data present on the
/// mask itself wins over a stray reference. Returns the dangling count added to `dangling`.
fn resolve_grids(settings: &mut Arc<DevelopSettings>, grids: &[String], dangling: usize) -> usize {
let mut dangling = dangling;
///
/// Settings that refer to no grid (nearly all of them) are left alone, so a value shared by many
/// holders stays shared: [`Arc::make_mut`] would copy it for each. A value with references is
/// resolved once (`done`): every holder that held it takes the same result, which is handed to
/// [`shared::settings`], so holders that are equal once resolved share one value too.
fn resolve_grids(settings: &mut Arc<DevelopSettings>, grids: &[String], dangling: usize, done: &mut ResolvedGrids) -> usize {
let mut referenced = false;
settings.visit_seg_masks(&mut |m| referenced |= m.grid.is_some());
if !referenced {
return dangling;
}
if let Some((_, resolved, dangled)) = done.get(&Arc::as_ptr(settings)) {
*settings = resolved.clone();
return dangling + dangled;
}
let original = settings.clone();
let mut dangled = 0usize;
Arc::make_mut(settings).visit_seg_masks_mut(&mut |m| {
if let Some(i) = m.grid.take() {
match (m.data.is_empty(), grids.get(i as usize)) {
(true, Some(data)) => m.data = data.clone(),
(true, None) => dangling += 1,
(true, None) => dangled += 1,
(false, _) => {}
}
}
});
dangling
*settings = shared::settings(settings.clone());
done.insert(Arc::as_ptr(&original), (original, settings.clone(), dangled));
dangling + dangled
}
/// A short memory of what the latest ops changed, so that what is derived from the catalog (the grid's list) can
@@ -934,6 +958,7 @@ impl Catalog {
photo.trim_history();
let id = photo.id;
self.next_photo = self.next_photo.max(id.0.saturating_add(1));
shared::photo(&mut photo);
self.index.file_changed(id, None, file_path(&photo.source));
self.photos.insert(id, Arc::new(*photo));
self.index.text_changed(id, self.photos.get(&id).map(|p| &**p));
@@ -964,7 +989,7 @@ impl Catalog {
}
Op::SetDevelop { id, settings, label, edited } => {
let p = self.photo_mut(id)?;
let old = std::mem::replace(&mut p.develop, settings);
let old = std::mem::replace(&mut p.develop, shared::settings(settings));
let old_edit = std::mem::replace(&mut p.edited, edited);
Op::SetDevelop { id, settings: old, label, edited: old_edit }
}
@@ -982,12 +1007,15 @@ impl Catalog {
let p = self.photo_mut(id)?;
Op::SetLocal { id, local: std::mem::replace(&mut p.local, local) }
}
Op::SetVersions { id, versions } => {
Op::SetVersions { id, mut versions } => {
let p = self.photo_mut(id)?;
shared::Anchor::new(p.develop.clone()).versions(&mut versions);
Op::SetVersions { id, versions: std::mem::replace(&mut p.versions, versions) }
}
Op::SetHistory { id, history } => {
Op::SetHistory { id, mut history } => {
let p = self.photo_mut(id)?;
let own = shared::Anchor::new(p.develop.clone());
history.iter_mut().for_each(|s| own.step(s));
let old = std::mem::replace(&mut p.history, history);
let old_cursor = p.history_cursor;
p.trim_history();
@@ -997,8 +1025,9 @@ impl Catalog {
Op::Batch { ops: vec![Op::SetHistory { id, history: old }, Op::SetHistoryCursor { id, cursor: old_cursor }] }
}
}
Op::PushHistory { id, step } => {
Op::PushHistory { id, mut step } => {
let p = self.photo_mut(id)?;
shared::Anchor::new(p.develop.clone()).step(&mut step);
let old = p.history.clone();
let old_cursor = p.history_cursor.take();
// a new edit made from an earlier step drops the steps after it
@@ -1335,10 +1364,11 @@ impl Catalog {
// an empty table, which is always dangling, so the table being empty does not skip it.
let grids = std::mem::take(&mut self.grids);
let mut dangling = 0usize;
let mut done = ResolvedGrids::new();
for p in self.photos.values_mut() {
let photo = Arc::make_mut(p);
for settings in photo.settings_holders_mut() {
dangling = resolve_grids(settings, &grids, dangling);
dangling = resolve_grids(settings, &grids, dangling, &mut done);
}
}
if dangling > 0 {
@@ -1674,6 +1704,8 @@ mod tests_scale;
#[cfg(test)]
mod tests_search_text;
#[cfg(test)]
mod tests_shared;
#[cfg(test)]
mod tests_tally;
#[cfg(test)]
mod tests_torn_append;
+5 -2
View File
@@ -320,6 +320,7 @@ fn maker_word(w: &str) -> String {
pub struct Version {
pub name: String,
pub created: String,
#[serde(deserialize_with = "crate::shared::deserialize")]
pub settings: Arc<DevelopSettings>,
#[serde(default)]
pub auto: bool,
@@ -328,6 +329,7 @@ pub struct Version {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HistoryStep {
pub label: String,
#[serde(deserialize_with = "crate::shared::deserialize")]
pub settings: Arc<DevelopSettings>,
}
@@ -355,6 +357,7 @@ pub struct Photo {
pub flag: Flag,
#[serde(default)]
pub label: Option<ColorLabel>,
#[serde(deserialize_with = "crate::shared::deserialize_current")]
pub develop: Arc<DevelopSettings>,
#[serde(default)]
pub edited: Option<String>,
@@ -397,7 +400,7 @@ pub struct Photo {
/// The settings import gave the photo when a user default (a raw/JPEG default preset, see
/// the engine's import defaults) changed them from [`Photo::camera_defaults`]. They count as
/// unedited, and Reset returns to them.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::shared::deserialize_optional")]
pub import_look: Option<Arc<DevelopSettings>>,
/// Assisted culling scores (`None` until analysed).
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -513,7 +516,7 @@ impl Photo {
rating: 0,
flag: Flag::None,
label: None,
develop: Arc::new(DevelopSettings::default()),
develop: crate::shared::default_settings(),
edited: None,
versions: Vec::new(),
history: Vec::new(),
+365
View File
@@ -0,0 +1,365 @@
//! One develop settings value for all the photos whose settings are equal.
//!
//! A photo holds its settings behind an `Arc`, and so do its history steps, versions and import
//! look. Most photos of a library were never edited: without sharing, each holds a copy of the
//! same defaults (over a third of the memory an unedited JPEG's record takes), and so does every
//! raw with the same import look. Here every
//! settings value that enters a catalog, read from a saved library or given by a change, is
//! replaced by the one already held when an equal one is.
//! Settings whose masks refer to a snapshot's grid table are shared again once the references are
//! resolved (`resolve_grids` in `lib.rs`); settings without a reference are left as they were read.
//!
//! Sharing never lets one photo's edit reach another: settings behind an `Arc` are not changed
//! in place (the catalog replaces them; `Arc::make_mut` copies a value that is shared).
//!
//! **Equal means the same down to the JSON.** `==` takes -0.0 for 0.0, which the saved form, a
//! photo's fingerprint and the preview-cache key tell apart. Two values are shared only when
//! they are `==` and neither holds a negative zero. Settings holding a negative zero are left
//! alone: never shared, never what others share.
//!
//! What is held to compare with: the defaults, and on each thread the last few values seen (a
//! camera's import defaults, a photo's own history). The thread's list keeps nothing alive: a
//! value no photo holds any more is gone from it too.
use std::cell::{OnceCell, RefCell};
use std::sync::{Arc, OnceLock, Weak};
use lightcraft_develop::DevelopSettings;
use serde::de::{Deserialize, Deserializer};
use crate::{HistoryStep, Photo, Version};
/// How many values a thread remembers besides the defaults and the current photo's.
const RECENT: usize = 4;
/// Whether a value holds a -0.0 anywhere (a float the saved JSON writes as `-0.0`): found by
/// walking it as `Serialize` does, so no text is built (writing every float out costs as much as
/// reading the library did).
fn has_negative_zero<T: serde::Serialize + ?Sized>(value: &T) -> bool {
value.serialize(Walk).is_err()
}
/// Walks a value; stops with an error at the first -0.0.
struct Walk;
#[derive(Debug)]
struct Found;
impl std::fmt::Display for Found {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("negative zero")
}
}
impl std::error::Error for Found {}
impl serde::ser::Error for Found {
fn custom<T: std::fmt::Display>(_: T) -> Self {
Found
}
}
type Walked = Result<(), Found>;
macro_rules! nothing {
($($method:ident($ty:ty)),* $(,)?) => {
$(fn $method(self, _: $ty) -> Walked { Ok(()) })*
};
}
impl serde::Serializer for Walk {
type Ok = ();
type Error = Found;
type SerializeSeq = Walk;
type SerializeTuple = Walk;
type SerializeTupleStruct = Walk;
type SerializeTupleVariant = Walk;
type SerializeMap = Walk;
type SerializeStruct = Walk;
type SerializeStructVariant = Walk;
nothing!(serialize_bool(bool), serialize_i8(i8), serialize_i16(i16), serialize_i32(i32), serialize_i64(i64), serialize_i128(i128));
nothing!(serialize_u8(u8), serialize_u16(u16), serialize_u32(u32), serialize_u64(u64), serialize_u128(u128));
nothing!(serialize_char(char), serialize_str(&str), serialize_bytes(&[u8]), serialize_unit_struct(&'static str));
fn serialize_f32(self, v: f32) -> Walked {
if v == 0.0 && v.is_sign_negative() { Err(Found) } else { Ok(()) }
}
fn serialize_f64(self, v: f64) -> Walked {
if v == 0.0 && v.is_sign_negative() { Err(Found) } else { Ok(()) }
}
fn serialize_none(self) -> Walked {
Ok(())
}
fn serialize_some<T: serde::Serialize + ?Sized>(self, v: &T) -> Walked {
v.serialize(Walk)
}
fn serialize_unit(self) -> Walked {
Ok(())
}
fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Walked {
Ok(())
}
fn serialize_newtype_struct<T: serde::Serialize + ?Sized>(self, _: &'static str, v: &T) -> Walked {
v.serialize(Walk)
}
fn serialize_newtype_variant<T: serde::Serialize + ?Sized>(self, _: &'static str, _: u32, _: &'static str, v: &T) -> Walked {
v.serialize(Walk)
}
fn serialize_seq(self, _: Option<usize>) -> Result<Walk, Found> {
Ok(Walk)
}
fn serialize_tuple(self, _: usize) -> Result<Walk, Found> {
Ok(Walk)
}
fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result<Walk, Found> {
Ok(Walk)
}
fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result<Walk, Found> {
Ok(Walk)
}
fn serialize_map(self, _: Option<usize>) -> Result<Walk, Found> {
Ok(Walk)
}
fn serialize_struct(self, _: &'static str, _: usize) -> Result<Walk, Found> {
Ok(Walk)
}
fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result<Walk, Found> {
Ok(Walk)
}
}
macro_rules! walk_elements {
($($trait:ident::$method:ident),* $(,)?) => {
$(impl serde::ser::$trait for Walk {
type Ok = ();
type Error = Found;
fn $method<T: serde::Serialize + ?Sized>(&mut self, v: &T) -> Walked {
v.serialize(Walk)
}
fn end(self) -> Walked {
Ok(())
}
})*
};
}
walk_elements!(
SerializeSeq::serialize_element,
SerializeTuple::serialize_element,
SerializeTupleStruct::serialize_field,
SerializeTupleVariant::serialize_field
);
impl serde::ser::SerializeMap for Walk {
type Ok = ();
type Error = Found;
fn serialize_key<T: serde::Serialize + ?Sized>(&mut self, k: &T) -> Walked {
k.serialize(Walk)
}
fn serialize_value<T: serde::Serialize + ?Sized>(&mut self, v: &T) -> Walked {
v.serialize(Walk)
}
fn end(self) -> Walked {
Ok(())
}
}
impl serde::ser::SerializeStruct for Walk {
type Ok = ();
type Error = Found;
fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, _: &'static str, v: &T) -> Walked {
v.serialize(Walk)
}
fn end(self) -> Walked {
Ok(())
}
}
impl serde::ser::SerializeStructVariant for Walk {
type Ok = ();
type Error = Found;
fn serialize_field<T: serde::Serialize + ?Sized>(&mut self, _: &'static str, v: &T) -> Walked {
v.serialize(Walk)
}
fn end(self) -> Walked {
Ok(())
}
}
fn held_default() -> &'static Arc<DevelopSettings> {
static DEFAULT: OnceLock<Arc<DevelopSettings>> = OnceLock::new();
DEFAULT.get_or_init(|| Arc::new(DevelopSettings::default()))
}
/// The default settings, held once.
pub fn default_settings() -> Arc<DevelopSettings> {
held_default().clone()
}
/// What a thread has seen: pointers that keep nothing alive (a value the catalog let go of is
/// gone from here too). None of the values holds a negative zero.
#[derive(Default)]
struct Seen {
/// The settings of the photo being read or added: its history (up to 200 steps, each seen
/// after it) usually ends with them.
current: Option<Weak<DevelopSettings>>,
/// The last few values, the latest first.
recent: Vec<Weak<DevelopSettings>>,
}
thread_local! {
static SEEN: RefCell<Seen> = RefCell::new(Seen::default());
}
/// How many values this thread remembers now (tests).
#[cfg(test)]
pub(crate) fn remembered() -> usize {
SEEN.with(|seen| seen.borrow().recent.len())
}
/// `settings`, or the value already held that is the same.
pub fn settings(settings: Arc<DevelopSettings>) -> Arc<DevelopSettings> {
share(settings, false)
}
/// [`settings`] for a photo's own settings (`current`): what its history is compared with first.
fn share(settings: Arc<DevelopSettings>, current: bool) -> Arc<DevelopSettings> {
// (looked for at most once, and only when an equal value turned up or this one is kept)
let exact = OnceCell::new();
let exact = || *exact.get_or_init(|| !has_negative_zero(settings.as_ref()));
let same = |held: &Arc<DevelopSettings>| Arc::ptr_eq(held, &settings) || (**held == *settings && exact());
let default = held_default();
if same(default) {
// (the held default is compared with anyway)
if current {
let _ = SEEN.try_with(|seen| seen.try_borrow_mut().map(|mut s| s.current = None));
}
return default.clone();
}
let found = SEEN.try_with(|seen| {
let mut seen = seen.try_borrow_mut().ok()?;
let found = seen.current.as_ref().and_then(Weak::upgrade).filter(|s| same(s)).or_else(|| {
// (values that are gone drop out as they are met)
let mut found = None;
seen.recent.retain(|w| match w.upgrade() {
Some(s) if found.is_none() && same(&s) => {
found = Some(s);
false
}
Some(_) => true,
None => false,
});
if let Some(f) = &found {
seen.recent.insert(0, Arc::downgrade(f));
}
found
});
if found.is_none() && exact() {
seen.recent.truncate(RECENT - 1);
seen.recent.insert(0, Arc::downgrade(&settings));
}
if current {
seen.current = match &found {
Some(f) => Some(Arc::downgrade(f)),
None => exact().then(|| Arc::downgrade(&settings)),
};
}
found
});
// (a thread shutting down: as it came)
found.ok().flatten().unwrap_or(settings)
}
/// Share the settings of a history step.
pub(crate) fn step(step: &mut HistoryStep) {
step.settings = settings(step.settings.clone());
}
/// What a change's settings are compared with first: the photo's own settings.
pub(crate) struct Anchor {
own: Arc<DevelopSettings>,
/// Whether `own` holds no negative zero (looked for once, and only when an equal value turned up).
exact: OnceCell<bool>,
}
impl Anchor {
pub(crate) fn new(own: Arc<DevelopSettings>) -> Self {
Self { own, exact: OnceCell::new() }
}
/// `s`, or the photo's own settings when equal (and neither holds a negative zero), or else what [`settings`] says.
fn settings(&self, s: Arc<DevelopSettings>) -> Arc<DevelopSettings> {
if Arc::ptr_eq(&self.own, &s) {
return s;
}
if *self.own == *s && *self.exact.get_or_init(|| !has_negative_zero(self.own.as_ref())) && !has_negative_zero(s.as_ref()) {
return self.own.clone();
}
settings(s)
}
pub(crate) fn step(&self, step: &mut HistoryStep) {
step.settings = self.settings(step.settings.clone());
}
pub(crate) fn versions(&self, versions: &mut [Version]) {
for v in versions {
v.settings = self.settings(v.settings.clone());
}
}
}
/// Share the settings of versions.
pub(crate) fn versions(versions: &mut [Version]) {
for v in versions {
v.settings = settings(v.settings.clone());
}
}
/// Share every settings value a photo holds.
pub(crate) fn photo(p: &mut Photo) {
p.develop = share(p.develop.clone(), true);
p.history.iter_mut().for_each(step);
versions(&mut p.versions);
p.import_look = p.import_look.take().map(settings);
}
/// Settings read from a saved library (`deserialize_with`): shared.
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Arc<DevelopSettings>, D::Error> {
DevelopSettings::deserialize(d).map(|s| share(Arc::new(s), false))
}
/// [`deserialize`] for a photo's own settings: what its history, read after them, is compared
/// with first.
pub(crate) fn deserialize_current<'de, D: Deserializer<'de>>(d: D) -> Result<Arc<DevelopSettings>, D::Error> {
DevelopSettings::deserialize(d).map(|s| share(Arc::new(s), true))
}
/// [`deserialize`] for settings a photo may not have (its import look).
pub(crate) fn deserialize_optional<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Arc<DevelopSettings>>, D::Error> {
Ok(Option::<DevelopSettings>::deserialize(d)?.map(|s| share(Arc::new(s), false)))
}
+113 -5
View File
@@ -40,6 +40,19 @@ pub trait Store: Send {
/// Cut a file to `len` bytes (drop a torn tail before appending again). A missing file is
/// left missing.
fn truncate(&mut self, name: &str, len: u64) -> io::Result<()>;
/// Remove a file (a missing one is not an error). The default can't: such a store keeps what
/// it was asked to remove.
fn remove(&mut self, name: &str) -> io::Result<()> {
let _ = name;
Err(io::Error::new(io::ErrorKind::Unsupported, "this store can't remove files"))
}
/// Whether the files an upgrade to a newer catalog format replaces are kept beside the
/// library (see [`crate::journal`] → *Format versions*): the way back to the build that wrote
/// them. `false` where there is no such build to go back to (the browser always runs the
/// newest one) and room is short.
fn keeps_replaced_formats(&self) -> bool {
true
}
/// Human-readable location (diagnostics).
fn describe(&self) -> String;
/// Another handle on the same files that a worker thread can write `catalog.snap` through
@@ -241,10 +254,20 @@ impl Store for FsStore {
self.folder.check()?;
let tmp = self.path(&format!("{name}.tmp"));
let mut f = create_staging(&tmp)?;
f.write_all(data)?;
f.sync_all()?;
check_staging(&self.folder, &tmp, &f)?;
std::fs::rename(&tmp, self.path(name))?;
let staged = (|| {
f.write_all(data)?;
f.sync_all()?;
check_staging(&self.folder, &tmp, &f)?;
std::fs::rename(&tmp, self.path(name))
})();
if let Err(e) = staged {
// no staging file is left beside the library (a kept copy is all or nothing), unless it is no longer ours: a
// folder or a name that came to belong to another save keeps its file (see `check_staging`)
if check_staging(&self.folder, &tmp, &f).is_ok() {
let _ = std::fs::remove_file(&tmp);
}
return Err(e);
}
self.sync_dir();
self.reset_sync_log(name, data.len() as u64);
Ok(())
@@ -283,7 +306,13 @@ impl Store for FsStore {
}
};
check_staging(&self.folder, &tmp, &file)?;
std::fs::rename(&tmp, self.path(name))?;
if let Err(e) = std::fs::rename(&tmp, self.path(name)) {
// (as in `write_atomic`: the staging file goes unless it came to belong to another save)
if check_staging(&self.folder, &tmp, &file).is_ok() {
let _ = std::fs::remove_file(&tmp);
}
return Err(e);
}
self.sync_dir();
self.reset_sync_log(name, n);
Ok(n)
@@ -384,6 +413,30 @@ impl Store for FsStore {
Ok(())
}
fn remove(&mut self, name: &str) -> io::Result<()> {
// What was handed to the log's thread is written first (a failure is the caller's: nothing is dropped). The thread
// goes only once the file is gone (it would read a missing file as another log), and the next append starts one.
#[cfg(not(target_arch = "wasm32"))]
let thread = self.log_for(name).is_some();
#[cfg(not(target_arch = "wasm32"))]
if thread {
self.flush_log()?;
}
self.folder.check()?;
match std::fs::remove_file(self.path(name)) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
#[cfg(not(target_arch = "wasm32"))]
if thread {
self.log = None;
}
// (a removed log is a log of no bytes: what the next append is checked against)
self.reset_sync_log(name, 0);
Ok(())
}
fn describe(&self) -> String {
self.dir.display().to_string()
}
@@ -458,6 +511,10 @@ impl Store for MemStore {
}
Ok(())
}
fn remove(&mut self, name: &str) -> io::Result<()> {
self.files.lock().unwrap_or_else(|e| e.into_inner()).remove(name);
Ok(())
}
fn describe(&self) -> String {
"memory".into()
}
@@ -515,3 +572,54 @@ mod tests_staging {
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod tests_failed_write {
use super::*;
fn dir_with_a_directory_at(tag: &str, name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("lc-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join(name)).unwrap();
dir
}
/// A write that can't land (here the rename fails, the name being a directory) leaves no staging file behind: the
/// files a library keeps before an upgrade are "all or nothing", and a `.tmp` beside them is a copy lying about.
#[test]
fn write_atomic_that_fails_leaves_no_staging_file() {
let dir = dir_with_a_directory_at("write-atomic-fails", "catalog.snap.v6-8");
let mut store = FsStore::open(&dir).unwrap();
assert!(store.write_atomic("catalog.snap.v6-8", b"{}").is_err());
assert!(!dir.join("catalog.snap.v6-8.tmp").exists(), "a staging file was left behind");
let _ = std::fs::remove_dir_all(&dir);
}
/// The streamed write cleans up the same way when the rename fails (it already did when the content can't be written).
#[test]
fn write_atomic_with_that_fails_to_rename_leaves_no_staging_file() {
let dir = dir_with_a_directory_at("write-atomic-with-fails", "catalog.log");
let mut store = FsStore::open(&dir).unwrap();
assert!(store.write_atomic_with("catalog.log", &mut |w| w.write_all(b"[1]")).is_err());
assert!(!dir.join("catalog.log.tmp").exists(), "a staging file was left behind");
let _ = std::fs::remove_dir_all(&dir);
}
/// A log that is removed while its thread runs ends the thread: the next append starts one for the new, empty file, and is
/// written (a thread that outlived its file would find another file than the one it wrote and hold the record back).
#[test]
fn removing_the_log_ends_its_writer() {
let dir = std::env::temp_dir().join(format!("lc-remove-log-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut store = FsStore::open(&dir).unwrap();
store.append("catalog.log", b"abc\n").unwrap();
store.flush().unwrap();
store.remove("catalog.log").unwrap();
assert!(!dir.join("catalog.log").exists());
store.append("catalog.log", b"de\n").unwrap();
store.flush().unwrap();
assert!(store.unwritten().is_none(), "nothing is held back");
assert_eq!(std::fs::read(dir.join("catalog.log")).unwrap(), b"de\n");
let _ = std::fs::remove_dir_all(&dir);
}
}
+586
View File
@@ -271,3 +271,589 @@ fn op_variants_are_versioned() {
let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None });
assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version");
}
// ---- an upgrade keeps what it replaces
/// A store whose writes of some files fail.
struct Refusing {
files: MemStore,
refuse: fn(&str) -> bool,
}
impl Store for Refusing {
fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
self.files.read(name)
}
fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
if (self.refuse)(name) {
return Err(std::io::Error::other("disk full"));
}
self.files.write_atomic(name, data)
}
fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.files.append(name, data)
}
fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> {
self.files.truncate(name, len)
}
fn remove(&mut self, name: &str) -> std::io::Result<()> {
self.files.remove(name)
}
fn describe(&self) -> String {
"refusing".into()
}
}
/// The library `fixtures/v<N>-catalog.*` holds, written by the build of format `N`.
fn fixture(version: u32) -> Option<(&'static str, &'static str)> {
match version {
6 => Some((include_str!("fixtures/v6-catalog.snap.json"), include_str!("fixtures/v6-catalog.log.jsonl"))),
_ => None,
}
}
/// A format 6 library (the fixture) in a store.
fn v6_library() -> (MemStore, Vec<u8>, Vec<u8>) {
let (snap, log) = fixture(6).unwrap();
let m = MemStore::new();
m.set(SNAPSHOT, snap.as_bytes().to_vec());
m.set(LOG, log.as_bytes().to_vec());
(m, snap.as_bytes().to_vec(), log.as_bytes().to_vec())
}
/// Given a library in an older format, when it is opened (which rewrites it in this build's
/// format, and older builds can't read that), then the files it was are kept beside it, byte for
/// byte, under names that say their format and the change they end at; the report names them;
/// and put back under their own names they are the library as it was.
#[test]
fn an_upgrade_keeps_the_files_it_replaces() {
let (m, snap, log) = v6_library();
let (_, upgraded, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!(r.upgraded_from, Some(6));
assert_eq!(r.kept, ["catalog.snap.v6-8", "catalog.log.v6-8"]);
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap.clone()), Some(log.clone())));
assert_eq!(snapshot_version(&m), u64::from(VERSION));
// the way back: the kept files under their own names
let back = MemStore::new();
back.set(SNAPSHOT, m.get("catalog.snap.v6-8").unwrap());
back.set(LOG, m.get("catalog.log.v6-8").unwrap());
assert_eq!(snapshot_version(&back), 6);
let (_, mut as_it_was, _) = Journal::open(Box::new(back)).unwrap();
as_it_was.revision = upgraded.revision;
assert_eq!(as_it_was, upgraded);
}
/// Given a library that is in this build's format already, or a new one, when it is opened,
/// then nothing is kept: there is nothing an older build could have read.
#[test]
fn nothing_is_kept_without_an_upgrade() {
let m = MemStore::new();
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
assert!(r.created && r.kept.is_empty());
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
assert!(r.kept.is_empty() && r.upgraded_from.is_none());
assert_eq!(m.files.lock().unwrap().keys().collect::<Vec<_>>(), [SNAPSHOT]);
}
/// Given a library from before snapshots (only a log), when it is opened, then the log is kept
/// (as format 0: there was no number yet) and no snapshot is made up for it.
#[test]
fn an_upgrade_of_a_log_only_library_keeps_the_log() {
let mut c = Catalog::new();
let op = photo(&mut c);
let log = format!("{}\n", encode_record(1, &op)).into_bytes();
let m = MemStore::new();
m.set(LOG, log.clone());
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!((r.upgraded_from, r.kept.as_slice()), (Some(0), ["catalog.log.v0-1".to_string()].as_slice()));
assert_eq!(m.get("catalog.log.v0-1"), Some(log));
assert_eq!(m.get("catalog.snap.v0-1"), None);
}
/// Given an older library whose files can't be kept (the disk is full), when it is opened, then
/// it is not upgraded without its way back: it opens as it is, with its files as they were and
/// nothing half kept, and is upgraded once there is room.
#[test]
fn a_library_that_cannot_be_kept_is_not_upgraded() {
let (m, snap, log) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") };
let (_, c, r) = Journal::open(Box::new(store)).unwrap();
assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0));
assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log)));
assert_eq!(m.files.lock().unwrap().keys().collect::<Vec<_>>(), [LOG, SNAPSHOT], "nothing half kept");
let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, Some(6), 2));
}
/// Given an older library on disk whose files can't be kept (the staging name of the second is taken by a directory,
/// so the first was written and must be removed again), when it is opened, then it is not upgraded, and no copy or
/// half-written staging file of the files it tried to keep is left lying about in the library's folder.
#[test]
fn a_library_on_disk_that_cannot_be_kept_leaves_nothing_lying_about() {
let dir = std::env::temp_dir().join(format!("lc-keep-fails-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("catalog.log.v6-8.tmp")).unwrap();
let (snap, log) = fixture(6).unwrap();
std::fs::write(dir.join(SNAPSHOT), snap).unwrap();
std::fs::write(dir.join(LOG), log).unwrap();
let (_, c, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0));
let mut names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
assert_eq!(names, [LOG, "catalog.log.v6-8.tmp", SNAPSHOT], "nothing but the library and the name that was taken");
assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), snap.as_bytes());
let _ = std::fs::remove_dir_all(&dir);
}
/// Given an older library whose upgrade can't be written, when it is opened, then it opens as it
/// was, with no copy of it left lying about: there is nothing to go back from.
#[test]
fn a_failed_upgrade_leaves_no_copy() {
let (m, snap, log) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT };
let (_, c, r) = Journal::open(Box::new(store)).unwrap();
assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0));
assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log)));
assert_eq!(m.files.lock().unwrap().keys().collect::<Vec<_>>(), [LOG, SNAPSHOT]);
}
/// Given an older library whose upgrade is written but whose log then can't be emptied, when it
/// is opened, then it is upgraded all the same (the log's changes are in the snapshot, and are
/// passed over when it is read), and the files it was are kept: its way back is not thrown away
/// because something failed after the upgrade.
#[test]
fn an_upgrade_that_is_written_keeps_its_copies_whatever_fails_after() {
let (m, snap, log) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name == LOG };
let (_, c, r) = Journal::open(Box::new(store)).unwrap();
assert_eq!((c.photos().count(), r.upgraded_from), (3, Some(6)));
assert_eq!(r.kept, ["catalog.snap.v6-8", "catalog.log.v6-8"]);
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log.clone())));
assert_eq!(snapshot_version(&m), u64::from(VERSION));
// the log it could not empty is all in the snapshot
assert_eq!(m.get(LOG), Some(log));
let (_, mut again, r) = Journal::open(Box::new(m)).unwrap();
again.revision = c.revision;
assert_eq!((again, r.replayed, r.upgraded_from), (c, 0, None));
}
/// Given an older library whose log is damaged, when it is opened (which saves what could be
/// read in this build's format), then that is an upgrade like any other: the snapshot it was is
/// kept beside the damaged log.
#[test]
fn a_damaged_older_library_keeps_its_snapshot() {
let (m, snap, log) = v6_library();
// a record in the middle that is not what was written, with good ones after it
let mut lines: Vec<String> = String::from_utf8(log).unwrap().lines().map(str::to_string).collect();
lines[1] = lines[1].replacen("\"crc\":", "\"crc\":1", 1);
let damaged = format!("{}\n", lines.join("\n")).into_bytes();
m.set(LOG, damaged.clone());
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
let kept_log = r.damaged.clone().expect("damaged");
assert_eq!((r.upgraded_from, r.kept.as_slice()), (Some(6), ["catalog.snap.v6-4".to_string()].as_slice()), "{r:?}");
assert_eq!((m.get("catalog.snap.v6-4"), m.get(&kept_log)), (Some(snap), Some(damaged)));
assert_eq!(snapshot_version(&m), u64::from(VERSION));
}
/// Given an older library whose log is damaged, when the upgrade is written but the damaged log
/// can't be replaced, then the library is refused (working in it would add changes after the
/// damage, where the next open would not read them), with the snapshot it was kept; and it
/// opens, repaired, once the log can be written.
#[test]
fn a_damaged_older_library_is_not_worked_in_with_its_damaged_log_in_place() {
let (m, snap, log) = v6_library();
let mut lines: Vec<String> = String::from_utf8(log).unwrap().lines().map(str::to_string).collect();
lines[1] = lines[1].replacen("\"crc\":", "\"crc\":1", 1);
m.set(LOG, format!("{}\n", lines.join("\n")).into_bytes());
let store = Refusing { files: m.clone(), refuse: |name| name == LOG };
let e = Journal::open(Box::new(store)).err().expect("refused");
assert!(matches!(&e, CatalogError::Io(why) if why.contains("damaged log")), "{e}");
assert_eq!(m.get("catalog.snap.v6-4"), Some(snap), "its way back stays");
let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!(c.photos().count(), 3);
assert!(r.damaged.is_some() && m.get(LOG).unwrap().is_empty(), "{r:?}");
}
/// Given an older library whose upgrade fails in a way that leaves it unknown whether it was
/// written (the snapshot can't be read afterwards), then the files it was are kept: the way
/// back is given up only when the library is known to be as it was.
#[test]
fn an_upgrade_that_cannot_be_checked_keeps_its_copies() {
/// Fails the write of the snapshot, and every read of it after that.
struct Blind {
files: MemStore,
failed: bool,
}
impl Store for Blind {
fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
if self.failed && name == SNAPSHOT {
return Err(std::io::Error::other("unreadable"));
}
self.files.read(name)
}
fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
if name == SNAPSHOT {
self.failed = true;
return Err(std::io::Error::other("the share went away"));
}
self.files.write_atomic(name, data)
}
fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.files.append(name, data)
}
fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> {
self.files.truncate(name, len)
}
fn remove(&mut self, name: &str) -> std::io::Result<()> {
self.files.remove(name)
}
fn describe(&self) -> String {
"blind".into()
}
}
let (m, snap, log) = v6_library();
let e = Journal::open(Box::new(Blind { files: m.clone(), failed: false })).err().expect("refused");
assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be told")), "{e}");
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log)));
}
/// Given an older library that was not upgraded at open (its files can't be kept), when a later
/// snapshot would upgrade it (a compaction, or closing), then that snapshot is not written: the
/// library stays as it was, with nothing half kept, and is never upgraded without its way back.
#[test]
fn a_library_that_could_not_be_kept_is_not_upgraded_by_a_later_snapshot_either() {
let (m, snap, log) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") };
let (mut j, c, r) = Journal::open(Box::new(store)).unwrap();
assert_eq!(r.upgraded_from, None);
assert!(j.snapshot(&c).is_err(), "closing");
assert!(j.snapshot_in_background(&c).is_err(), "a compaction");
assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log)));
assert_eq!(m.files.lock().unwrap().keys().collect::<Vec<_>>(), [LOG, SNAPSHOT], "nothing half kept");
}
/// Given an older library whose upgrade could not be written at open (a full disk), when a later
/// snapshot is written (the disk has room again), then the files it was are kept first, as the
/// open would have kept them, and the library is upgraded.
#[test]
fn a_library_left_in_its_old_format_keeps_its_files_when_a_later_snapshot_upgrades_it() {
static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
let (m, snap, log) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) };
let (mut j, c, r) = Journal::open(Box::new(store)).unwrap();
assert_eq!((r.upgraded_from, r.kept.len()), (None, 0));
assert!(j.snapshot(&c).is_err(), "still full");
assert_eq!(m.files.lock().unwrap().keys().collect::<Vec<_>>(), [LOG, "catalog.log.v6-8", SNAPSHOT, "catalog.snap.v6-8"], "kept, not upgraded");
FULL.store(false, std::sync::atomic::Ordering::SeqCst);
j.snapshot(&c).unwrap();
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log)));
assert_eq!(snapshot_version(&m), u64::from(VERSION));
}
/// Given an older library whose log is damaged and whose snapshot can't be kept, when it is
/// opened, then it is refused and left as it was (it is not repaired without its way back).
#[test]
fn a_damaged_older_library_whose_snapshot_cannot_be_kept_is_refused() {
let (m, snap, log) = v6_library();
let mut lines: Vec<String> = String::from_utf8(log).unwrap().lines().map(str::to_string).collect();
lines[1] = lines[1].replacen("\"crc\":", "\"crc\":1", 1);
let damaged = format!("{}\n", lines.join("\n")).into_bytes();
m.set(LOG, damaged.clone());
let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.snap.v") };
let e = Journal::open(Box::new(store)).err().expect("refused");
assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be kept")), "{e}");
assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(damaged)));
}
/// Given an older library that was not upgraded at open (its files can't be kept), when a later
/// snapshot upgrades it, then the files that snapshot kept are told once, after it is written
/// (not before, not for a snapshot that failed, and the open's report has none).
#[test]
fn the_files_a_later_snapshot_keeps_are_told_once_it_is_written() {
static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
let (m, _, _) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) };
let (mut j, c, r) = Journal::open(Box::new(store)).unwrap();
assert!(r.kept.is_empty());
assert!(j.snapshot(&c).is_err(), "still full");
assert!(j.take_kept().is_empty(), "kept for a snapshot that is not written: nothing to tell yet");
FULL.store(false, std::sync::atomic::Ordering::SeqCst);
j.snapshot(&c).unwrap();
assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]);
assert!(j.take_kept().is_empty(), "once");
}
/// Given a library opened in its old format (its upgrade could not be written) that is then
/// changed, in this build's ops, before any snapshot is tried, when a later snapshot upgrades it,
/// then the files kept are the library as it was at open, under the names the open would have
/// given them: not the log as it is now, and nothing piles up. (An older build can read them
/// whatever was appended since.)
#[test]
fn files_kept_by_a_later_snapshot_are_the_library_as_it_was_at_open() {
static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
let (m, snap, log) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) };
let (mut j, c, _) = Journal::open(Box::new(store)).unwrap();
j.append(&[Op::SetLabelName { label: ColorLabel::ALL[0], name: Some("x".into()) }]).unwrap();
assert!(m.get(LOG).unwrap().len() > log.len(), "the log has grown");
assert!(j.snapshot(&c).is_err(), "still full");
FULL.store(false, std::sync::atomic::Ordering::SeqCst);
j.snapshot(&c).unwrap();
assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]);
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log)));
let files = m.files.lock().unwrap();
assert_eq!(files.keys().filter(|k| k.contains(".v6-")).count(), 2, "{:?}", files.keys());
}
/// Given a library left in its old format whose snapshot is in this build's format already (a
/// write that landed and reported a failure, before anything was kept), when snapshots are
/// written, then each of them works: the upgrade is done, with nothing to keep (the old files
/// are gone from under that name), and nothing is refused until the library is reopened.
#[test]
fn a_snapshot_that_landed_is_the_upgrade_done() {
static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
let (m, _, log) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) };
let (mut j, c, _) = Journal::open(Box::new(store)).unwrap();
FULL.store(false, std::sync::atomic::Ordering::SeqCst);
m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":8,\"catalog\":{}}}\n", c.to_snapshot()).into_bytes());
j.snapshot(&c).unwrap();
j.snapshot(&c).unwrap();
assert!(j.take_kept().is_empty());
assert_eq!(snapshot_version(&m), u64::from(VERSION));
assert!(!m.files.lock().unwrap().keys().any(|k| k.contains(".v6-")), "nothing kept from a snapshot that is not the old one");
let _ = log;
}
/// Given a library left in its old format, when a snapshot lands after its files were kept but
/// reports a failure, and the snapshot is tried again, then the retry goes through, and the files
/// told are the old library, not the snapshot that is there now.
#[test]
fn a_snapshot_that_landed_after_its_files_were_kept_is_tried_again() {
static LAND: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
struct Landing {
inner: Refusing,
}
impl Store for Landing {
fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
self.inner.read(name)
}
fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
use std::sync::atomic::Ordering::SeqCst;
if name == SNAPSHOT && LAND.load(SeqCst) == 1 {
// lands, and says it did not (the share dropped the answer)
self.inner.files.write_atomic(name, data)?;
LAND.store(2, SeqCst);
return Err(std::io::Error::other("the share went away"));
}
self.inner.write_atomic(name, data)
}
fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.inner.append(name, data)
}
fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> {
self.inner.truncate(name, len)
}
fn remove(&mut self, name: &str) -> std::io::Result<()> {
self.inner.remove(name)
}
fn describe(&self) -> String {
"landing".into()
}
}
let (m, snap, log) = v6_library();
let store =
Landing { inner: Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && LAND.load(std::sync::atomic::Ordering::SeqCst) == 0 } };
let (mut j, c, _) = Journal::open(Box::new(store)).unwrap();
LAND.store(1, std::sync::atomic::Ordering::SeqCst);
assert!(j.snapshot(&c).is_err(), "landed, and said it did not");
assert_eq!(snapshot_version(&m), u64::from(VERSION), "it did land");
// the upgrade landed: its way back is told now, not only after a later snapshot succeeds
assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]);
j.snapshot(&c).unwrap();
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log)), "the old library, not the snapshot that landed");
assert!(j.take_kept().is_empty(), "told once");
}
/// Given a library left in its old format whose snapshot failed after its files were kept, when
/// the snapshot is tried again (a compaction retries as the log grows), then the files are not
/// copied again: a large library is not written out in full at every retry.
#[test]
fn files_kept_for_a_failed_snapshot_are_not_written_again_on_a_retry() {
static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
let (m, _, _) = v6_library();
let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) };
let (mut j, c, _) = Journal::open(Box::new(store)).unwrap();
assert!(j.snapshot(&c).is_err());
m.set("catalog.snap.v6-8", b"marker".to_vec());
assert!(j.snapshot(&c).is_err(), "still full");
assert_eq!(m.get("catalog.snap.v6-8"), Some(b"marker".to_vec()), "not written again");
FULL.store(false, std::sync::atomic::Ordering::SeqCst);
j.snapshot(&c).unwrap();
assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]);
}
/// Given a library restored from an older backup that reaches the same format and change as a set
/// kept before (other bytes under the same names), when it is upgraded, then the set kept before is
/// left as it was, and the new files are kept beside it, both under names ending `-2`.
#[test]
fn files_kept_before_are_never_overwritten() {
let (m, snap, log) = v6_library();
m.set("catalog.snap.v6-8", b"an earlier snapshot".to_vec());
m.set("catalog.log.v6-8", b"an earlier log".to_vec());
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!((r.upgraded_from, r.kept.as_slice()), (Some(6), ["catalog.snap.v6-8-2".to_string(), "catalog.log.v6-8-2".to_string()].as_slice()));
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(b"an earlier snapshot".to_vec()), Some(b"an earlier log".to_vec())));
assert_eq!((m.get("catalog.snap.v6-8-2"), m.get("catalog.log.v6-8-2")), (Some(snap), Some(log)));
}
/// Given that set and a copy of it with the same name taken too, when the library is upgraded, then the next free name is used.
#[test]
fn the_next_free_name_is_used_when_several_are_taken() {
let (m, snap, _) = v6_library();
for name in ["catalog.snap.v6-8", "catalog.snap.v6-8-2"] {
m.set(name, name.as_bytes().to_vec());
}
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!(r.kept, ["catalog.snap.v6-8-3", "catalog.log.v6-8-3"]);
assert_eq!(m.get("catalog.snap.v6-8-3"), Some(snap));
}
/// Given kept files that are there already, byte for byte the same (an earlier open of this very library), when it is
/// opened, then they are the copy: nothing is written under another name.
#[test]
fn kept_files_that_are_there_already_are_reused() {
let (m, snap, log) = v6_library();
m.set("catalog.snap.v6-8", snap);
m.set("catalog.log.v6-8", log);
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!(r.kept, ["catalog.snap.v6-8", "catalog.log.v6-8"]);
assert!(!m.files.lock().unwrap().keys().any(|k| k.ends_with("-2")));
}
/// Given a set kept before whose snapshot is this very one but whose log holds other bytes, when the library is
/// upgraded, then both files of the new set take the next name, and the set kept before is left as it was.
#[test]
fn a_set_with_the_same_snapshot_and_another_log_is_not_reused_in_part() {
let (m, snap, log) = v6_library();
m.set("catalog.snap.v6-8", snap.clone());
m.set("catalog.log.v6-8", b"another log".to_vec());
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!(r.kept, ["catalog.snap.v6-8-2", "catalog.log.v6-8-2"]);
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap.clone()), Some(b"another log".to_vec())));
assert_eq!((m.get("catalog.snap.v6-8-2"), m.get("catalog.log.v6-8-2")), (Some(snap), Some(log)));
}
/// Given a hundred sets kept before under every name the upgrade may take, when the library is opened, then it is not
/// upgraded, nothing is written and nothing is removed: an upgrade that can't keep its files is not done.
#[test]
fn an_upgrade_is_refused_when_a_hundred_kept_sets_are_in_the_way() {
let (m, snap, log) = v6_library();
m.set("catalog.snap.v6-8", b"earlier".to_vec());
for copy in 2..=100 {
m.set(&format!("catalog.snap.v6-8-{copy}"), b"earlier".to_vec());
}
let before = m.files.lock().unwrap().clone();
let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap();
assert_eq!((r.upgraded_from, r.kept.len()), (None, 0));
assert_eq!(*m.files.lock().unwrap(), before, "nothing written or removed");
assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log)));
}
/// Given kept files that were there before and an upgrade that is then not written (a full disk), when the library is
/// opened, then they stay: only what this open wrote is removed again.
#[test]
fn an_upgrade_that_is_not_written_removes_only_what_it_kept() {
let (m, snap, log) = v6_library();
m.set("catalog.snap.v6-8", snap.clone());
m.set("catalog.log.v6-8", log.clone());
let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT };
let (_, _, r) = Journal::open(Box::new(store)).unwrap();
assert_eq!((r.upgraded_from, r.kept.len()), (None, 0));
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log)), "kept before, and still there");
assert_eq!(snapshot_version(&m), 6);
// and a different set that was in the way, with the new one not written whole
let (m, snap, log) = v6_library();
m.set("catalog.snap.v6-8", b"earlier".to_vec());
m.set("catalog.log.v6-8", b"earlier".to_vec());
let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") };
let (_, _, r) = Journal::open(Box::new(store)).unwrap();
assert_eq!((r.upgraded_from, r.kept.len()), (None, 0));
assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(b"earlier".to_vec()), Some(b"earlier".to_vec())));
assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log)));
assert_eq!(m.files.lock().unwrap().keys().collect::<Vec<_>>(), [LOG, "catalog.log.v6-8", SNAPSHOT, "catalog.snap.v6-8"], "nothing half kept");
}
/// Given a store that writes a kept file and then reports a failure (a network share that dropped its answer), when an
/// older library is opened, then it is not upgraded, and the file that landed is not left behind.
#[test]
fn a_kept_file_that_landed_despite_an_error_is_removed() {
struct Dropped(MemStore);
impl Store for Dropped {
fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
self.0.read(name)
}
fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.0.write_atomic(name, data)?;
if name.starts_with("catalog.log.v") {
return Err(std::io::Error::other("the share went away"));
}
Ok(())
}
fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.0.append(name, data)
}
fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> {
self.0.truncate(name, len)
}
fn remove(&mut self, name: &str) -> std::io::Result<()> {
self.0.remove(name)
}
fn describe(&self) -> String {
"dropped".into()
}
}
let (m, snap, log) = v6_library();
let (_, c, r) = Journal::open(Box::new(Dropped(m.clone()))).unwrap();
assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0));
assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log)));
assert_eq!(m.files.lock().unwrap().keys().collect::<Vec<_>>(), [LOG, SNAPSHOT], "nothing left of the kept set");
}
/// Given a store that keeps no replaced files (the browser's), when an older library is opened, then the report says so
/// (so a damaged log set aside beside it isn't presented as half of a copy of the library as it was).
#[test]
fn the_report_says_whether_the_store_keeps_files() {
struct Browser(MemStore);
impl Store for Browser {
fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
self.0.read(name)
}
fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.0.write_atomic(name, data)
}
fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.0.append(name, data)
}
fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> {
self.0.truncate(name, len)
}
fn keeps_replaced_formats(&self) -> bool {
false
}
fn describe(&self) -> String {
"browser".into()
}
}
let (m, _, _) = v6_library();
let (_, _, r) = Journal::open(Box::new(Browser(m.clone()))).unwrap();
assert!(!r.kept_files && r.kept.is_empty() && r.upgraded_from == Some(6), "{r:?}");
let (m, _, _) = v6_library();
let (_, _, r) = Journal::open(Box::new(m)).unwrap();
assert!(r.kept_files);
}
+78
View File
@@ -390,3 +390,81 @@ fn omitted_shared_grid_table_clears_dangling_references() {
let MaskShape::Object { seg: Some(seg), .. } = &p.history[0].settings.masks[0].components[0].shape else { panic!("an Object mask") };
assert_eq!(seg.data, blob, "the history step's inline grid is untouched");
}
/// Equal settings that refer to the same grid in a snapshot's table are held once after the
/// snapshot is read: resolving the references gives every holder its grid's data, and the
/// holders that are equal again share one value (a library with many masked photos is not
/// held once per photo and step). What is written back is unchanged.
#[test]
fn resolved_grid_references_share_equal_settings() {
let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]);
let settings = Arc::new(settings_with_seg(seg, 0.5));
let mut live = Catalog::new();
let mut ops = Vec::new();
for n in 1..=2u64 {
let id = PhotoId(n);
let name = format!("{n}.jpg");
ops.push(Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, &name, "JPEG", 60, 40, "2026-01-01")) });
ops.push(Op::SetDevelop { id, settings: settings.clone(), label: "Exposure".into(), edited: Some("t".into()) });
ops.push(Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings: settings.clone() } });
ops.push(Op::SetVersions {
id,
versions: vec![Version { name: "v".into(), created: "2026-01-01".into(), settings: settings.clone(), auto: false }],
});
}
for op in &ops {
live.apply(op.clone()).unwrap();
}
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&ops).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let snap_bytes = m.get(SNAPSHOT).unwrap();
let v: serde_json::Value = serde_json::from_slice(&snap_bytes).unwrap();
assert_eq!(v["catalog"]["grids"].as_array().unwrap().len(), 1, "the snapshot refers to its one grid");
assert!(std::str::from_utf8(&snap_bytes).unwrap().contains("\"grid\":0"), "and its masks hold references");
let (_, loaded, report) = open(&m);
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
let first = &loaded.photo(PhotoId(1)).unwrap().develop;
for n in 1..=2 {
let p = loaded.photo(PhotoId(n)).unwrap();
assert!(Arc::ptr_eq(&p.develop, first), "photo {n}'s settings");
assert!(p.history.iter().all(|h| Arc::ptr_eq(&h.settings, first)), "photo {n}'s history");
assert!(p.versions.iter().all(|v| Arc::ptr_eq(&v.settings, first)), "photo {n}'s versions");
}
}
/// A masked photo whose history is longer than the few values sharing remembers still holds its
/// settings and its last step once: the references of equal holders resolve to one value, not to
/// a copy per holder that is shared only when it happens to be remembered.
#[test]
fn a_masked_photos_settings_share_with_its_last_step_after_a_long_history() {
let seg = SegMask::from_logits(32, &vec![1.0f32; 32 * 32]);
let id = PhotoId(1);
let mut live = Catalog::new();
let mut ops = vec![Op::AddPhoto { photo: Box::new(Photo::new(id, Source::Demo { scene: 0 }, "1.jpg", "JPEG", 60, 40, "2026-01-01")) }];
let mut last = Arc::new(DevelopSettings::default());
for i in 1..=10u32 {
last = Arc::new(settings_with_seg(seg.clone(), f64::from(i) * 0.1));
ops.push(Op::PushHistory { id, step: HistoryStep { label: "Exposure".into(), settings: last.clone() } });
}
ops.push(Op::SetDevelop { id, settings: last, label: "Exposure".into(), edited: Some("t".into()) });
for op in &ops {
live.apply(op.clone()).unwrap();
}
let m = MemStore::new();
let (mut j, _, _) = open(&m);
j.append(&ops).unwrap();
j.snapshot(&live).unwrap();
drop(j);
let (_, loaded, report) = open(&m);
assert_eq!(report.repaired, Vec::<String>::new(), "{:?}", report.repaired);
assert_eq!(loaded.to_snapshot(), live.to_snapshot());
let p = loaded.photo(id).unwrap();
assert_eq!(p.history.len(), 10);
let last = p.history.last().unwrap();
assert!(Arc::ptr_eq(&p.develop, &last.settings), "the photo's settings and its last step are one value");
}
+397
View File
@@ -0,0 +1,397 @@
//! Photos whose develop settings are equal share one settings value in memory
//! ([`crate::shared`]): a library of photos nobody edited holds the defaults once, not once per
//! photo.
use std::sync::Arc;
use lightcraft_develop::DevelopSettings;
use crate::journal::encode_record;
use crate::*;
fn photo(id: u64) -> Photo {
Photo::new(
PhotoId(id),
Source::File { path: format!("/pictures/2019/trip/IMG_{id:06}.jpg") },
&format!("IMG_{id:06}.jpg"),
"JPEG",
4032,
3024,
"2026-10-10T12:00:00",
)
}
fn raw(id: u64) -> Photo {
let mut p = photo(id);
p.kind = MediaKind::Raw;
p.format = "CR3".into();
p.as_shot_wb = Some((5200.0, 3.0));
// as an import gives it: settings of its own that equal every other CR3's
p.develop = Arc::new(p.import_defaults());
p
}
fn edited(d: impl FnOnce(&mut DevelopSettings)) -> Arc<DevelopSettings> {
let mut s = DevelopSettings::default();
d(&mut s);
Arc::new(s)
}
fn catalog_of(photos: impl IntoIterator<Item = Photo>) -> Catalog {
let mut c = Catalog::new();
for p in photos {
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
}
c
}
fn settings_of(c: &Catalog, id: u64) -> &Arc<DevelopSettings> {
&c.photo(PhotoId(id)).unwrap().develop
}
/// How many different settings values the catalog's photos hold between them.
fn distinct(c: &Catalog) -> usize {
let mut seen: Vec<*const DevelopSettings> = c.photos().map(|p| Arc::as_ptr(&p.develop)).collect();
seen.sort_unstable();
seen.dedup();
seen.len()
}
/// The catalog through a saved library and back: from its snapshot, from a library directory's
/// snapshot file, and from the log alone.
fn reloaded(c: &Catalog) -> Vec<(&'static str, Catalog)> {
let mut out = vec![("snapshot", Catalog::from_snapshot(&c.to_snapshot()).unwrap())];
let m = MemStore::new();
let (mut j, _, _) = Journal::open(Box::new(m.clone())).unwrap();
j.snapshot(c).unwrap();
drop(j);
out.push(("library", Journal::open(Box::new(m)).unwrap().1));
let m = MemStore::new();
let log: String =
c.photos().enumerate().map(|(k, p)| encode_record(k as u64 + 1, &Op::AddPhoto { photo: Box::new(p.as_ref().clone()) }) + "\n").collect();
m.set(journal::LOG, log.into_bytes());
out.push(("the log", Journal::open(Box::new(m)).unwrap().1));
out
}
/// Given photos nobody edited, when they are added to a catalog or a saved library is opened,
/// then they all hold the same settings value.
#[test]
fn unedited_photos_share_the_default_settings() {
let c = catalog_of((1..=20).map(photo));
assert_eq!(distinct(&c), 1);
assert_eq!(**settings_of(&c, 1), DevelopSettings::default());
for (how, back) in reloaded(&c) {
assert_eq!(back.len(), 20, "{how}");
assert_eq!(distinct(&back), 1, "{how}");
assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}");
}
}
/// Given raws that were given their import defaults one by one (equal settings, a value each),
/// then they share one value too, also after the library is opened again.
#[test]
fn photos_with_equal_settings_share_them() {
let c = catalog_of((1..=20).map(raw));
assert_ne!(**settings_of(&c, 1), DevelopSettings::default());
assert_eq!(distinct(&c), 1);
for (how, back) in reloaded(&c) {
assert_eq!(distinct(&back), 1, "{how}");
assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}");
}
// settings set by a change are shared like those a photo arrives with
let mut c = catalog_of((1..=4).map(photo));
for id in 1..=4 {
c.apply(Op::SetDevelop { id: PhotoId(id), settings: edited(|s| s.light.exposure = 0.5), label: "Exposure".into(), edited: None }).unwrap();
}
assert_eq!(distinct(&c), 1);
}
/// Given photos that share their settings, when one of them is edited, then only that one
/// changes: sharing is never a way for one photo's edit to reach another.
#[test]
fn editing_one_photo_leaves_the_ones_it_shared_with() {
let mut c = catalog_of((1..=3).map(photo));
let undo =
c.apply(Op::SetDevelop { id: PhotoId(2), settings: edited(|s| s.light.exposure = 1.0), label: "Exposure".into(), edited: None }).unwrap();
assert_eq!(settings_of(&c, 2).light.exposure, 1.0);
assert_eq!((&**settings_of(&c, 1), &**settings_of(&c, 3)), (&DevelopSettings::default(), &DevelopSettings::default()));
assert!(Arc::ptr_eq(settings_of(&c, 1), settings_of(&c, 3)));
// and undoing it gives the photo the shared value back
c.apply(undo).unwrap();
assert_eq!(distinct(&c), 1);
// a caller that edits a copy of a photo's settings (`Arc::make_mut` copies a shared value) and
// gives it back as a change leaves the photos that held the old value alone
let mut own = c.photo(PhotoId(1)).unwrap().as_ref().clone();
Arc::make_mut(&mut own.develop).light.contrast = 30.0;
c.apply(Op::SetDevelop { id: PhotoId(1), settings: own.develop.clone(), label: "Contrast".into(), edited: None }).unwrap();
assert_eq!(settings_of(&c, 1).light.contrast, 30.0);
assert_eq!(**settings_of(&c, 2), DevelopSettings::default());
assert_eq!(**settings_of(&c, 3), DevelopSettings::default());
assert_eq!(*shared::default_settings(), DevelopSettings::default());
c.apply(Op::SetDevelop { id: PhotoId(1), settings: shared::default_settings(), label: "Reset".into(), edited: None }).unwrap();
// the same after a reload
for (how, mut back) in reloaded(&c) {
back.apply(Op::SetDevelop { id: PhotoId(2), settings: edited(|s| s.light.exposure = 1.0), label: "Exposure".into(), edited: None }).unwrap();
assert_eq!(**settings_of(&back, 1), DevelopSettings::default(), "{how}");
assert_eq!(**settings_of(&back, 3), DevelopSettings::default(), "{how}");
}
}
/// A photo's history steps, versions and import look share with its settings where they are
/// equal: after the library is opened again as before it was saved.
#[test]
fn a_photos_history_shares_with_its_settings() {
let now = edited(|s| s.light.exposure = 0.3);
let before = edited(|s| s.light.contrast = 10.0);
let mut p = photo(1);
p.develop = now.clone();
p.history = vec![
HistoryStep { label: "Contrast".into(), settings: before.clone() },
HistoryStep { label: "Reset".into(), settings: Arc::new(DevelopSettings::default()) },
HistoryStep { label: "Exposure".into(), settings: now.clone() },
];
p.versions = vec![Version { name: "A".into(), created: "2026-10-10".into(), settings: before.clone(), auto: false }];
p.import_look = Some(before);
let c = catalog_of([p, photo(2)]);
for (how, back) in reloaded(&c).into_iter().chain([("as added", c.clone())]) {
let p = back.photo(PhotoId(1)).unwrap();
assert!(Arc::ptr_eq(&p.develop, &p.history[2].settings), "{how}");
assert!(Arc::ptr_eq(&p.history[0].settings, &p.versions[0].settings), "{how}");
assert!(Arc::ptr_eq(&p.history[0].settings, p.import_look.as_ref().unwrap()), "{how}");
assert!(Arc::ptr_eq(&p.history[1].settings, settings_of(&back, 2)), "{how}: the defaults");
assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}");
}
}
/// A long history (more steps than a thread remembers values) still ends with the photo's
/// settings as one value.
#[test]
fn a_long_history_ends_with_the_photos_settings() {
let mut p = photo(1);
let mut d = DevelopSettings::default();
for step in 0..40 {
d.light.exposure = f64::from(step) * 0.01;
p.history.push(HistoryStep { label: "Exposure".into(), settings: Arc::new(d.clone()) });
}
p.develop = Arc::new(d);
let c = catalog_of([p, photo(2)]);
for (how, back) in reloaded(&c).into_iter().chain([("as added", c.clone())]) {
let p = back.photo(PhotoId(1)).unwrap();
assert!(Arc::ptr_eq(&p.develop, &p.history[39].settings), "{how}");
assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}");
// the next photo's settings are its own
assert_eq!(**settings_of(&back, 2), DevelopSettings::default(), "{how}");
}
}
/// Settings that are equal but for the sign of a zero are not the same settings (their JSON,
/// and the fingerprint and preview-cache key made from it, differ): they are never shared.
#[test]
fn settings_that_differ_in_the_sign_of_a_zero_are_not_shared() {
let negative = |id: u64| {
let mut p = photo(id);
p.develop = edited(|s| s.wb.tint = -0.0);
p
};
let c = catalog_of([photo(1), negative(2), photo(3), negative(4)]);
assert_eq!(*settings_of(&c, 2), *settings_of(&c, 1), "equal as numbers");
for (how, back) in reloaded(&c).into_iter().chain([("as added", c.clone())]) {
for id in [2, 4] {
let p = back.photo(PhotoId(id)).unwrap();
assert!(!Arc::ptr_eq(&p.develop, settings_of(&back, 1)), "{how}");
assert!(p.develop.wb.tint.is_sign_negative(), "{how}");
assert_eq!(p.develop.hash64(), c.photo(PhotoId(id)).unwrap().develop.hash64(), "{how}");
}
assert!(settings_of(&back, 1).wb.tint.is_sign_positive() && Arc::ptr_eq(settings_of(&back, 1), settings_of(&back, 3)), "{how}");
}
}
/// Settings that aren't the defaults and their twin with a negative zero, met one after the
/// other in either order, as two photos' settings and as a photo's settings and history step:
/// each keeps its own sign, and neither is ever handed the other's value.
#[test]
fn a_negative_zero_twin_is_never_what_others_share() {
let twin = |tint: f64| {
edited(|s| {
s.light.exposure = 0.5;
s.wb.tint = tint;
})
};
for (first, second) in [(-0.0, 0.0), (0.0, -0.0)] {
let (mut a, mut b, mut both) = (photo(1), photo(2), photo(3));
a.develop = twin(first);
b.develop = twin(second);
both.develop = twin(first);
both.history = vec![HistoryStep { label: "x".into(), settings: twin(second) }, HistoryStep { label: "y".into(), settings: twin(first) }];
let c = catalog_of([a, b, both]);
for (how, back) in reloaded(&c).into_iter().chain([("as added", c.clone())]) {
let sign = |s: &Arc<DevelopSettings>| s.wb.tint.is_sign_negative();
let (a, b, both) = (settings_of(&back, 1), settings_of(&back, 2), back.photo(PhotoId(3)).unwrap());
assert_eq!((sign(a), sign(b)), (first.is_sign_negative(), second.is_sign_negative()), "{how} {first} {second}");
assert!(!Arc::ptr_eq(a, b), "{how}");
assert_eq!((sign(&both.develop), sign(&both.history[0].settings), sign(&both.history[1].settings)), (sign(a), sign(b), sign(a)), "{how}");
assert!(!Arc::ptr_eq(&both.history[0].settings, &both.history[1].settings), "{how}");
assert_eq!((a.hash64(), b.hash64()), (twin(first).hash64(), twin(second).hash64()), "{how}");
assert_ne!(a.hash64(), b.hash64());
assert_eq!(back.to_snapshot(), c.to_snapshot(), "{how}");
}
}
}
/// A change's settings that equal the photo's own as numbers but differ in the sign of a zero are not handed
/// the photo's value, in either order.
#[test]
fn changes_never_take_the_photos_settings_across_a_negative_zero() {
let twin = |tint: f64| {
edited(|s| {
s.light.exposure = 0.5;
s.wb.tint = tint;
})
};
for (own, given) in [(0.0, -0.0), (-0.0, 0.0)] {
let mut c = catalog_of([photo(1)]);
c.apply(Op::SetDevelop { id: PhotoId(1), settings: twin(own), label: "Tint".into(), edited: None }).unwrap();
c.apply(Op::SetHistory { id: PhotoId(1), history: vec![HistoryStep { label: "Tint".into(), settings: twin(given) }] }).unwrap();
let p = c.photo(PhotoId(1)).unwrap();
assert!(!Arc::ptr_eq(&p.develop, &p.history[0].settings), "own {own:?}, given {given:?}");
assert_eq!(p.history[0].settings.wb.tint.is_sign_negative(), given.is_sign_negative());
assert_eq!(p.develop.wb.tint.is_sign_negative(), own.is_sign_negative());
}
}
/// Settings given by any change are shared: a history step pushed or set, and versions.
#[test]
fn settings_given_by_changes_are_shared() {
let look = || edited(|s| s.light.exposure = 0.7);
let mut c = catalog_of((1..=2).map(photo));
c.apply(Op::SetDevelop { id: PhotoId(1), settings: look(), label: "Exposure".into(), edited: None }).unwrap();
c.apply(Op::PushHistory { id: PhotoId(1), step: HistoryStep { label: "Exposure".into(), settings: look() } }).unwrap();
let p = c.photo(PhotoId(1)).unwrap();
assert!(Arc::ptr_eq(&p.develop, &p.history[0].settings), "PushHistory");
c.apply(Op::SetVersions { id: PhotoId(2), versions: vec![Version { name: "A".into(), created: "2026".into(), settings: look(), auto: false }] })
.unwrap();
assert!(Arc::ptr_eq(&c.photo(PhotoId(2)).unwrap().versions[0].settings, settings_of(&c, 1)), "SetVersions");
c.apply(Op::SetHistory { id: PhotoId(2), history: vec![HistoryStep { label: "A".into(), settings: look() }] }).unwrap();
assert!(Arc::ptr_eq(&c.photo(PhotoId(2)).unwrap().history[0].settings, settings_of(&c, 1)), "SetHistory");
// a new photo's settings are the shared defaults from the start
assert!(Arc::ptr_eq(&photo(7).develop, &photo(8).develop));
}
/// Settings given by a change are shared with the photo's own settings even when the thread's list of recent
/// values has since moved on to others: the target photo's settings are what they are compared with first.
#[test]
fn settings_given_by_changes_are_shared_with_the_photos_own_even_when_not_recent() {
let look = || edited(|s| s.light.exposure = 0.7);
let mut c = catalog_of((1..=2).map(photo));
c.apply(Op::SetDevelop { id: PhotoId(1), settings: look(), label: "Exposure".into(), edited: None }).unwrap();
// more different values than the thread remembers, held by another photo
let others = |c: &mut Catalog| {
let versions = (1..=6u32)
.map(|i| Version {
name: format!("V{i}"),
created: "2026".into(),
settings: edited(|s| s.light.exposure = f64::from(i) / 10.0 + 1.0),
auto: false,
})
.collect();
c.apply(Op::SetVersions { id: PhotoId(2), versions }).unwrap();
};
others(&mut c);
c.apply(Op::SetHistory { id: PhotoId(1), history: vec![HistoryStep { label: "A".into(), settings: look() }] }).unwrap();
let p = c.photo(PhotoId(1)).unwrap();
assert!(Arc::ptr_eq(&p.develop, &p.history[0].settings), "SetHistory");
others(&mut c);
c.apply(Op::PushHistory { id: PhotoId(1), step: HistoryStep { label: "B".into(), settings: look() } }).unwrap();
let p = c.photo(PhotoId(1)).unwrap();
assert!(Arc::ptr_eq(&p.develop, &p.history[1].settings), "PushHistory");
others(&mut c);
c.apply(Op::SetVersions { id: PhotoId(1), versions: vec![Version { name: "C".into(), created: "2026".into(), settings: look(), auto: false }] })
.unwrap();
let p = c.photo(PhotoId(1)).unwrap();
assert!(Arc::ptr_eq(&p.develop, &p.versions[0].settings), "SetVersions");
}
/// Settings that can't be read are still an error naming what is wrong, not shared defaults.
#[test]
fn bad_settings_are_still_refused() {
for bad in [r#"{"light":{"exposure":"a lot"}}"#, r#"["x"]"#, r#""x""#, r#"7"#, r#"null"#] {
let record = format!(
r#"{{"id":1,"source":{{"type":"file","path":"/a.jpg"}},"file_name":"a.jpg","format":"JPEG","width":1,"height":1,"imported":"2026","develop":{bad}}}"#
);
assert!(serde_json::from_str::<Photo>(&record).is_err(), "{bad}");
}
}
/// What a thread remembers to compare with keeps no settings alive, and is a handful of values:
/// settings no photo holds any more are freed, however many were seen.
#[test]
fn remembered_settings_are_not_kept_alive() {
let mut watched = Vec::new();
for k in 0..50 {
let s = shared::settings(edited(|s| s.light.exposure = 0.001 * f64::from(k + 1)));
watched.push(Arc::downgrade(&s));
}
assert!(watched.iter().all(|w| w.upgrade().is_none()), "{} kept alive", watched.iter().filter(|w| w.upgrade().is_some()).count());
// and of values that are all still held (a library of photos each edited differently), it
// remembers a handful, not all of them
let held: Vec<_> = (1..=200).map(|k| shared::settings(edited(|s| s.light.contrast = f64::from(k)))).collect();
assert!(shared::remembered() <= 4, "{} remembered", shared::remembered());
drop(held);
// while they are held, an equal value is still found
let held = shared::settings(edited(|s| s.light.exposure = 0.9));
assert!(Arc::ptr_eq(&held, &shared::settings(edited(|s| s.light.exposure = 0.9))));
}
/// New photos start from the one held default.
#[test]
fn a_new_photos_settings_are_the_held_default() {
assert!(Arc::ptr_eq(&photo(7).develop, &shared::default_settings()));
}
/// A negative zero anywhere in the settings, in whatever field it is, keeps them from being
/// shared with the equal settings that hold a positive one.
#[test]
fn a_negative_zero_in_any_field_is_found() {
fn zeros(v: &serde_json::Value, path: &mut Vec<String>, out: &mut Vec<Vec<String>>) {
match v {
serde_json::Value::Number(n) if n.is_f64() && n.as_f64() == Some(0.0) => out.push(path.clone()),
serde_json::Value::Object(m) => {
for (k, v) in m {
path.push(k.clone());
zeros(v, path, out);
path.pop();
}
}
serde_json::Value::Array(a) => {
for (i, v) in a.iter().enumerate() {
path.push(i.to_string());
zeros(v, path, out);
path.pop();
}
}
_ => {}
}
}
let default = serde_json::to_value(DevelopSettings::default()).unwrap();
let mut found = Vec::new();
zeros(&default, &mut Vec::new(), &mut found);
assert!(found.len() > 20, "{} zeros in the defaults: the walk finds none", found.len());
let base = shared::settings(Arc::new(DevelopSettings::default()));
let mut checked = 0;
for path in found {
let mut v = default.clone();
let pointer = path.iter().map(|k| format!("/{k}")).collect::<String>();
*v.pointer_mut(&pointer).unwrap() = serde_json::Value::Number(serde_json::Number::from_f64(-0.0).unwrap());
let twin: DevelopSettings = serde_json::from_value(v).unwrap();
if twin.hash64() == DevelopSettings::default().hash64() {
continue; // (a zero the settings don't write back: nothing to tell apart)
}
assert_eq!(twin, DevelopSettings::default(), "{path:?}");
checked += 1;
let twin = Arc::new(twin);
let shared = shared::settings(twin.clone());
assert!(Arc::ptr_eq(&shared, &twin) && !Arc::ptr_eq(&shared, &base), "{path:?} was shared with the defaults");
}
assert!(checked > 20, "only {checked} negative zeros could be told apart");
}
+1
View File
@@ -52,6 +52,7 @@ lightcraft-segment = { workspace = true, optional = true }
# model downloads run natively only (the web build fetches no models)
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
lightcraft-fetch = { workspace = true }
jiff = { workspace = true }
# capture-time parsing for face recognition (native only)
chrono = { workspace = true }
# free space of the drive holding the preview cache (the low-disk alert; pure Rust: rustix / windows-sys)
+8 -20
View File
@@ -80,28 +80,16 @@ pub fn specs() -> Vec<CommandSpec> {
has_active,
set_before
),
cmd!(
"beforeAfter.copyAfterToBefore",
"Copy After's Settings to Before",
["View", "Before/After Settings"],
None,
"{}",
has_active,
|s, _| { set_before(s, &json!({"source": "current"})) }
),
cmd!(
"beforeAfter.copyBeforeToAfter",
"Copy Before's Settings to After",
["View", "Before/After Settings"],
None,
"{}",
has_active,
|s, _| { before_to_after(s, false) }
),
cmd!("beforeAfter.swap", "Swap Before and After Settings", ["View", "Before/After Settings"], None, "{}", has_active, |s, _| {
cmd!("beforeAfter.copyAfterToBefore", "Copy After's Settings to Before", ["View", "Before/After"], None, "{}", has_active, |s, _| {
set_before(s, &json!({"source": "current"}))
}),
cmd!("beforeAfter.copyBeforeToAfter", "Copy Before's Settings to After", ["View", "Before/After"], None, "{}", has_active, |s, _| {
before_to_after(s, false)
}),
cmd!("beforeAfter.swap", "Swap Before and After Settings", ["View", "Before/After"], None, "{}", has_active, |s, _| {
before_to_after(s, true)
}),
cmd!("beforeAfter.resetBefore", "Reset Before to Import State", ["View", "Before/After Settings"], None, "{}", has_active, |s, _| {
cmd!("beforeAfter.resetBefore", "Reset Before to Import State", ["View", "Before/After"], None, "{}", has_active, |s, _| {
set_before(s, &json!({"source": "import"}))
}),
]
+1 -1
View File
@@ -302,7 +302,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(
"faces.detect",
"Detect Faces",
["Photo"],
["Photo", "Metadata"],
None,
"{ids?, apply?: bool (default true), score?: 0.6, nmsIou?: 0.3, maxFaces?} → {photos: [{id, faces: [{rect, score, landmarks}]}]}. Finds faces with the YuNet detector (download it first: `faces.models.download {id: \"yunet-2023mar\"}`) and, unless `apply` is false, adds them as unnamed face regions (one undo step), replacing earlier detections but never regions from XMP or ones you named; the sidecar is not touched",
has_selection,
+2 -2
View File
@@ -1,4 +1,4 @@
//! Focus points for photos already in the library: `photo.readFocusPoints` (Photo ▸ Read Focus Points) and the
//! Focus points for photos already in the library: `photo.readFocusPoints` (Photo ▸ Metadata ▸ Read Focus Points) and the
//! per-frame `focus.pump` that keeps the background job going. The job itself is `crate::focus_scan`.
use serde_json::Value;
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(
"photo.readFocusPoints",
"Read Focus Points",
["Photo"],
["Photo", "Metadata"],
None,
"{ids?, wait?: false} → {queued, running, last?: {total, done, found, none, unavailable, bytesRead, seconds, cancelled}} — read the camera's focus point for photos imported before it was read (Sony α1 and A7S III raws and JPEGs), from the few KB of each file that hold it, on a background job with a row in the activity stack. Without `ids`, every photo in the library not looked at yet; with `ids`, those photos, looked at again. Photos that have a point keep it. No undo step and no sidecar write. `wait: true` returns when all are read (scripts)",
super::always,
+4 -3
View File
@@ -145,7 +145,8 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "none of these photos has a GPS position"));
}
let dir = dataset_dir(p).ok_or_else(|| bad(C, "no settings folder: give `dataset`"))?;
let names = s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo → Download Place Names)")))?;
let names =
s.place_names.load(&dir).map_err(|e| bad(C, format!("{e}: download the place names first (Photo → Metadata → Download Place Names)")))?;
// a large selection shows in the activity stack and can be stopped
let task = (todo.len() > 1).then(|| s.activity.start("geocode", "Looking up places", Cancel::Yes));
let mut ops = Vec::new();
@@ -311,7 +312,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(
"metadata.reverseGeocode",
"Fill Location from GPS",
["Photo"],
["Photo", "Metadata"],
None,
"{ids?, overwrite?: bool (also replace place fields that already have text; default false: only empty ones are filled), dryRun?, dataset?: folder, maxDistance?: metres (past this distance from the town found, City is left empty and the town is given as nearestCity)} → {looked, found, changed, photos: [{id, place: {sublocation, city, state, country, iso, distance}, nearestCity?}], attribution} — fills City / State / Country (and Sublocation when known) from GPS with the offline GeoNames place names (download them first); one undo step. The place names list towns of 15 000 people or more (GeoNames cities15000): a photo taken in a smaller town gets the nearest larger one, up to 50 km away (`distance` says how far); `maxDistance` keeps such a town out of City",
has_selection,
@@ -323,7 +324,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.push(cmd!(
"metadata.downloadPlaceNames",
"Download Place Names (GeoNames)",
["Photo"],
["Photo", "Metadata"],
None,
"{} → {started, path, attribution} — downloads the GeoNames cities list (CC-BY 4.0, ~3 MB, from download.geonames.org) in the background for Fill Location from GPS, always into `geonames` in the settings folder (a folder or server named by the caller is refused); no photo data is sent",
always,
+4 -4
View File
@@ -379,7 +379,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(
"library.refresh",
"Refresh View",
["View"],
["View", "Sort"],
None,
"{} — show what matches now: a view that holds its photos (`library.holdView`) lets go of the ones that stopped matching a smart album's rules, Picks or the filter bar since it was opened, sorted or last refreshed",
always,
@@ -391,7 +391,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(
"library.holdView",
"Hold View Until Refreshed",
["View"],
["View", "Sort"],
None,
"{on?: bool (toggles when omitted)} → {hold} — when on, an edit that makes a photo stop matching the view (a keyword given in a smart album of photos without keywords, a flag taken off in Picks, a rating under the filter bar's) keeps it in the view until `library.refresh`, Reshuffle, or another source, filter or sort; photos that start matching still appear at once, and deleting a photo or taking it out of the album or folder shown still takes it out of the view. Changing a smart album's rules is another view too. Off (the default): the view follows every edit. Kept with the library's preferences; asking for the state it already has changes nothing",
always,
@@ -504,7 +504,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(query "library.devices", "Cameras and Cards", [], None, "{} → [{name, path (its DCIM folder), root}] — mounted volumes with a DCIM folder", always, |_, _| {
Ok(serde_json::to_value(crate::devices::devices_now()).unwrap_or_default())
}),
cmd!(query "photo.copyMetadata", "Copy Metadata", ["Photo"], Some("Cmd+Alt+Shift+C"), "{} — title, caption, copyright (notice, status, usage terms, info URL), creator, location and keywords of the active photo", has_active, |s, _| {
cmd!(query "photo.copyMetadata", "Copy Metadata", ["Photo", "Metadata"], Some("Cmd+Alt+Shift+C"), "{} — title, caption, copyright (notice, status, usage terms, info URL), creator, location and keywords of the active photo", has_active, |s, _| {
let id = s.active().ok_or_else(|| bad("photo.copyMetadata", "no active photo"))?;
let m = &s.catalog.photo(id).ok_or_else(|| bad("photo.copyMetadata", "no photo"))?.meta;
let v = json!({"title": m.title, "caption": m.caption, "altText": m.alt_text, "extendedDescription": m.extended_description,
@@ -517,7 +517,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(
"photo.pasteMetadata",
"Paste Metadata",
["Photo"],
["Photo", "Metadata"],
Some("Cmd+Alt+Shift+V"),
"{ids?, fields?: [title|caption|copyright|copyrightStatus|usageTerms|copyrightUrl|creator|location|keywords] (default: all copied)}",
has_selection,
+2 -2
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(
"photo.saveMetadataToFile",
"Save Metadata to File",
["Photo"],
["Photo", "Metadata"],
Some("Cmd+S"),
"{ids?} — writes each photo's XMP sidecar (metadata + develop settings) next to the original, merged into an existing one (other apps' data kept; an unreadable one is backed up first) → {written: [path], merged: [path], backups: [{path, backup}], failed}",
has_selection,
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(
"photo.readMetadataFromFile",
"Read Metadata from File",
["Photo"],
["Photo", "Metadata"],
None,
"{ids?} — reads each photo's XMP sidecar, or embedded XMP in raw/DNG and JPEG files when no sidecar exists: metadata and develop settings, one undo step; never writes the sidecar, even with auto-write on; JPEG uses the first complete standard XMP APP1 before SOS/EOI, within 16 MiB of headers and 4096 marker/fill steps; an unreadable sidecar fails without embedded fallback → {read, failed, warnings?: [{path, code, profile?, mode?, fields?}]}",
has_selection,
+1 -1
View File
@@ -31,7 +31,7 @@ pub fn load(s: &mut Session) {
..Default::default()
};
// one demo photo carries a camera focus point (as a Sony raw would), on the bloom's centre, so
// View ▸ Focus Point and Zoom to Focus Point can be tried without a camera file
// View ▸ Loupe Overlay ▸ Focus Point and Zoom to Focus Point can be tried without a camera file
if sc.name == "Cosmos bloom" {
p.meta.focus = Some(lightcraft_meta::FocusPoint {
rect: lightcraft_geom::Rect { x0: 0.42, y0: 0.433, x1: 0.50, y1: 0.487 },
+3 -2
View File
@@ -117,11 +117,12 @@ fn fs_load<T>(path: &str, max_edge: usize, load: impl FnOnce(Vec<u8>) -> Result<
}
/// The modification time in `meta` as ISO 8601 (see [`ProbeInfo::file_modified`]); `None` when the
/// filesystem doesn't say or the time is before 1970.
/// filesystem doesn't say or the time is before 1970. In the host's time zone, like every date the
/// catalog stores: this is the capture date of a file that carries none of its own.
fn modified_iso(meta: &std::fs::Metadata) -> Option<String> {
let t = meta.modified().ok()?;
let secs = i64::try_from(t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs()).ok()?;
Some(crate::import::civil(secs))
Some(crate::import::local_civil(secs))
}
impl crate::Session {
+9 -1
View File
@@ -469,8 +469,16 @@ fn undated_files_take_the_file_date() {
let path = dir.join("export.jpg");
std::fs::write(&path, &jpeg).unwrap();
let path = path.to_string_lossy().to_string();
// The case reported in issue #2284: a JPEG that went through a messenger keeps no capture
// date, only a modification time, here 2026-10-18 20:15:11 in UTC-5. Pinning it also dates
// the file in the other half of the year from "now", so a zone with summer time is read at
// the right instant and not at today's offset.
let shot = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").unwrap().unix_seconds();
let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(u64::try_from(shot).unwrap());
std::fs::File::options().write(true).open(&path).unwrap().set_modified(when).unwrap();
let mtime = std::fs::metadata(&path).unwrap().modified().unwrap().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
let want = crate::import::civil(mtime as i64);
assert_eq!(mtime as i64, shot, "the file date is the one the test set");
let want = crate::import::local_civil(mtime as i64);
let (_, probe) = fs_hooks();
let info = probe(&path).unwrap();
assert_eq!(info.captured, None, "the file itself has no date");
+1 -1
View File
@@ -46,7 +46,7 @@ mod types;
pub(crate) use commit::start_from_file;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use commit::workers;
pub use commit::{batch_size, civil, commit_prepared, system_clock};
pub use commit::{batch_size, civil, commit_prepared, local_civil, local_instant, system_clock};
pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults};
#[cfg(test)]
use files::expand_knowing;
+144 -1
View File
@@ -388,7 +388,7 @@ pub fn system_clock() -> String {
#[cfg(not(target_arch = "wasm32"))]
{
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
civil(secs)
local_civil(secs)
}
#[cfg(target_arch = "wasm32")]
{
@@ -400,3 +400,146 @@ pub fn system_clock() -> String {
pub fn civil(secs: i64) -> String {
lightcraft_catalog::dates::civil(secs)
}
/// Unix seconds → `YYYY-MM-DDTHH:MM:SS` in the host's time zone: the local civil time every date
/// the catalog stores is in (`captured`, `imported`, an album's `created`, an edit's `edited`).
///
/// The offset is the one in force *at that instant*, not today's, so a photo from July keeps
/// summer time when it is read in January. A host whose zone cannot be read falls back to UTC, as
/// the web build does (issue #2284: a file with no capture date was dated by its modification time
/// in UTC, which put an evening photo on the next day).
#[cfg(not(target_arch = "wasm32"))]
pub fn local_civil(secs: i64) -> String {
civil_in(secs, &system_zone())
}
/// The host's zone. It holds the whole rule set, so each instant still gets the offset that was in
/// force then. jiff keeps the zone it read for five minutes (a cheap shared handle, so an import
/// does not re-read the system database per file) and reads it again after that, so a host whose
/// zone is changed while LightCraft runs dates its files in the new zone from then on, not in the
/// one it started in.
#[cfg(not(target_arch = "wasm32"))]
fn system_zone() -> jiff::tz::TimeZone {
jiff::tz::TimeZone::system()
}
/// [`local_civil`] in a given zone. `jiff::TimeZone::system` falls back to a zone that behaves
/// like UTC when the host has none to read, and an instant outside the range it can represent
/// (far outside the range of a file date) keeps its UTC reading rather than failing an import.
#[cfg(not(target_arch = "wasm32"))]
fn civil_in(secs: i64, zone: &jiff::tz::TimeZone) -> String {
let offset = jiff::Timestamp::from_second(secs).map(|t| i64::from(zone.to_offset_info(t).offset().seconds())).unwrap_or(0);
civil(secs.saturating_add(offset))
}
#[cfg(target_arch = "wasm32")]
pub fn local_civil(secs: i64) -> String {
civil(secs)
}
/// The instant at which the host's zone reads `civil` (`YYYY-MM-DDTHH:MM:SS`): the inverse of
/// [`local_civil`]. Tests pin a file's modification time with it, so that an undated file takes
/// the local date they mean whatever zone the machine is in.
#[cfg(not(target_arch = "wasm32"))]
pub fn local_instant(civil: &str) -> Option<i64> {
instant_in(civil, &system_zone())
}
/// [`local_instant`] in a given zone. `None` when the text is not a civil date-time, or when the
/// zone has no such moment: an hour a spring-forward removes is not a time anything happened at,
/// and jiff's ordinary conversion would answer with the instant an hour later, which reads back as
/// a different time and so is not an inverse at all. An hour a fall-back repeats takes the first
/// of the two.
#[cfg(not(target_arch = "wasm32"))]
fn instant_in(civil: &str, zone: &jiff::tz::TimeZone) -> Option<i64> {
let when: jiff::civil::DateTime = civil.trim().parse().ok()?;
let ambiguous = zone.to_ambiguous_zoned(when);
match ambiguous.offset() {
jiff::tz::AmbiguousOffset::Gap { .. } => None,
_ => ambiguous.earlier().ok().map(|z| z.timestamp().as_second()),
}
}
#[cfg(target_arch = "wasm32")]
pub fn local_instant(civil: &str) -> Option<i64> {
lightcraft_catalog::dates::iso_seconds(civil)
}
// (the clock is the host's only natively: the web build's is UTC, and has no jiff)
#[cfg(all(test, not(target_arch = "wasm32")))]
mod clock_tests {
use super::*;
/// Issue #2284: an instant becomes the civil time the host's own zone shows for it, with the
/// offset in force *then*. The reported case is a JPEG with no capture date whose modification
/// time is 2026-10-18 20:15:11 in UTC-5: dated by `civil` it read 01:15 the next day.
#[test]
fn local_civil_reads_the_hosts_zone_at_that_instant() {
let zone = jiff::tz::TimeZone::system();
// the report, then one in each half of the year (so a zone with DST uses both offsets),
// one on a year boundary, and one before the epoch
for iso in ["2026-10-19T01:15:11Z", "2026-07-04T12:00:00Z", "2026-01-15T23:30:00Z", "2027-01-01T00:00:00Z", "1969-12-31T23:59:59Z"] {
let secs = lightcraft_meta::DateTime::parse_iso(iso).expect("a test timestamp").unix_seconds();
let zoned = jiff::Timestamp::from_second(secs).expect("in range").to_zoned(zone.clone());
assert_eq!(local_civil(secs), zoned.strftime("%Y-%m-%dT%H:%M:%S").to_string(), "{iso}");
}
}
/// The reported numbers, against a fixed UTC-5 zone, so they are checked on any host: a CI
/// runner set to UTC would make the test above agree with itself and prove nothing.
#[test]
fn an_evening_in_utc_minus_5_stays_that_evening() {
let secs = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").expect("a test timestamp").unix_seconds();
assert_eq!(civil(secs), "2026-10-19T01:15:11", "the UTC reading the file used to be dated by");
let zone = jiff::tz::TimeZone::fixed(jiff::tz::offset(-5));
assert_eq!(civil_in(secs, &zone), "2026-10-18T20:15:11");
// and the other way, so the sign cannot be read backwards
assert_eq!(civil_in(secs, &jiff::tz::TimeZone::fixed(jiff::tz::offset(2))), "2026-10-19T03:15:11");
}
/// `local_instant` undoes `local_civil`, so a fixture can pin a file to a local date.
#[test]
fn local_instant_is_the_inverse_of_local_civil() {
for iso in ["2026-01-14T05:58:48", "2026-07-04T12:00:00", "2026-10-18T20:15:11"] {
let secs = local_instant(iso).expect("a local instant");
assert_eq!(local_civil(secs), iso);
}
assert_eq!(local_instant("not a date"), None);
}
/// The hour a spring-forward removes is no instant at all, so there is nothing to answer with:
/// jiff's ordinary conversion returns the hour after the gap, which would pin a file to a time
/// it does not read back as. The hour a fall-back repeats takes the first of the two.
#[test]
fn a_local_time_a_spring_forward_removed_has_no_instant() {
let Ok(zone) = jiff::tz::TimeZone::get("America/New_York") else {
lightcraft_testkit::skip!(System, "no IANA time zone database to read America/New_York from");
return;
};
// 2026-03-08: 02:00 becomes 03:00, so nothing happened at 02:30
assert_eq!(instant_in("2026-03-08T02:30:00", &zone), None);
// the hours either side of the gap are ordinary, and round-trip
for iso in ["2026-03-08T01:30:00", "2026-03-08T03:30:00"] {
let secs = instant_in(iso, &zone).expect("either side of the gap");
assert_eq!(civil_in(secs, &zone), iso);
}
// 2026-11-01: 02:00 becomes 01:00, so 01:30 happens twice; the first is the one in summer
// time, 05:30 UTC, and it reads back as what was asked for
let fold = instant_in("2026-11-01T01:30:00", &zone).expect("the repeated hour");
assert_eq!(fold, lightcraft_meta::DateTime::parse_iso("2026-11-01T05:30:00Z").expect("a test timestamp").unix_seconds());
assert_eq!(civil_in(fold, &zone), "2026-11-01T01:30:00");
}
/// Whatever the host's zone, what it produces is a date the rest of the catalog can read back,
/// and it differs from UTC only by a whole number of minutes no larger than a real offset.
#[test]
fn local_civil_is_a_catalog_date_within_a_real_offset_of_utc() {
let secs = lightcraft_meta::DateTime::parse_iso("2026-10-19T01:15:11Z").expect("a test timestamp").unix_seconds();
let local = local_civil(secs);
let read = lightcraft_catalog::dates::iso_seconds(&local).expect("a date the catalog can read");
let shift = read - secs;
assert_eq!(shift % 60, 0, "{local}");
assert!(shift.abs() <= 18 * 3600, "{local}");
assert_eq!(lightcraft_catalog::dates::normalize_iso(&local).as_deref(), Some(local.as_str()));
}
}
+34 -3
View File
@@ -360,7 +360,9 @@ fn presets_json(s: &Session) -> String {
/// Finish a background compaction that is done (cheap otherwise). A failed one lost nothing (the
/// log is kept whole) and is retried later; it is reported like other persistence errors.
fn poll_compaction(lib: &mut Library) {
if let Err(e) = lib.journal.poll() {
let polled = lib.journal.poll();
note_upgrade_kept(lib);
if let Err(e) = polled {
log::error!("library: compaction: {e}");
lib.last_error = Some(format!("compaction: {e}"));
}
@@ -368,6 +370,16 @@ fn poll_compaction(lib: &mut Library) {
lib.log_held = lib.journal.unwritten();
}
/// A snapshot that upgraded a library left in an older format at open kept the files it was:
/// tell so once, like the open does ([`kept_note`]). Cheap when nothing was kept.
fn note_upgrade_kept(lib: &mut Library) {
let kept = lib.journal.take_kept();
if let Some(note) = kept_note(&kept, None) {
lib.settings_warnings.push(note);
lib.report.kept.extend(kept);
}
}
/// How long the frame loop waits before retrying a failed append (commands retry at once).
const RETRY_BACKOFF: std::time::Duration = std::time::Duration::from_secs(2);
@@ -411,6 +423,20 @@ struct SettingsLoad {
blocked: Vec<&'static str>,
}
/// What to tell the person when opening the library upgraded it: the files it was are kept
/// beside it (as large as it was), and are theirs to delete.
fn kept_note(kept: &[String], damaged: Option<&String>) -> Option<String> {
if kept.is_empty() && damaged.is_none() {
return None;
}
// (a library whose log was damaged: that log is the other half of what it was)
let kept: Vec<&str> = kept.iter().chain(damaged).map(String::as_str).collect();
Some(format!(
"This library was upgraded for this version of LightCraft, and earlier versions can't open it now. The library as it was is kept beside it as {}: delete it once the earlier version is no longer wanted (docs/catalog-persistence.md, \"Going back to an older version\").",
kept.join(" and ")
))
}
impl SettingsLoad {
fn read<T: serde::de::DeserializeOwned>(&mut self, store: &mut dyn Store, name: &'static str) -> Option<T> {
let bytes = match store.read(name) {
@@ -726,6 +752,8 @@ impl Session {
self.tidy_thumbnail_cache();
}
let view_written = self.view_json();
// (a damaged log is only part of "what the library was" when opening upgraded it, and the store keeps what an upgrade replaces: a library in this format that lost its log's tail was not upgraded, and the browser's store keeps no snapshot for the log to go with)
let kept = kept_note(&report.kept, report.damaged.as_ref().filter(|_| report.upgraded_from.is_some() && report.kept_files));
self.library = Some(Library {
dir,
on_disk,
@@ -740,7 +768,7 @@ impl Session {
forgot_local: None,
presets_saved,
view_written,
settings_warnings: unlocked_warning(lock.as_ref()).into_iter().chain(settings.warnings).collect(),
settings_warnings: unlocked_warning(lock.as_ref()).into_iter().chain(kept).chain(settings.warnings).collect(),
warnings_reported: 0,
blocked: settings.blocked,
folder,
@@ -1124,6 +1152,7 @@ impl Session {
log::error!("library: compaction: {e}");
lib.last_error = Some(format!("compaction: {e}"));
}
note_upgrade_kept(lib);
}
/// Compact the log into a snapshot now.
@@ -1133,7 +1162,9 @@ impl Session {
return Err(EngineError::Other("can't compact during an interaction".into()));
}
if let Some(lib) = self.library.as_mut() {
lib.journal.snapshot(&self.catalog)?;
let snapshot = lib.journal.snapshot(&self.catalog);
note_upgrade_kept(lib);
snapshot?;
}
Ok(())
}
+9 -3
View File
@@ -20,6 +20,9 @@ fn temp_dir(tag: &str) -> std::path::PathBuf {
d
}
/// The clock these tests run on; an undated file is pinned to it too (see `write_png`).
const CLOCK: &str = "2026-01-14T05:58:48";
/// A small procedural PNG (distinct per seed).
fn write_png(path: &Path, seed: u8) {
let (w, h) = (48usize, 32usize);
@@ -28,8 +31,10 @@ fn write_png(path: &Path, seed: u8) {
let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, bytes).unwrap();
// undated files take the file's date: the tests' clock time (2026-01-14T05:58:48)
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328);
// Undated files take the file's date, read in the host's zone (issue #2284), so the file is
// pinned to the instant this machine reads as the tests' clock time rather than to a fixed one.
let secs = crate::import::local_instant(CLOCK).and_then(|s| u64::try_from(s).ok()).unwrap_or(0);
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap();
}
@@ -57,7 +62,8 @@ fn write_png_with_metadata(path: &Path, seed: u8, exif: Option<&[u8]>, xmp: Opti
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, bytes).unwrap();
// Keep the same known file-date fallback as write_png, distinct from the regression timestamp.
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328);
let secs = crate::import::local_instant(CLOCK).and_then(|s| u64::try_from(s).ok()).unwrap_or(0);
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap();
}
+7 -2
View File
@@ -15,6 +15,9 @@ fn temp_dir(tag: &str) -> PathBuf {
d
}
/// The clock these tests run on; an undated file is pinned to it too (see `write_png`).
const CLOCK: &str = "2026-01-14T05:58:48";
pub(super) fn write_png(path: &Path, seed: u8) {
let (w, h) = (40usize, 24usize);
let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 5) as u8, (i / w * 7) as u8, seed, 255]).collect();
@@ -22,8 +25,10 @@ pub(super) fn write_png(path: &Path, seed: u8) {
let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, bytes).unwrap();
// undated files take the file's date: the tests' clock time (2026-01-14T05:58:48)
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_768_370_328);
// Undated files take the file's date, read in the host's zone (issue #2284), so the file is
// pinned to the instant this machine reads as the tests' clock time rather than to a fixed one.
let secs = crate::import::local_instant(CLOCK).and_then(|s| u64::try_from(s).ok()).unwrap_or(0);
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
std::fs::File::options().write(true).open(path).unwrap().set_modified(t).unwrap();
}
+196
View File
@@ -217,6 +217,202 @@ fn a_preset_that_cannot_be_written_counts_as_unsaved_until_it_is() {
assert!(String::from_utf8_lossy(&stored(&files)).contains("Mine"));
}
/// Given a library saved by an earlier version, when it is opened, then the person is told once
/// that it was upgraded and where the library as it was is kept (the files are theirs to
/// delete), and `library.info` lists it; a library that was not upgraded says nothing.
#[test]
fn an_upgraded_library_says_where_what_it_was_is_kept() {
let dir = std::env::temp_dir().join(format!("lightcraft-kept-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("catalog.snap"), include_str!("../../../catalog/src/fixtures/v6-catalog.snap.json")).unwrap();
std::fs::write(dir.join("catalog.log"), include_str!("../../../catalog/src/fixtures/v6-catalog.log.jsonl")).unwrap();
let mut s = Session::new();
s.open_library(&dir, false).unwrap();
let told = s.take_library_warnings();
assert!(told.iter().any(|w| w.contains("catalog.snap.v6-8") && w.contains("catalog.log.v6-8") && w.contains("delete")), "{told:?}");
assert!(dir.join("catalog.snap.v6-8").exists() && dir.join("catalog.log.v6-8").exists());
let info = s.execute("library.info", &serde_json::json!({})).unwrap();
assert!(info["settingsWarnings"].to_string().contains("catalog.snap.v6-8"), "{info}");
s.close_library().unwrap();
s.open_library(&dir, false).unwrap();
assert!(!s.take_library_warnings().iter().any(|w| w.contains("upgraded")));
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// The v6 fixture's log with its second record replaced by garbage (a record after it is still good, so it is damage, not a torn tail).
fn damaged_v6_log() -> String {
let log = include_str!("../../../catalog/src/fixtures/v6-catalog.log.jsonl");
log.lines().enumerate().map(|(i, l)| if i == 1 { "not a record" } else { l }).collect::<Vec<_>>().join("\n") + "\n"
}
/// Given a library from an earlier version that has only a damaged log, when it is opened and upgraded, then the person is told
/// where the damaged log is kept (there is no kept snapshot to name it beside).
#[test]
fn an_upgraded_library_with_only_a_damaged_log_says_where_the_log_is_kept() {
let dir = std::env::temp_dir().join(format!("lightcraft-kept-dmg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("catalog.log"), damaged_v6_log()).unwrap();
let mut s = Session::new();
s.open_library(&dir, false).unwrap();
let told = s.take_library_warnings();
assert!(told.iter().any(|w| w.contains("upgraded") && w.contains("catalog.log.damaged-")), "{told:?}");
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// A library already in this version's format whose log was damaged was not upgraded: it is not told it was.
#[test]
fn a_current_library_with_a_damaged_log_is_not_told_it_was_upgraded() {
let dir = std::env::temp_dir().join(format!("lightcraft-cur-dmg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut s = Session::new();
s.open_library(&dir, true).unwrap();
s.execute("photo.rate", &serde_json::json!({"rating": 3})).unwrap();
s.execute("photo.rate", &serde_json::json!({"rating": 4})).unwrap();
s.execute("photo.rate", &serde_json::json!({"rating": 5})).unwrap();
drop(s);
let log = std::fs::read_to_string(dir.join("catalog.log")).unwrap();
let broken: Vec<&str> = log.lines().enumerate().map(|(i, l)| if i == 1 { "not a record" } else { l }).collect();
std::fs::write(dir.join("catalog.log"), broken.join("\n") + "\n").unwrap();
let mut s = Session::new();
let damaged = s.open_library(&dir, false).unwrap().damaged.clone();
assert!(damaged.is_some_and(|name| dir.join(name).exists()), "the log was found damaged and kept");
let told = s.take_library_warnings();
assert!(!told.iter().any(|w| w.contains("upgraded")), "{told:?}");
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// The browser's storage: it keeps no copy of a library an upgrade replaces.
struct KeepsNothing(MemStore);
impl Store for KeepsNothing {
fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
self.0.read(name)
}
fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.0.write_atomic(name, data)
}
fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
self.0.append(name, data)
}
fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> {
self.0.truncate(name, len)
}
fn keeps_replaced_formats(&self) -> bool {
false
}
fn describe(&self) -> String {
"keeps nothing".into()
}
}
/// Given a store that keeps no replaced files (the browser's) and an older library with a damaged log, when it is opened and
/// upgraded, then the damaged log set aside is not presented as "the library as it was": there is no snapshot to go with it.
#[test]
fn a_store_that_keeps_no_files_does_not_tell_of_a_kept_damaged_log() {
let m = MemStore::new();
m.set("catalog.snap", include_bytes!("../../../catalog/src/fixtures/v6-catalog.snap.json").to_vec());
m.set("catalog.log", damaged_v6_log().into_bytes());
let mut s = Session::new();
let stores =
LibraryStores { dir: "browser".into(), catalog: Box::new(KeepsNothing(m.clone())), files: Box::new(MemStore::new()), on_disk: false };
let report = s.open_library_in(stores, false).unwrap();
assert!(report.damaged.is_some() && report.upgraded_from == Some(6), "the log was found damaged and the library upgraded: {report:?}");
let told = s.take_library_warnings();
assert!(!told.iter().any(|w| w.contains("upgraded") || w.contains("catalog.log.damaged-")), "{told:?}");
}
/// The same library on a store that does keep files, with no snapshot (only the damaged log): the person is told where the log is kept.
#[test]
fn a_store_that_keeps_files_tells_of_a_kept_damaged_log() {
let m = MemStore::new();
m.set("catalog.log", damaged_v6_log().into_bytes());
let mut s = Session::new();
let stores = LibraryStores { dir: "kept".into(), catalog: Box::new(m.clone()), files: Box::new(MemStore::new()), on_disk: false };
s.open_library_in(stores, false).unwrap();
let told = s.take_library_warnings();
assert!(told.iter().any(|w| w.contains("upgraded") && w.contains("catalog.log.damaged-")), "{told:?}");
}
/// An older library (format 6) that could not keep its files at open: a directory sits where the
/// first kept file goes.
fn library_that_could_not_keep_its_files(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("lightcraft-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("catalog.snap.v6-8")).unwrap();
std::fs::write(dir.join("catalog.snap.v6-8").join("in the way"), b"x").unwrap();
std::fs::write(dir.join("catalog.snap"), include_str!("../../../catalog/src/fixtures/v6-catalog.snap.json")).unwrap();
std::fs::write(dir.join("catalog.log"), include_str!("../../../catalog/src/fixtures/v6-catalog.log.jsonl")).unwrap();
dir
}
/// The names of the files kept for format 6 in `dir`.
fn kept_for_v6(dir: &std::path::Path, prefix: &str) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap())
.filter(|e| e.path().is_file())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with(prefix))
.collect();
names.sort();
names
}
/// Given an older library that could not keep its files at open, when a later compaction upgrades
/// it (the files can be kept now), then the person is told once where the library as it was is
/// kept, as when the open upgrades it, and a later compaction tells nothing more.
#[test]
fn a_later_upgrade_says_where_what_it_was_is_kept() {
let dir = library_that_could_not_keep_its_files("kept-later");
let mut s = Session::new();
s.open_library(&dir, false).unwrap();
assert!(s.take_library_warnings().iter().all(|w| !w.contains("upgraded")), "not upgraded at open");
assert!(s.compact_library().is_err(), "its files can't be kept yet");
std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap();
s.compact_library().unwrap();
let (snap, log) = (kept_for_v6(&dir, "catalog.snap.v6-"), kept_for_v6(&dir, "catalog.log.v6-"));
assert_eq!((snap.len(), log.len()), (1, 1), "the files as they were are kept");
let told = s.take_library_warnings();
assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0]) && w.contains("delete")), "{told:?}");
let info = s.execute("library.info", &serde_json::json!({})).unwrap();
assert!(info["settingsWarnings"].to_string().contains(&snap[0]), "{info}");
s.compact_library().unwrap();
assert!(s.take_library_warnings().is_empty(), "told once");
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// The same, when the compaction is written by the background worker: the person is told once its
/// result is taken (the frame loop's `persist`), not before.
#[test]
fn a_background_upgrade_says_where_what_it_was_is_kept() {
let dir = library_that_could_not_keep_its_files("kept-background");
let mut s = Session::new();
s.open_library(&dir, false).unwrap();
let _ = s.take_library_warnings();
std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap();
s.compact_soon();
let started = std::time::Instant::now();
let mut told = Vec::new();
while told.is_empty() && started.elapsed() < std::time::Duration::from_secs(30) {
std::thread::sleep(std::time::Duration::from_millis(10));
s.persist().unwrap();
told = s.take_library_warnings();
}
let (snap, log) = (kept_for_v6(&dir, "catalog.snap.v6-"), kept_for_v6(&dir, "catalog.log.v6-"));
assert_eq!((snap.len(), log.len()), (1, 1));
assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0])), "{told:?}");
s.persist().unwrap();
assert!(s.take_library_warnings().is_empty(), "told once");
s.close_library().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// A batch that fails and whose rollback then fails halfway leaves the catalog changed. The change must reach the
/// journal (a restart finds what the session had) and the person must be able to take it back.
#[test]
+116 -7
View File
@@ -51,12 +51,18 @@ const MAX_REDIRECTS: usize = 8;
/// The mirrors to try, in order: `env`'s (base URLs separated by commas, spaces or newlines), then
/// the mirrors file's (one base URL per line, `#` comments), then `defaults`; duplicates and
/// unusable URLs dropped, at most 16.
/// unusable URLs dropped, at most 16. A mirror can be `http(s)://`, `file://<absolute path>` or an
/// absolute folder path: files from a local folder are copied (then checked like a download).
pub fn mirrors(env: Option<&str>, file: Option<&Path>, defaults: &[&str]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut add = |s: &str| {
let s = s.trim().trim_end_matches('/');
if !s.is_empty() && Url::parse(s).is_ok() && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS {
let s = s.trim();
// a local folder (an absolute path) is the same as its `file://` URL
let s = if Path::new(s).is_absolute() { format!("file://{}", s.replace('%', "%25")) } else { s.to_string() };
let s = keep_root(s.trim_end_matches('/'));
let s = s.as_str();
let usable = local_path(s).is_some() || Url::parse(s).is_ok();
if !s.is_empty() && usable && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS {
out.push(s.to_string());
}
};
@@ -197,13 +203,13 @@ fn download_source(
let mut errors = Vec::new();
let mut ok = false;
'mirrors: for m in mirrors {
let url = if exact_urls { m.clone() } else { format!("{m}/{}", f.name) };
let url = if exact_urls { m.clone() } else { file_url_in(m, f.name) };
for _ in 0..opts.attempts.clamp(1, 16) {
if cancel.load(Ordering::Relaxed) {
return Err(DownloadError::Cancelled);
}
let mut report = |n: u64, announced: u64| {
let mirror = Url::parse(m).map(|u| u.display()).unwrap_or_default();
let mirror = short(m);
progress(&Progress {
file: f.name.to_string(),
done: before.saturating_add(n),
@@ -284,6 +290,9 @@ fn bearer<'a>(token: Option<&'a str>, url: &Url, origin: &str) -> Option<&'a str
/// A mirror for messages (no query string: it may hold a token).
fn short(m: &str) -> String {
if local_path(m).is_some() {
return m.to_string();
}
Url::parse(m).map(|u| u.display()).unwrap_or_else(|_| "mirror".into())
}
@@ -345,8 +354,11 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: &
}
Err(_) => 0,
};
let fetched = f.size != Some(have) || have == 0;
if fetched {
let local = local_path(url);
let fetched = local.is_some() || f.size != Some(have) || have == 0;
if let Some(src) = local {
copy_local(&src, &part, limit, f.size, cancel, report)?;
} else if fetched {
let limits = Limits { connect: opts.connect_timeout, stall: opts.stall_timeout, cancel };
let mut url = Url::parse(url).map_err(|e| Fail::NextMirror(e.to_string()))?;
let origin = url.host.clone();
@@ -455,6 +467,103 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: &
Ok(())
}
/// The local path of a `file://` URL (absolute only; `file:///C:/x` → `C:/x` on Windows).
/// A mirror with its trailing separators taken off, except a filesystem root's: `file:///` and `file:///D:/` stay
/// as they are (without it neither is an absolute path).
fn keep_root(s: &str) -> String {
match s {
"file:" => "file:///".to_string(),
s if s.starts_with("file://") && s.ends_with(':') => format!("{s}/"),
s => s.to_string(),
}
}
/// The URL of file `name` on mirror `m`: one separator between them (a root mirror already ends with one), and on a
/// local mirror the name's own `%` escaped, so the decoded path is that very name.
fn file_url_in(m: &str, name: &str) -> String {
let name = if local_path(m).is_some() { name.replace('%', "%25") } else { name.to_string() };
if m.ends_with('/') { format!("{m}{name}") } else { format!("{m}/{name}") }
}
fn local_path(url: &str) -> Option<PathBuf> {
let rest = url.strip_prefix("file://")?;
let rest = if rest.get(2..3) == Some(":") { rest.strip_prefix('/').unwrap_or(rest) } else { rest };
let rest = percent_decode(rest)?;
let p = PathBuf::from(&rest);
if p.is_absolute() && !rest.chars().any(char::is_control) { Some(p) } else { None }
}
/// Decode `%XX` escapes (a `file://` URL's path); `None` for a broken escape or non-UTF-8 result.
fn percent_decode(s: &str) -> Option<String> {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while let Some(&c) = b.get(i) {
if c == b'%' {
let hex = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else {
out.push(c);
i += 1;
}
}
String::from_utf8(out).ok()
}
/// Copy a file from a local mirror into `part` (from the start; it is checked afterwards like a download).
fn copy_local(src: &Path, part: &Path, limit: u64, size: Option<u64>, cancel: &AtomicBool, report: &mut dyn FnMut(u64, u64)) -> Result<(), Fail> {
let disk = |e: std::io::Error| Fail::Disk(format!("{}: {e}", part.display()));
let meta = std::fs::metadata(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?;
if !meta.is_file() {
return Err(Fail::NextMirror(format!("{} is not a file", src.display())));
}
if meta.len() > limit || size.is_some_and(|s| s != meta.len()) {
return Err(Fail::NextMirror(format!("{} has the wrong size ({} bytes)", src.display(), meta.len())));
}
let mut input = File::open(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?;
// (a fresh file: an old one at that name may be a hard link to the source, which truncating would empty)
let mut out = new_part(part).map_err(disk)?;
let announced = size.unwrap_or(meta.len());
let mut have = 0u64;
report(0, announced);
let mut buf = vec![0u8; 1 << 20];
loop {
if cancel.load(Ordering::Relaxed) {
drop(out);
let _ = std::fs::remove_file(part);
return Err(Fail::Cancelled);
}
let n = match input.read(&mut buf) {
Ok(n) => n,
Err(e) => {
drop(out);
let _ = std::fs::remove_file(part);
return Err(Fail::NextMirror(format!("{}: {e}", src.display())));
}
};
if n == 0 {
break;
}
if have.saturating_add(n as u64) > limit {
drop(out);
let _ = std::fs::remove_file(part);
return Err(Fail::NextMirror(format!("{} grew past the expected {limit} bytes", src.display())));
}
out.write_all(buf.get(..n).unwrap_or_default()).map_err(disk)?;
have = have.saturating_add(n as u64);
report(have, announced);
}
// a source rewritten (or cut short) after its size was read: what was copied is not that file, and a partial
// left behind would be resumed by the next mirror, failing its hash; so it goes, and the next mirror starts over
if have != announced {
drop(out);
let _ = std::fs::remove_file(part);
return Err(Fail::NextMirror(format!("{} changed while it was copied ({have} of {announced} bytes)", src.display())));
}
out.sync_all().map_err(disk)
}
fn http_fail(e: HttpError) -> Fail {
match e {
HttpError::Cancelled => Fail::Cancelled,
+125
View File
@@ -426,6 +426,131 @@ fn hostile_file_specs_are_rejected_before_touching_disk() {
}
}
#[test]
fn copies_from_a_local_folder_mirror_and_checks_the_hash() {
let src = tmp("local-src");
let dst = tmp("local-dst");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("model.bin"), payload()).unwrap();
// a bare absolute path and a file:// URL are both mirrors (passed as a default, which is not split on spaces
// or commas the way the environment's list is: the temp folder may hold either)
let m = mirrors(None, None, &[src.to_str().unwrap()]);
assert_eq!(m, vec![file_url(&src)]);
let (r, prog) = run(&[pinned()], &m, &dst, &AtomicBool::new(false));
r.unwrap();
assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload());
assert!(prog.last().is_some_and(|p| p.done == p.total));
// a damaged local copy is rejected and never moved into place
let bad = tmp("local-bad");
std::fs::create_dir_all(&bad).unwrap();
let mut damaged = payload();
damaged[7] ^= 1;
std::fs::write(bad.join("model.bin"), damaged).unwrap();
let dst2 = tmp("local-dst2");
let (r, _) = run(&[pinned()], &[file_url(&bad)], &dst2, &AtomicBool::new(false));
assert!(matches!(r, Err(DownloadError::AllMirrorsFailed { .. })), "{r:?}");
assert!(!dst2.join("model.bin").exists() && !dst2.join("model.bin.part").exists());
// a missing folder, a relative path and a directory in place of a file are errors, not panics
let (r, _) = run(&[pinned()], &["file:///nonexistent/model-mirror".to_string()], &dst2, &AtomicBool::new(false));
assert!(r.is_err());
assert!(mirrors(Some("file://relative/dir"), None, &[]).is_empty());
std::fs::create_dir_all(src.join("dir.bin")).unwrap();
let dir_spec = FileSpec { name: "dir.bin", size: None, sha256: None, max: 10 };
let (r, _) = run(&[dir_spec], &[file_url(&src)], &dst2, &AtomicBool::new(false));
assert!(r.is_err());
for d in [&src, &dst, &bad, &dst2] {
let _ = std::fs::remove_dir_all(d);
}
}
/// The `file://` URL of a local folder (its own `%` escaped, as [`mirrors`] does: the temp folder may hold one).
fn file_url(p: &Path) -> String {
format!("file://{}", p.display().to_string().replace('%', "%25"))
}
/// A filesystem root is a usable mirror, and a file in it is found under one separator (CodeRabbit on #3010).
#[test]
fn a_root_folder_mirror_keeps_its_separator() {
assert_eq!(keep_root("file:"), "file:///");
assert_eq!(keep_root("file:///D:"), "file:///D:/");
assert_eq!(keep_root("file:///models"), "file:///models");
assert_eq!(file_url_in("file:///", "model.bin"), "file:///model.bin");
#[cfg(unix)]
{
assert_eq!(mirrors(None, None, &["/"]), ["file:///"]);
assert_eq!(local_path("file:///model.bin"), Some(PathBuf::from("/model.bin")));
}
}
/// A file name with a literal `%20` in it is copied from a local mirror under that very name, not as a space
/// (CodeRabbit on #3010).
#[test]
fn a_local_mirror_keeps_a_file_names_percent_signs() {
let src = tmp("local-percent-src");
let dst = tmp("local-percent-dst");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("model%20.bin"), payload()).unwrap();
let p = payload();
let spec = FileSpec { name: "model%20.bin", size: Some(p.len() as u64), sha256: Some(leak(sha_hex(&p))), max: p.len() as u64 };
let (r, _) = run(&[spec], &[file_url(&src)], &dst, &AtomicBool::new(false));
r.unwrap();
assert_eq!(std::fs::read(dst.join("model%20.bin")).unwrap(), payload());
for d in [&src, &dst] {
let _ = std::fs::remove_dir_all(d);
}
}
/// A leftover `.part` that is a hard link to the local mirror's file is replaced, never truncated through: the
/// mirror's file keeps its bytes (CodeRabbit on #3010).
#[cfg(unix)]
#[test]
fn a_hard_linked_part_never_empties_the_local_source() {
let src = tmp("local-link-src");
let dst = tmp("local-link-dst");
std::fs::create_dir_all(&src).unwrap();
std::fs::create_dir_all(&dst).unwrap();
std::fs::write(src.join("model.bin"), payload()).unwrap();
std::fs::hard_link(src.join("model.bin"), dst.join("model.bin.part")).unwrap();
let (r, _) = run(&[pinned()], &[file_url(&src)], &dst, &AtomicBool::new(false));
r.unwrap();
assert_eq!(std::fs::read(src.join("model.bin")).unwrap(), payload(), "the mirror's file is untouched");
assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload());
for d in [&src, &dst] {
let _ = std::fs::remove_dir_all(d);
}
}
/// A local source whose length on reading differs from the one its metadata gave (here a /proc file, whose size
/// reads as 0: as a file rewritten after its size was checked) is not kept as a partial for the next mirror to
/// resume (CodeRabbit on #3010).
#[cfg(target_os = "linux")]
#[test]
fn a_local_copy_that_comes_out_another_length_leaves_no_partial() {
let dst = tmp("local-changed-dst");
std::fs::create_dir_all(&dst).unwrap();
let part = dst.join("status.part");
let r = copy_local(Path::new("/proc/self/status"), &part, 1 << 20, None, &AtomicBool::new(false), &mut |_, _| {});
assert!(matches!(r, Err(Fail::NextMirror(_))), "the next mirror is tried");
assert!(!part.exists(), "the partial is removed");
let _ = std::fs::remove_dir_all(&dst);
}
#[test]
fn file_urls_are_percent_decoded_but_bare_paths_keep_their_percent_signs() {
// (absolute on every platform: `/models/…` has no drive on Windows, where it is not an absolute path)
let percent = std::env::temp_dir().join("50%20off");
let bare = mirrors(None, None, &[percent.to_str().unwrap()]);
assert_eq!(bare.len(), 1);
assert_eq!(local_path(&bare[0]), Some(percent));
let spaced = std::env::temp_dir().join("my sam3");
assert_eq!(local_path(&format!("file://{}", spaced.to_str().unwrap().replace('%', "%25").replace(' ', "%20"))), Some(spaced));
for hostile in ["file:///x%", "file:///x%2", "file:///x%zz", "file:///x%ff", "file:///x%0a"] {
assert_eq!(local_path(hostile), None, "{hostile}");
}
}
#[test]
fn names_differing_only_in_case_are_one_file() {
let spec = |name| FileSpec { name, size: Some(1), sha256: None, max: 1 };
+14 -7
View File
@@ -11,14 +11,21 @@ use std::path::Path;
/// The `facebook/sam3` checkpoint files [`crate::Sam3::load`] needs.
///
/// `model.safetensors` is pinned to the official checkpoint (Hugging Face LFS SHA-256). The two
/// tokenizer files are small text files without a pinned hash yet: they are only parsed by the
/// tokenizer (never executed) and capped in size.
// TODO(maintainer): pin `vocab.json` and `merges.txt` (size + SHA-256) when the files are
// uploaded to LightCraft's CDN.
/// All three are pinned (exact size + SHA-256) to the official `facebook/sam3` checkpoint files,
/// checked against a copy of them on 2026-10-13.
pub const SAM3_FILES: &[FileSpec] = &[
FileSpec { name: "vocab.json", size: None, sha256: None, max: 4 << 20 },
FileSpec { name: "merges.txt", size: None, sha256: None, max: 4 << 20 },
FileSpec {
name: "vocab.json",
size: Some(862_328),
sha256: Some("5047b556ce86ccaf6aa22b3ffccfc52d391ea4accdab9c2f2407da5b742d4363"),
max: 4 << 20,
},
FileSpec {
name: "merges.txt",
size: Some(524_619),
sha256: Some("9fd691f7c8039210e0fced15865466c65820d09b63988b0174bfe25de299051a"),
max: 4 << 20,
},
FileSpec {
name: crate::WEIGHTS_FILE,
size: Some(SAM3_WEIGHTS_SIZE),
+6
View File
@@ -278,6 +278,7 @@
"Before/After (Y)": "Před/Po (Y)",
"Before/After Settings": "Nastavení Před/Po",
"Before/After Split": "Rozdělené Před/Po",
"Before/After": "Před/Po",
"Before/After Split Top/Bottom": "Rozdělené Před/Po nahoře/dole",
"Before/After Top/Bottom": "Před/Po nahoře/dole",
"Begin Interaction": "Zahájit interakci",
@@ -508,6 +509,7 @@
"Cut": "Vyjmout",
"Cut pages": "Vyjmout stránky",
"Cycle Crop Overlay": "Přepnout překrytí ořezu",
"Crop Overlay": "Překrytí ořezu",
"Cycle Crop Overlay Orientation": "Přepnout orientaci překrytí ořezu",
"Cycle Info Overlay": "Přepnout překrytí informací",
"Cycle Mask Overlay Color": "Přepnout barvu překrytí masky",
@@ -2068,6 +2070,7 @@
"XMP sidecars": "Přidružené soubory XMP",
"Year": "Rok",
"Yellow": "Žlutá",
"White": "Bílá",
"Yellow Hue": "Odstín žluté",
"Yellow Luminance": "Jas žluté",
"Yellow Saturation": "Sytost žluté",
@@ -2452,6 +2455,9 @@
"The photos are imported once it ends": "Fotky se naimportují potom",
"An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí",
"Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky",
"Loupe Overlay": "Překrytí lupy",
"View Options…": "Možnosti zobrazení…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Zobrazení → Překrytí lupy → Možnosti zobrazení určuje, které řádky zobrazují Info 1 a Info 2.",
"Profile: from the file (the camera's own correction)": "Profil: ze souboru (vlastní korekce fotoaparátu)",
"Downloading the lens database…": "Stahuje se databáze objektivů…",
"This file names no lens.": "Tento soubor neuvádí žádný objektiv.",
+5
View File
@@ -158,6 +158,7 @@
"Before/After (Y)": "Vorher/Nachher (Y)",
"Before/After Settings": "Vorher/Nachher-Einstellungen",
"Before/After Split": "Vorher/Nachher geteilt",
"Before/After": "Vorher/Nachher",
"Before/After Split Top/Bottom": "Vorher/Nachher geteilt – oben/unten",
"Before/After Top/Bottom": "Vorher/Nachher – oben/unten",
"Begin Interaction": "Interaktion beginnen",
@@ -372,6 +373,7 @@
"Cut": "Ausschneiden",
"Cut pages": "Seiten ausschneiden",
"Cycle Crop Overlay": "Zuschnittüberlagerung wechseln",
"Crop Overlay": "Zuschnittüberlagerung",
"Cycle Crop Overlay Orientation": "Ausrichtung der Zuschnittüberlagerung wechseln",
"Cycle Info Overlay": "Infoüberlagerung wechseln",
"Cycle Mask Overlay Color": "Farbe der Maskenüberlagerung wechseln",
@@ -1673,6 +1675,7 @@
"XMP sidecars": "XMP-Begleitdateien",
"Year": "Jahr",
"Yellow": "Gelb",
"White": "Weiß",
"Yellow Hue": "Gelb – Farbton",
"Yellow Luminance": "Gelb – Luminanz",
"Yellow Saturation": "Gelb – Sättigung",
@@ -3508,6 +3511,8 @@
"The photos are imported once it ends": "Die Fotos werden danach importiert",
"An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist",
"Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst",
"View Options…": "Ansichtsoptionen…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Ansicht → Lupenüberlagerung → Ansichtsoptionen legt fest, welche Zeilen Info 1 und Info 2 zeigen.",
"Camera preview": "Kameravorschau",
"The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Das eigene JPEG der Kamera, angezeigt, bis LightCraft die Raw-Datei gerendert hat. Farbe und Tonwerte am gerenderten Foto beurteilen.",
"Profile: from the file (the camera's own correction)": "Profil: aus der Datei (Korrektur der Kamera)",
+6
View File
@@ -141,6 +141,7 @@
"Before/After (Y)": "Antes/Después (Y)",
"Before/After Settings": "Ajustes de Antes/Después",
"Before/After Split": "Antes/Después dividido",
"Before/After": "Antes/Después",
"Before/After Split Top/Bottom": "Antes/Después dividido arriba/abajo",
"Before/After Top/Bottom": "Antes/Después arriba/abajo",
"Begin Interaction": "Iniciar interacción",
@@ -361,6 +362,7 @@
"Cut": "Cortar",
"Cut pages": "Cortar páginas",
"Cycle Crop Overlay": "Alternar superposición de recorte",
"Crop Overlay": "Superposición de recorte",
"Cycle Crop Overlay Orientation": "Alternar orientación de la superposición de recorte",
"Cycle Info Overlay": "Alternar superposición de información",
"Cycle Mask Overlay Color": "Alternar color de superposición de máscara",
@@ -1779,6 +1781,7 @@
"XMP sidecars": "Archivos XMP complementarios",
"Year": "Año",
"Yellow": "Amarillo",
"White": "Blanco",
"Yellow Hue": "Tono amarillo",
"Yellow Luminance": "Luminancia amarilla",
"Yellow Saturation": "Saturación amarilla",
@@ -2403,6 +2406,9 @@
"The photos are imported once it ends": "Las fotos se importarán después",
"An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine",
"Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos",
"Loupe Overlay": "Superposición de la lupa",
"View Options…": "Opciones de vista…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Vista → Superposición de la lupa → Opciones de vista elige las líneas que muestran Info 1 e Info 2.",
"Camera preview": "Vista previa de la cámara",
"The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "El JPEG propio de la cámara, mostrado hasta que LightCraft haya renderizado el RAW. Juzga el color y el tono en la foto renderizada.",
"Profile: from the file (the camera's own correction)": "Perfil: del archivo (corrección de la propia cámara)",
+6
View File
@@ -189,6 +189,7 @@
"Basic": "Perus",
"Before": "Ennen",
"Before the last template": "Ennen viimeistä mallipohjaa",
"Before/After": "Ennen/jälkeen",
"Before/After (Y)": "Ennen/jälkeen (Y)",
"Before/After Settings": "Ennen/jälkeen-asetukset",
"Before/After Split": "Ennen/jälkeen jaettuna",
@@ -440,6 +441,7 @@
"Crop & Rotate": "Rajaa ja kierrä",
"Crop & Rotate (C)": "Rajaa ja kierrä (C)",
"Crop Aspect": "Rajauksen kuvasuhde",
"Crop Overlay": "Rajauksen peittokuva",
"Crop, Rotate, Geometry": "Rajaus, kierto, geometria",
"Cropped": "Rajattu",
"Cross Process": "Ristiinkäsittely",
@@ -2193,6 +2195,7 @@
"Wednesday": "keskiviikko",
"What's New": "Mitä uutta",
"When pins show on the photo (Shift+H cycles)": "Milloin nastat näkyvät kuvassa (Shift+H vaihtaa)",
"White": "Valkoinen",
"White Balance": "Valkotasapaino",
"White Balance Selector": "Valkotasapainon valitsin",
"White Balance Selector (W)": "Valkotasapainon valitsin (W)",
@@ -2390,6 +2393,9 @@
"Dropped Files": "Pudotetut tiedostot",
"Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä",
"Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta",
"Loupe Overlay": "Luupin peittokuva",
"View Options…": "Näyttöasetukset…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Näytä → Luupin peittokuva → Näyttöasetukset valitsee rivit, jotka Info 1 ja Info 2 näyttävät.",
"Lens Profiles": "Objektiiviprofiilit",
"Download lens profiles?": "Ladataanko objektiiviprofiilit?",
"LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft voi korjata monien objektiivien vääristymän ja vinjetoinnin avoimen objektiivitietokannan avulla (lensfun, noin {size} Mt).",
+4
View File
@@ -140,6 +140,7 @@
"Before/After (Y)": "Avant/Après (Y)",
"Before/After Settings": "Réglages Avant/Après",
"Before/After Split": "Avant/Après divisé",
"Before/After": "Avant/Après",
"Before/After Split Top/Bottom": "Avant/Après divisé haut/bas",
"Before/After Top/Bottom": "Avant/Après haut/bas",
"Begin Interaction": "Commencer l'interaction",
@@ -345,6 +346,7 @@
"Cut": "Couper",
"Cut pages": "Couper les pages",
"Cycle Crop Overlay": "Parcourir les incrustations de recadrage",
"Crop Overlay": "Incrustation de recadrage",
"Cycle Crop Overlay Orientation": "Parcourir les orientations de l'incrustation de recadrage",
"Cycle Info Overlay": "Parcourir les incrustations d'informations",
"Cycle Mask Overlay Color": "Parcourir les couleurs de l'incrustation du masque",
@@ -1599,6 +1601,7 @@
"XMP sidecars": "Fichiers annexes XMP",
"Year": "Année",
"Yellow": "Jaune",
"White": "Blanc",
"Yellow Hue": "Teinte jaune",
"Yellow Luminance": "Luminance jaune",
"Yellow Saturation": "Saturation jaune",
@@ -2706,6 +2709,7 @@
"Use sRGB": "Utiliser sRGB",
"View Options": "Options d'affichage",
"View Options…": "Options d'affichage…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Affichage → Incrustation de la loupe → Options d'affichage choisit les lignes que montrent Info 1 et Info 2.",
"View → View Options chooses the lines Info 1 and Info 2 show.": "Affichage → Options d'affichage choisit les lignes que montrent Infos 1 et Infos 2.",
"Visualize HDR": "Visualiser le HDR",
"When pins show on the photo (Shift+H cycles)": "Quand les épingles s'affichent sur la photo (Maj+H pour parcourir)",
+6
View File
@@ -193,6 +193,7 @@
"Basic": "Dasar",
"Before": "Sebelum",
"Before the last template": "Sebelum templat terakhir diterapkan",
"Before/After": "Sebelum/Sesudah",
"Before/After (Y)": "Sebelum/Sesudah (Y)",
"Before/After Settings": "Pengaturan Sebelum/Sesudah",
"Before/After Split": "Sebelum/Sesudah: terbagi",
@@ -439,6 +440,7 @@
"Crop & Rotate": "Pangkas & putar",
"Crop & Rotate (C)": "Pangkas & putar (C)",
"Crop Aspect": "Aspek pangkas",
"Crop Overlay": "Overlay pangkas",
"Crop, Rotate, Geometry": "Pangkas, putar, geometri",
"Cropped": "Dipangkas",
"Cross Process": "Cross Process",
@@ -2186,6 +2188,7 @@
"We": "Rb",
"Wednesday": "Rabu",
"What's New": "Yang baru",
"White": "Putih",
"White Balance": "Keseimbangan putih",
"White Balance Selector": "Pemilih keseimbangan putih",
"White Balance Selector (W)": "Pemilih keseimbangan putih (W)",
@@ -2403,6 +2406,9 @@
"Dropped Files": "File yang dijatuhkan",
"Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto",
"Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan",
"Loupe Overlay": "Overlay loupe",
"View Options…": "Opsi Tampilan…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Tampilan → Overlay loupe → Opsi Tampilan memilih baris yang ditampilkan Info 1 dan Info 2.",
"Lens Profiles": "Profil lensa",
"Download lens profiles?": "Unduh profil lensa?",
"LightCraft can correct distortion and vignetting for many lenses using the open lens database (lensfun, about {size} MB).": "LightCraft dapat mengoreksi distorsi dan vinyet untuk banyak lensa menggunakan basis data lensa terbuka (lensfun, sekitar {size} MB).",
+4 -1
View File
@@ -141,6 +141,7 @@
"Before/After (Y)": "Prima/Dopo (Y)",
"Before/After Settings": "Impostazioni Prima/Dopo",
"Before/After Split": "Prima/Dopo diviso",
"Before/After": "Prima/Dopo",
"Before/After Split Top/Bottom": "Prima/Dopo diviso sopra/sotto",
"Before/After Top/Bottom": "Prima/Dopo sopra/sotto",
"Begin Interaction": "Inizia interazione",
@@ -346,6 +347,7 @@
"Cut": "Taglia",
"Cut pages": "Taglia pagine",
"Cycle Crop Overlay": "Cambia sovrapposizione del ritaglio",
"Crop Overlay": "Sovrapposizione del ritaglio",
"Cycle Crop Overlay Orientation": "Cambia orientamento della sovrapposizione del ritaglio",
"Cycle Info Overlay": "Cambia sovrapposizione delle informazioni",
"Cycle Mask Overlay Color": "Cambia colore della sovrapposizione maschera",
@@ -1630,6 +1632,7 @@
"XMP sidecars": "File XMP collaterali",
"Year": "Anno",
"Yellow": "Giallo",
"White": "Bianco",
"Yellow Hue": "Tonalità giallo",
"Yellow Luminance": "Luminanza giallo",
"Yellow Saturation": "Saturazione giallo",
@@ -2397,7 +2400,6 @@
"Use Defaults": "Usa predefiniti",
"Show briefly when photo changes": "Mostra brevemente al cambio di foto",
"Camera & Lens": "Fotocamera e obiettivo",
"View → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.",
"Blur Amount": "Quantità di sfocatura",
"Boost": "Enfasi",
"In Focus": "A fuoco",
@@ -2543,6 +2545,7 @@
"Click to show clipping warnings for shadows and highlights.": "Fai clic per mostrare gli avvisi di taglio per ombre e luci.",
"Hide this wheel's effect": "Nascondi l'effetto di questa ruota",
"Loupe Overlay": "Sovrapposizione lente",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Visualizza → Sovrapposizione lente → Opzioni di visualizzazione sceglie le righe di Info 1 e Info 2.",
"Grid: add the next photo to the selection": "Griglia: aggiungi la foto successiva alla selezione",
"Grid: add the previous photo to the selection": "Griglia: aggiungi la foto precedente alla selezione",
"Grid: first photo of the view": "Griglia: prima foto della vista",
+7
View File
@@ -141,6 +141,7 @@
"Before/After (Y)": "編集前/編集後(Y)",
"Before/After Settings": "編集前/編集後の設定",
"Before/After Split": "編集前/編集後の分割表示",
"Before/After": "編集前/編集後",
"Before/After Split Top/Bottom": "編集前/編集後の上下分割表示",
"Before/After Top/Bottom": "編集前/編集後の上下表示",
"Begin Interaction": "操作を開始",
@@ -335,6 +336,7 @@
"Custom template…": "カスタムテンプレート…",
"Custom…": "カスタム…",
"Cycle Crop Overlay": "切り抜きの重ね表示を切り替え",
"Crop Overlay": "切り抜きの重ね表示",
"Cycle Crop Overlay Orientation": "切り抜きの重ね表示の向きを切り替え",
"Cycle Info Overlay": "情報オーバーレイを切り替え",
"Cycle Mask Overlay Color": "マスクの重ね表示の色を切り替え",
@@ -1526,6 +1528,7 @@
"XMP sidecars": "XMPサイドカーファイル",
"Year": "年",
"Yellow": "イエロー",
"White": "ホワイト",
"Yellow Hue": "イエローの色相",
"Yellow Luminance": "イエローの輝度",
"Yellow Saturation": "イエローの彩度",
@@ -2401,6 +2404,10 @@
"The photos are imported once it ends": "終わりしだい写真を読み込みます",
"An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください",
"Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください",
"Loupe Overlay": "ルーペのオーバーレイ",
"View Options…": "表示オプション…",
"View Options": "表示オプション",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "表示 → ルーペのオーバーレイ → 表示オプション で、情報1と情報2に表示する行を選びます。",
"Camera preview": "カメラのプレビュー",
"The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "LightCraft が RAW を現像するまで表示される、カメラ自身の JPEG です。色とトーンは現像後の写真で判断してください。",
"Profile: from the file (the camera's own correction)": "プロファイル: ファイル内(カメラ自身の補正)",
+5
View File
@@ -257,6 +257,7 @@
"Before/After (Y)": "მანამდე/შემდეგ (Y)",
"Before/After Settings": "მანამდე/შემდეგ პარამეტრები",
"Before/After Split": "მანამდე/შემდეგ, გაყოფილი",
"Before/After": "მანამდე/შემდეგ",
"Before/After Split Top/Bottom": "მანამდე/შემდეგ, გაყოფილი ზემოთ/ქვემოთ",
"Before/After Top/Bottom": "მანამდე/შემდეგ ზემოთ/ქვემოთ",
"Begin Interaction": "ურთიერთქმედების დაწყება",
@@ -523,6 +524,7 @@
"Cut pages": "გვერდების ამოჭრა",
"Cut, Copy, Paste and Select All. Esc in them gives back the text from before you started typing (in the Info panel it": "ხელმისაწვდომია ამოჭრა, კოპირება, ჩასმა და ყველაფრის მონიშვნა. Esc მათში აკრეფის დაწყებამდე არსებულ ტექსტს აბრუნებს (ინფორმაციის პანელში",
"Cycle Crop Overlay": "ჩამოჭრის ზედდების მონაცვლეობა",
"Crop Overlay": "ჩამოჭრის ზედდება",
"Cycle Crop Overlay Orientation": "ჩამოჭრის ზედდების ორიენტაციის მონაცვლეობა",
"Cycle Info Overlay": "ინფორმაციის ზედდების მონაცვლეობა",
"Cycle Mask Overlay Color": "ნიღბის ზედდების ფერის მონაცვლეობა",
@@ -2316,6 +2318,7 @@
"XMP sidecars": "XMP თანმხლები ფაილები",
"Year": "წელი",
"Yellow": "ყვითელი",
"White": "თეთრი",
"Yellow Hue": "ყვითლის ფერის ტონი",
"Yellow Luminance": "ყვითლის სიკაშკაშე",
"Yellow Saturation": "ყვითლის გაჯერება",
@@ -3162,6 +3165,8 @@
"Delete Cell": "უჯრის წაშლა",
"Click a cell to move, resize or arrange it": "დაწკაპეთ უჯრაზე მის გადასაადგილებლად, ზომის შესაცვლელად ან დასალაგებლად",
"Loupe Overlay": "ლუპის ზედდება",
"View Options…": "ხედის პარამეტრები…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "ხედი → ლუპის ზედდება → ხედის პარამეტრები ირჩევს სტრიქონებს, რომლებსაც Info 1 და Info 2 აჩვენებს.",
"2026-10-21": "2026-10-21",
"Sharper resampling in HDR and panorama merges": "უფრო მკვეთრი ხელახალი დისკრეტიზაცია HDR-ისა და პანორამის გაერთიანებებში",
"Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a": "გაერთიანებული ფოტოები (HDR და პანორამა) ხელახლა დისკრეტიზდება უფრო მკვეთრი ფილტრით (Lanczos-3 ბიწრფივის ნაცვლად). ფოტოს",
+6
View File
@@ -135,6 +135,7 @@
"Before/After (Y)": "Przed/Po (Y)",
"Before/After Settings": "Ustawienia porównania przed/po",
"Before/After Split": "Podział przed/po",
"Before/After": "Przed/Po",
"Before/After Split Top/Bottom": "Podział przed/po góra/dół",
"Before/After Top/Bottom": "Przed/Po góra/dół",
"Begin Interaction": "Rozpocznij interakcję",
@@ -332,6 +333,7 @@
"Cut": "Wytnij",
"Cut pages": "Wytnij strony",
"Cycle Crop Overlay": "Przełącz nakładkę kadrowania",
"Crop Overlay": "Nakładka kadrowania",
"Cycle Crop Overlay Orientation": "Przełącz orientację nakładki kadrowania",
"Cycle Info Overlay": "Przełącz nakładkę informacji",
"Cycle Mask Overlay Color": "Przełącz kolor nakładki maski",
@@ -1563,6 +1565,7 @@
"XMP sidecars": "Pliki pomocnicze XMP",
"Year": "Rok",
"Yellow": "Żółty",
"White": "Biały",
"Yellow Hue": "Odcień żółci",
"Yellow Luminance": "Luminancja żółci",
"Yellow Saturation": "Nasycenie żółci",
@@ -2327,6 +2330,9 @@
"The photos are imported once it ends": "Zdjęcia zostaną zaimportowane potem",
"An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy",
"Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia",
"Loupe Overlay": "Nakładka lupy",
"View Options…": "Opcje widoku…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Widok → Nakładka lupy → Opcje widoku wybiera wiersze, które pokazują Info 1 i Info 2.",
"Profile: from the file (the camera's own correction)": "Profil: z pliku (korekcja aparatu)",
"Downloading the lens database…": "Pobieranie bazy obiektywów…",
"This file names no lens.": "Ten plik nie podaje obiektywu.",
+6
View File
@@ -145,6 +145,7 @@
"Before/After (Y)": "Antes/Depois (Y)",
"Before/After Settings": "Configurações de Antes/Depois",
"Before/After Split": "Divisão Antes/Depois",
"Before/After": "Antes/Depois",
"Before/After Split Top/Bottom": "Divisão Antes/Depois topo/base",
"Before/After Top/Bottom": "Antes/Depois topo/base",
"Begin Interaction": "Iniciar interação",
@@ -353,6 +354,7 @@
"Cut": "Recortar",
"Cut pages": "Recortar páginas",
"Cycle Crop Overlay": "Alternar sobreposição de recorte",
"Crop Overlay": "Sobreposição de recorte",
"Cycle Crop Overlay Orientation": "Alternar orientação da sobreposição de recorte",
"Cycle Info Overlay": "Alternar sobreposição de informações",
"Cycle Mask Overlay Color": "Alternar cor da sobreposição da máscara",
@@ -1623,6 +1625,7 @@
"XMP sidecars": "Sidecars XMP",
"Year": "Ano",
"Yellow": "Amarelo",
"White": "Branco",
"Yellow Hue": "Matiz do amarelo",
"Yellow Luminance": "Luminância do amarelo",
"Yellow Saturation": "Saturação do amarelo",
@@ -2247,6 +2250,9 @@
"The photos are imported once it ends": "As fotos serão importadas depois",
"An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar",
"Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos",
"Loupe Overlay": "Sobreposição da lupa",
"View Options…": "Opções de exibição…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Exibir → Sobreposição da lupa → Opções de exibição escolhe as linhas que Info 1 e Info 2 mostram.",
"Camera preview": "Prévia da câmera",
"The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "O JPEG da própria câmera, mostrado até o LightCraft renderizar o RAW. Avalie cor e tom na foto renderizada.",
"Profile: from the file (the camera's own correction)": "Perfil: do arquivo (correção da própria câmera)",
+6
View File
@@ -311,6 +311,7 @@
"Before/After (Y)": "До/после (Y)",
"Before/After Settings": "Настройки «до/после»",
"Before/After Split": "Разделение «до/после»",
"Before/After": "До/после",
"Before/After Split Top/Bottom": "Разделение «до/после» сверху/снизу",
"Before/After Top/Bottom": "До/после сверху/снизу",
"Begin Interaction": "Начать взаимодействие",
@@ -490,6 +491,7 @@
"Cut": "Вырезать",
"Cut pages": "Вырезать страницы",
"Cycle Crop Overlay": "Переключить сетку кадрирования",
"Crop Overlay": "Сетка кадрирования",
"Cycle Crop Overlay Orientation": "Переключить ориентацию сетки кадрирования",
"Cycle Info Overlay": "Переключить информационную накладку",
"Cycle Mask Overlay Color": "Переключить цвет наложения маски",
@@ -1577,6 +1579,7 @@
"XMP sidecars": "XMP-файлы",
"Year": "Год",
"Yellow": "Жёлтый",
"White": "Белый",
"Yellow Hue": "Тон жёлтого",
"Yellow Luminance": "Яркость жёлтого",
"Yellow Saturation": "Насыщенность жёлтого",
@@ -2609,6 +2612,9 @@
"The photos are imported once it ends": "Фото будут импортированы после этого",
"An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится",
"Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото",
"Loupe Overlay": "Накладка лупы",
"View Options…": "Параметры вида…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Вид → Накладка лупы → Параметры вида выбирает строки, которые показывают Info 1 и Info 2.",
"Camera preview": "Превью камеры",
"The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Собственный JPEG камеры, показанный, пока LightCraft не обработает RAW. Оценивайте цвет и тон по обработанному фото.",
"Profile: from the file (the camera's own correction)": "Профиль: из файла (коррекция самой камеры)",
+4
View File
@@ -3318,6 +3318,7 @@
"usual and then added to Photos, into a top-level album of that name (made when it's missing). The toast says how": "som vanligt och läggs sedan till i Photos, i ett album på toppnivå med det namnet (skapas om det saknas). Notisen anger hur",
"View Options": "Visningsalternativ",
"View Options…": "Visningsalternativ…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Visa → Lupp-överlägg → Visningsalternativ väljer vilka rader Info 1 och Info 2 visar.",
"View → View Options chooses the lines Info 1 and Info 2 show.": "Visa → Visningsalternativ väljer vilka rader Info 1 och Info 2 visar.",
"VLC and recent phones and TVs play it.": "VLC och nya telefoner och tv-apparater spelar upp den.",
"watermark preview for it, no longer crashes LightCraft; the export is capped at the encoders' 65,535 pixels.": "vattenstämpelförhandsgranskning för den, kraschar inte längre LightCraft; exporten begränsas till kodarnas 65 535 pixlar.",
@@ -3411,6 +3412,9 @@
"Dropped Files": "Släppta filer",
"Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton",
"Import dropped files without review": "Importera släppta filer utan granskning",
"White": "Vit",
"Before/After": "Före/efter",
"Crop Overlay": "Beskärningsöverlägg",
"A manual slideshow shows each slide until → or ← changes it. Exports still use the slide duration.": "I ett manuellt bildspel visas varje bild tills du byter med → eller ←. Exporter använder ändå visningstiden per bild.",
"Always merge into the open library": "Sammanfoga alltid med det öppna biblioteket",
"Another library was opened since this window appeared: nothing was imported": "Ett annat bibliotek öppnades efter att det här fönstret visades: ingenting importerades",
+6
View File
@@ -325,6 +325,7 @@
"Window": "Вікно",
"Wrote the XMP sidecars that were waiting": "XMP-файли, що очікували, записано",
"Yellow": "Жовтий",
"White": "Білий",
"Yes": "Так",
"Zoom": "Масштаб",
"Zoom In": "Збільшити",
@@ -479,6 +480,7 @@
"Before/After (Y)": "До/після (Y)",
"Before/After Settings": "Налаштування до/після",
"Before/After Split": "Розділення до/після",
"Before/After": "До/після",
"Before/After Split Top/Bottom": "Розділення до/після зверху/знизу",
"Before/After Top/Bottom": "До/після зверху/знизу",
"Begin Interaction": "Почати взаємодію",
@@ -622,6 +624,7 @@
"Change Time": "Змінити час",
"Custom template…": "Власний шаблон…",
"Cycle Crop Overlay": "Перемкнути накладання кадрування",
"Crop Overlay": "Накладання кадрування",
"Cycle Crop Overlay Orientation": "Перемкнути орієнтацію накладання кадрування",
"Cycle Info Overlay": "Перемкнути накладання інформації",
"Cycle Mask Overlay Color": "Перемкнути колір накладання маски",
@@ -2399,6 +2402,9 @@
"The photos are imported once it ends": "Фото буде імпортовано після цього",
"An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться",
"Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото",
"Loupe Overlay": "Накладання лупи",
"View Options…": "Параметри перегляду…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Вигляд → Накладання лупи → Параметри перегляду вибирає рядки, які показують Info 1 та Info 2.",
"Camera preview": "Прев'ю камери",
"The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "Власний JPEG камери, показаний, доки LightCraft не обробить RAW. Оцінюйте колір і тон за обробленим фото.",
"Profile: from the file (the camera's own correction)": "Профіль: з файлу (корекція самої камери)",
+4
View File
@@ -182,6 +182,7 @@
"Balance": "Cân bằng",
"Basic": "Cơ bản",
"Before": "Trước",
"Before/After": "Trước/Sau",
"Before/After (Y)": "Trước/Sau (Y)",
"Before/After Settings": "Cài đặt Trước/Sau",
"Before/After Split": "Chia Trước/Sau",
@@ -409,6 +410,7 @@
"Crop & Rotate": "Cắt và xoay",
"Crop & Rotate (C)": "Cắt và xoay (C)",
"Crop Aspect": "Tỷ lệ cắt",
"Crop Overlay": "Lớp phủ cắt",
"Crop, Rotate, Geometry": "Cắt, xoay, hình học",
"Cropped": "Đã cắt",
"Cross Process": "Cross Process",
@@ -2003,6 +2005,7 @@
"We": "T4",
"Wednesday": "Thứ Tư",
"What's New": "Có gì mới",
"White": "Trắng",
"White Balance": "Cân bằng trắng",
"White Balance Selector": "Bộ chọn cân bằng trắng",
"White Balance Selector (W)": "Bộ chọn cân bằng trắng (W)",
@@ -2723,6 +2726,7 @@
"Use Defaults": "Dùng mặc định",
"View Options": "Tùy chọn hiển thị",
"View Options…": "Tùy chọn hiển thị…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "Xem → Lớp phủ kính lúp → Tùy chọn xem chọn các dòng mà Info 1 và Info 2 hiển thị.",
"View → View Options chooses the lines Info 1 and Info 2 show.": "Xem → Tùy chọn hiển thị để chọn các dòng hiển thị trong Thông tin 1 và Thông tin 2.",
"When importing a Lightroom catalog": "Khi nhập danh mục Lightroom",
"Width & Height": "Chiều rộng & Chiều cao",
+6
View File
@@ -144,6 +144,7 @@
"Before/After (Y)": "修改前/修改后 (Y)",
"Before/After Settings": "修改前/修改后设置",
"Before/After Split": "修改前/修改后分屏",
"Before/After": "修改前/修改后",
"Before/After Split Top/Bottom": "修改前/修改后上下分屏",
"Before/After Top/Bottom": "修改前/修改后上下排列",
"Begin Interaction": "开始交互",
@@ -351,6 +352,7 @@
"Cut": "剪切",
"Cut pages": "剪切页面",
"Cycle Crop Overlay": "切换裁切叠加",
"Crop Overlay": "裁切叠加",
"Cycle Crop Overlay Orientation": "切换裁切叠加方向",
"Cycle Info Overlay": "切换信息叠加",
"Cycle Mask Overlay Color": "切换蒙版叠加颜色",
@@ -1599,6 +1601,7 @@
"XMP sidecars": "XMP 附属文件",
"Year": "年",
"Yellow": "黄色",
"White": "白色",
"Yellow Hue": "黄色色相",
"Yellow Luminance": "黄色明度",
"Yellow Saturation": "黄色饱和度",
@@ -2246,6 +2249,9 @@
"The photos are imported once it ends": "结束后即导入这些照片",
"An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片",
"Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入",
"Loupe Overlay": "放大镜叠加",
"View Options…": "视图选项…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "视图 → 放大镜叠加 → 视图选项 用于选择“信息 1”和“信息 2”显示的行。",
"Camera preview": "相机预览",
"The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "相机自己的 JPEG,在 LightCraft 渲染出原始文件之前显示。请在渲染后的照片上判断颜色和影调。",
"Profile: from the file (the camera's own correction)": "配置文件:来自文件(相机自身的校正)",
+6
View File
@@ -144,6 +144,7 @@
"Before/After (Y)": "編輯前/後(Y)",
"Before/After Settings": "編輯前/後設定",
"Before/After Split": "編輯前/後分割檢視",
"Before/After": "編輯前/後",
"Before/After Split Top/Bottom": "編輯前/後上下分割檢視",
"Before/After Top/Bottom": "編輯前/後上下檢視",
"Begin Interaction": "開始互動",
@@ -352,6 +353,7 @@
"Cut": "剪下",
"Cut pages": "剪下頁面",
"Cycle Crop Overlay": "切換裁切疊加",
"Crop Overlay": "裁切疊加",
"Cycle Crop Overlay Orientation": "切換裁切疊加方向",
"Cycle Info Overlay": "切換資訊疊加",
"Cycle Mask Overlay Color": "切換遮色片疊加色彩",
@@ -1605,6 +1607,7 @@
"XMP sidecars": "XMP 附屬檔案",
"Year": "年",
"Yellow": "黃色",
"White": "白色",
"Yellow Hue": "黃色色相",
"Yellow Luminance": "黃色明度",
"Yellow Saturation": "黃色飽和度",
@@ -2203,6 +2206,9 @@
"The photos are imported once it ends": "結束後即匯入這些照片",
"An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片",
"Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入",
"Loupe Overlay": "放大鏡疊加",
"View Options…": "檢視選項…",
"View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show.": "檢視 → 放大鏡疊加 → 檢視選項 可選擇「資訊 1」和「資訊 2」顯示的行。",
"Camera preview": "相機預覽",
"The camera's own JPEG, shown until LightCraft has rendered the raw. Judge colour and tone on the rendered photo.": "相機自己的 JPEG,在 LightCraft 算繪出原始檔之前顯示。請在算繪後的照片上判斷色彩與色調。",
"Profile: from the file (the camera's own correction)": "設定檔:來自檔案(相機本身的校正)",
+1 -1
View File
@@ -537,7 +537,7 @@ pub fn open_download_dialog(app: &mut LightcraftApp, m: &Value) {
app.ui.dialog = Some(crate::state::Dialog::FaceModel { path: String::new(), info, accepted: false });
}
/// Photo ▸ Detect Faces without the detector: offer to download it (its terms first), the same as in Settings.
/// Photo ▸ Metadata ▸ Detect Faces without the detector: offer to download it (its terms first), the same as in Settings.
pub fn offer_detector(app: &mut LightcraftApp) {
let list = app.session.execute("faces.models.list", &json!({})).unwrap_or(Value::Null);
if let Some(m) = list["models"].as_array().and_then(|a| a.iter().find(|m| m["role"] == "detector" && m["installed"] != true)) {
@@ -128,10 +128,10 @@ pub(super) fn interface_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke
use crate::state::InfoOverlay as I;
choices(ui, "settingsInfo", &[(I::Off, "Off"), (I::Basic, "Info 1"), (I::Exposure, "Info 2")], &mut app.ui.info_overlay);
});
hint(ui, t, crate::i18n::tr("View → View Options chooses the lines Info 1 and Info 2 show."));
hint(ui, t, crate::i18n::tr("View → Loupe Overlay → View Options chooses the lines Info 1 and Info 2 show."));
}
/// View ▸ View Options (⌘J), Lightroom Classic's Loupe View tab: whether the info overlay shows and
/// View ▸ Loupe Overlay ▸ View Options… (⌘J), Lightroom Classic's Loupe View tab: whether the info overlay shows and
/// which, the three lines each of Info 1 and Info 2 shows, which of them shows briefly when the
/// photo changes, and whether the loupe shows its loading and rendering message
/// (`view.viewOptions`). Changes apply as they are made.
@@ -23,7 +23,7 @@ pub(super) fn slideshow_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Toke
export_section(app, ui, t);
}
/// Export: PDF, JPEG sequence or video of the slideshow (View ▸ Export Slideshow…).
/// Export: PDF, JPEG sequence or video of the slideshow (View ▸ Slideshow ▸ Export Slideshow…).
fn export_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
heading(ui, t, crate::i18n::tr("Export"));
let running = app.session.slideshow_export.as_ref().is_some_and(|r| r.running());
@@ -1,4 +1,4 @@
//! View ▸ Export Slideshow…: the dialog's choices go to `app.slideshowExport`, which asks where
//! View ▸ Slideshow ▸ Export Slideshow…: the dialog's choices go to `app.slideshowExport`, which asks where
//! to write (a PDF or video file, or the folder of a JPEG sequence) and starts the engine's
//! `slideshow.export` in the background. The export's row in the activity stack shows its
//! progress and ✕ (the engine owns the row); [`poll`] tells the user how it ended.
@@ -74,7 +74,7 @@ pub fn poll(app: &mut LightcraftApp, ctx: &egui::Context) {
}
/// A labelled row (fixed label column).
/// View ▸ Export Slideshow…: what to write (PDF, JPEG sequence, video) and how big; where comes
/// View ▸ Slideshow ▸ Export Slideshow…: what to write (PDF, JPEG sequence, video) and how big; where comes
/// after (a save dialog).
pub(super) fn slideshow_export_body(app: &mut LightcraftApp, ui: &mut egui::Ui, settings: &mut lightcraft_engine::slideshow_export::ExportSettings) {
use lightcraft_engine::slideshow_export::{ExportSettings, Format};
+14 -15
View File
@@ -731,7 +731,7 @@ fn adding_a_face_model_shows_its_terms_and_installs_only_once_accepted() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Photo > Detect Faces without the detector offers the download: the terms first, nothing fetched before they are
/// Photo > Metadata > Detect Faces without the detector offers the download: the terms first, nothing fetched before they are
/// accepted, and the model's row in Settings has its Download button.
#[test]
fn detect_faces_without_the_detector_offers_the_download_and_fetches_nothing_before_acceptance() {
@@ -4176,6 +4176,12 @@ fn import_copy_renames_into_destination() {
let _ = std::fs::remove_dir_all(&base);
}
/// The instant this machine reads as the tests' clock time: an undated file takes the file's
/// date in the host's zone, so a fixed epoch would file it on the day before west of UTC.
fn filed_at() -> u64 {
lightcraft_engine::import::local_instant("2026-01-14T05:58:48").and_then(|s| u64::try_from(s).ok()).unwrap_or(0)
}
/// Import review, Copy, Folders → Custom template…: the default `{date:%Y}/{date:%Y%m%d}`
/// files copies under `2026/20260114/`, the example line shows the full destination, and a
/// template that would climb out of the destination is refused.
@@ -4188,13 +4194,10 @@ fn import_copy_into_a_custom_folder_template() {
let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[40, 3, 9, 255]; 64] };
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();
std::fs::write(src.join("IMG_01.png"), png).unwrap();
// undated files are filed by the file's date (2026-01-14T05:58:48)
std::fs::File::options()
.write(true)
.open(src.join("IMG_01.png"))
.unwrap()
.set_modified(std::time::UNIX_EPOCH + Duration::from_secs(1_768_370_328))
.unwrap();
// Undated files are filed by the file's date, read in the host's zone (issue #2284), so
// the file is pinned to the instant this machine reads as 2026-01-14T05:58:48.
let when = std::time::UNIX_EPOCH + Duration::from_secs(filed_at());
std::fs::File::options().write(true).open(src.join("IMG_01.png")).unwrap().set_modified(when).unwrap();
let dest_s = dest.to_string_lossy().to_string();
let services = crate::Services { png: None, pick_folder: Some(Box::new(move || Some(dest_s.clone()))), ..Default::default() };
let mut session = lightcraft_engine::Session::with_demo().with_fs();
@@ -4247,12 +4250,8 @@ fn import_move_into_a_folder_template() {
let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[40 + i, 3, 9, 255]; 64] };
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();
std::fs::write(src.join(format!("IMG_0{i}.png")), png).unwrap();
std::fs::File::options()
.write(true)
.open(src.join(format!("IMG_0{i}.png")))
.unwrap()
.set_modified(std::time::UNIX_EPOCH + Duration::from_secs(1_768_370_328))
.unwrap();
let when = std::time::UNIX_EPOCH + Duration::from_secs(filed_at());
std::fs::File::options().write(true).open(src.join(format!("IMG_0{i}.png"))).unwrap().set_modified(when).unwrap();
}
let dest_s = dest.to_string_lossy().to_string();
let services = crate::Services { png: None, pick_folder: Some(Box::new(move || Some(dest_s.clone()))), ..Default::default() };
@@ -4665,7 +4664,7 @@ fn info_overlay_toasts_are_painted_in_the_users_language() {
}
}
/// ⌘J opens View ▸ View Options; its menus choose Info 1's and Info 2's lines, Use Defaults puts
/// ⌘J opens View ▸ Loupe Overlay ▸ View Options…; its menus choose Info 1's and Info 2's lines, Use Defaults puts
/// them back, and `view.viewOptions` sets them for an agent (refusing a line it doesn't know).
#[test]
fn view_options_choose_the_info_overlay_lines() {
+204 -78
View File
@@ -120,9 +120,9 @@ pub fn native_menu_structure(bar: &[(String, Vec<MenuNode>)], keymap: &crate::sh
/// Top-level menus in order (the macOS app menu is added by the host).
pub const MENUS: &[&str] = &["File", "Edit", "View", "Photo", "Window", "Help"];
/// Order and grouping per menu: command ids, `---` separators and `@Submenu` placeholders.
/// Entries with a menu path that aren't listed are appended at the end of their menu, before any
/// [`LAST`] item.
/// Order and grouping per menu: command ids, `---` separators and `@Submenu` placeholders. Every
/// command with a menu path has a slot here, or its submenu does (a test checks it); an entry left
/// out would still be appended at the end of its menu, before any [`LAST`] item.
const LAYOUT: &[(&str, &[&str])] = &[
(
"File",
@@ -130,12 +130,15 @@ const LAYOUT: &[(&str, &[&str])] = &[
"file.addPhotos",
"file.addFolder",
"@Import from Device",
"file.importLightroom",
"---",
"app.newLibrary",
"app.openLibrary",
"@Open Recent Library",
"file.backupLibrary",
"file.restoreLibrary",
"file.findMissing",
"library.compact",
"---",
"dialog.newAlbum",
"dialog.newFolder",
@@ -151,6 +154,9 @@ const LAYOUT: &[(&str, &[&str])] = &[
"app.exportPrevious",
"@Export with Preset",
"---",
"dialog.print",
"dialog.contactSheet",
"---",
"library.toggleAutoWriteXmp",
"@Previews",
"---",
@@ -179,6 +185,7 @@ const LAYOUT: &[(&str, &[&str])] = &[
"view.focusSearch",
"---",
"app.settings",
"@Language",
],
),
(
@@ -186,35 +193,20 @@ const LAYOUT: &[(&str, &[&str])] = &[
&[
"view.photoGrid",
"view.squareGrid",
"@Grid Info",
"view.thumbSizeUp",
"view.thumbSizeDown",
"view.detail",
"view.compare",
"view.survey",
"view.reference",
"view.people",
"---",
"view.leftPanel",
"@Sidebar Sections",
"view.photoCounts",
"view.faceBoxes",
"view.focusPoint",
"view.zoomToFocus",
"view.filmstrip",
"view.histogram",
"view.navigator",
"view.infoOverlay",
"@Loupe Overlay",
"@Appearance",
"---",
"view.fullScreenPreview",
"view.lightsOut",
"view.enterFullScreen",
"---",
"view.showOriginal",
"view.beforeAfter",
"view.beforeAfterSplit",
"@Before/After Settings",
"@Grid Info",
"view.thumbSizeUp",
"view.thumbSizeDown",
"@Sort",
"@Stacks",
"view.filterBar",
"library.toggleFilters",
"library.clearFilter",
"---",
"view.zoomIn",
"view.zoomOut",
@@ -225,38 +217,39 @@ const LAYOUT: &[(&str, &[&str])] = &[
"view.clipping",
"view.visualizeHdr",
"view.softProof",
"view.maskOverlay",
"view.maskOverlayAll",
"view.maskOverlayMode",
"view.maskOverlayColor",
"view.maskPins",
"@Tool Overlay",
"view.cropOverlay",
"view.visualizeSpots",
"---",
"@Sort",
"@Stacks",
"view.filterBar",
"library.toggleFilters",
"library.clearFilter",
"library.refresh",
"library.holdView",
"@Loupe Overlay",
"@Before/After",
"@Mask Overlay",
"@Tool Overlay",
"@Crop Overlay",
"---",
"compare.swap",
"compare.makeSelect",
"---",
"view.viewOptions",
"view.fullScreenPreview",
"view.lightsOut",
"view.enterFullScreen",
"@Slideshow",
"---",
"@Appearance",
],
),
(
"Photo",
&[
"@Edit In",
"---",
"@Add to Album",
"photo.addToLibrary",
"---",
"@Set Rating",
"@Set Flag",
"@Set Color Label",
"@Metadata Preset",
"view.autoAdvance",
"dialog.cull",
"library.findSimilar",
"---",
"photo.rotateLeft",
"photo.rotateRight",
@@ -265,36 +258,38 @@ const LAYOUT: &[(&str, &[&str])] = &[
"---",
"version.create",
"photo.virtualCopy",
"photo.duplicate",
"@Stack",
"@Photo Merge",
"photo.convertToDng",
"---",
"develop.auto",
"develop.treatment",
"develop.reset",
"develop.matchExposure",
"develop.updateProcess",
"dialog.createPreset",
"---",
"photo.saveMetadataToFile",
"photo.readMetadataFromFile",
"photo.reload",
"photo.readFocusPoints",
"@Metadata",
"---",
"app.showInFinder",
"app.showInFolders",
"dialog.rename",
"dialog.captureTime",
"photo.tagFromTracklog",
"photo.reload",
"tool.enablePainting",
"---",
"album.removePhotos",
"photo.delete",
"photo.restore",
"photo.deletePermanently",
"library.emptyRecentlyDeleted",
],
),
(
"Window",
&[
"panel.edit",
"panel.profiles",
"panel.crop",
"panel.remove",
"panel.masking",
@@ -309,6 +304,17 @@ const LAYOUT: &[(&str, &[&str])] = &[
"---",
"@Edit Sections",
"@Tools",
"---",
"view.leftPanel",
"view.rightPanel",
"@Sidebar Sections",
"view.photoCounts",
"view.filmstrip",
"view.histogram",
"view.navigator",
"---",
"view.secondWindow",
"ui.dock.reset",
],
),
(
@@ -321,10 +327,12 @@ const LAYOUT: &[(&str, &[&str])] = &[
"app.github",
"app.artcraft",
"---",
"app.help",
"app.whatsNew",
"app.shortcuts",
"app.systemInfo",
"app.openLogFolder",
"@Debug",
"---",
"app.checkForUpdates",
"app.about",
@@ -332,12 +340,58 @@ const LAYOUT: &[(&str, &[&str])] = &[
),
];
/// Items that always end their menu in their own separator group, after the entries appended
/// because the layout doesn't list them (Quit is the last item of the in-window File menu).
/// Order and grouping inside submenus: (menu, submenu, slots). Slots are as in [`LAYOUT`] (ids of
/// entries with that submenu path, `---`, `@Nested` submenus), plus `*` for the parameterized
/// items [`expanded`] builds. A submenu without a row here lists those first, then its entries.
const SUBMENUS: &[(&str, &str, &[&str])] = &[
("View", "Sort", &["*", "---", "library.refresh", "library.holdView"]),
("View", "Loupe Overlay", &["view.infoOverlay", "view.viewOptions", "view.focusPoint", "view.zoomToFocus", "view.faceBoxes", "---", "*"]),
(
"View",
"Before/After",
&[
"view.showOriginal",
"view.beforeAfter",
"view.beforeAfterSplit",
"view.beforeAfterTopBottom",
"view.beforeAfterSplitTopBottom",
"---",
"beforeAfter.copyAfterToBefore",
"beforeAfter.copyBeforeToAfter",
"beforeAfter.swap",
"beforeAfter.resetBefore",
],
),
("View", "Mask Overlay", &["view.maskOverlay", "view.maskOverlayAll", "view.maskPins", "---", "*"]),
(
"Photo",
"Metadata",
&[
"dialog.allMetadata",
"photo.copyMetadata",
"photo.pasteMetadata",
"@Metadata Preset",
"---",
"photo.saveMetadataToFile",
"photo.readMetadataFromFile",
"photo.readFocusPoints",
"---",
"dialog.captureTime",
"photo.tagFromTracklog",
"metadata.reverseGeocode",
"metadata.downloadPlaceNames",
"---",
"faces.detect",
],
),
];
/// Items that always end their menu in their own separator group (Quit is the last item of the
/// in-window File menu).
const LAST: &[&str] = &["app.quit"];
/// Registry entries that are reached another way (parameterized commands are expanded into
/// submenus below; others duplicate a dialog command).
/// Registry entries that are reached another way: parameterized commands and the items of
/// hand-built submenus are made by [`expanded`]; the others duplicate a dialog command.
const HIDDEN: &[&str] = &[
"photo.rate",
"photo.flag",
@@ -352,6 +406,14 @@ const HIDDEN: &[&str] = &[
"album.create",
"library.import",
"preset.create",
// File ▸ Previews ▸ Discard Preview Cache
"library.clearPreviews",
// View ▸ Loupe Overlay
"view.chooseLayoutImage",
"view.layoutImage",
// View ▸ Mask Overlay (each mode and colour, then the cycle item)
"view.maskOverlayMode",
"view.maskOverlayColor",
];
/// The selection includes a photo in Recently Deleted.
@@ -525,7 +587,14 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>>
None,
),
MenuNode::Separator,
item("library.clearPreviews", Value::Null, "Discard Preview Cache", None, true, None),
item(
"library.clearPreviews",
Value::Null,
"Discard Preview Cache",
crate::shortcuts::shortcut_of(&app.ui.settings.keymap, "library.clearPreviews"),
true,
None,
),
]
}
"Set Rating" => (0..=5u8)
@@ -652,6 +721,39 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>>
}
v
}
"Mask Overlay" => {
// each mode and colour of the Masking panel's overlay, then the item that steps on
use lightcraft_engine::pipeline::MaskView;
let mode = MaskView::parse(&app.ui.mask_overlay_mode).unwrap_or_default();
let mut v: Vec<MenuNode> = MaskView::ALL
.into_iter()
.map(|m| item("view.maskOverlayMode", json!({"mode": m.name()}), m.label(), None, true, Some(m == mode)))
.collect();
let keymap = &app.ui.settings.keymap;
v.push(item(
"view.maskOverlayMode",
Value::Null,
"Cycle Mask Overlay Mode",
crate::shortcuts::shortcut_of(keymap, "view.maskOverlayMode"),
true,
None,
));
v.push(MenuNode::Separator);
let colors = crate::panels::masking::OVERLAY_COLORS.into_iter().zip(crate::panels::masking::OVERLAY_COLOR_NAMES);
v.extend(colors.map(|(c, name)| {
let hex = format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]);
item("view.maskOverlayColor", json!({"color": hex}), name, None, true, Some(app.ui.mask_overlay_color == c))
}));
v.push(item(
"view.maskOverlayColor",
Value::Null,
"Cycle Mask Overlay Color",
crate::shortcuts::shortcut_of(keymap, "view.maskOverlayColor"),
true,
None,
));
v
}
"Tool Overlay" => {
// when the spot and mask pins show; the last item steps to the next mode (Shift+H)
use crate::state::ToolOverlay;
@@ -808,13 +910,11 @@ pub(crate) fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>>
"Add to Album" => {
let targets = app.session.selected();
let sel = !targets.is_empty();
// albums hold library photos (issue #684): a Local-only selection is told what to do first
// albums hold library photos (issue #684): a Local-only selection finds them off, and Add to My
// Photos is the Photo menu's own item right below this submenu (not repeated in it: one command,
// one row)
let local_only = crate::panels::grid::local_only(app, &targets);
let mut v: Vec<MenuNode> = vec![];
if local_only {
v.push(item("photo.addToLibrary", Value::Null, crate::i18n::tr("Add to My Photos First"), None, false, None));
v.push(MenuNode::Separator);
}
let mut albums: Vec<_> = app.session.catalog.albums().filter(|a| !a.folder && !a.is_smart()).map(|a| (a.name.clone(), a.id.0)).collect();
albums.sort_by_key(|(n, _)| n.to_lowercase());
let any = !albums.is_empty();
@@ -869,6 +969,48 @@ fn tidy(v: Vec<MenuNode>) -> Vec<MenuNode> {
out
}
/// How deep `@Nested` submenus in [`SUBMENUS`] may go (a slot naming its own submenu stops here).
const MAX_SUBMENU_DEPTH: usize = 3;
/// The items of submenu `name` in menu `title`: its [`SUBMENUS`] slots when it has a row there
/// (else the parameterized items of [`expanded`]), then the entries with this submenu path that
/// no slot names, the ones opening a dialog last after a separator.
fn submenu_items(app: &LightcraftApp, entries: &[MenuEntry], used: &mut [bool], title: &str, name: &str, depth: usize) -> Vec<MenuNode> {
let here = |e: &MenuEntry| e.menu.len() == 2 && e.menu[0] == title && e.menu[1] == name;
let slots = SUBMENUS.iter().find(|(t, s, _)| *t == title && *s == name).map_or(&["*"][..], |(_, _, l)| *l);
let mut children = Vec::new();
for slot in slots {
if *slot == "---" {
children.push(MenuNode::Separator);
} else if *slot == "*" {
children.extend(expanded(app, name).unwrap_or_default());
} else if let Some(nested) = slot.strip_prefix('@') {
if depth < MAX_SUBMENU_DEPTH {
let items = submenu_items(app, entries, used, title, nested, depth + 1);
children.push(MenuNode::Submenu { label: nested.to_string(), children: items });
}
} else if let Some(i) = entries.iter().position(|e| e.id == *slot && here(e)) {
if let Some(u) = used.get_mut(i) {
*u = true;
}
children.push(node(app, &entries[i]));
}
}
let mut dialogs = Vec::new();
for (e, u) in entries.iter().zip(used.iter_mut()) {
if !*u && here(e) {
*u = true;
// commands that open a dialog go last, after a separator
if e.label.ends_with('…') { dialogs.push(node(app, e)) } else { children.push(node(app, e)) }
}
}
if !dialogs.is_empty() {
children.push(MenuNode::Separator);
children.extend(dialogs);
}
children
}
/// The whole menu bar: (title, items) per menu in [`MENUS`] order.
pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec<MenuNode>)> {
let entries: Vec<MenuEntry> =
@@ -879,34 +1021,18 @@ pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec<MenuNode>)> {
let layout = LAYOUT.iter().find(|(t, _)| t == title).map(|(_, l)| *l).unwrap_or(&[]);
let mut items = Vec::new();
let mut last = Vec::new();
let sub = |name: &str, used: &mut [bool]| -> Vec<MenuNode> {
let mut children = expanded(app, name).unwrap_or_default();
let mut dialogs = Vec::new();
for (i, e) in entries.iter().enumerate() {
if !used[i] && e.menu.len() == 2 && e.menu[0] == *title && e.menu[1] == name {
used[i] = true;
// commands that open a dialog go last, after a separator
if e.label.ends_with('…') { dialogs.push(node(app, e)) } else { children.push(node(app, e)) }
}
}
if !dialogs.is_empty() {
children.push(MenuNode::Separator);
children.extend(dialogs);
}
children
};
for slot in layout {
if *slot == "---" {
items.push(MenuNode::Separator);
} else if let Some(name) = slot.strip_prefix('@') {
let children = sub(name, &mut used);
let children = submenu_items(app, &entries, &mut used, title, name, 1);
items.push(MenuNode::Submenu { label: name.to_string(), children });
} else if let Some(i) = entries.iter().position(|e| e.id == *slot && e.menu.first().map(String::as_str) == Some(title)) {
used[i] = true;
if LAST.contains(slot) { last.push(node(app, &entries[i])) } else { items.push(node(app, &entries[i])) }
}
}
// everything else that names this menu
// anything the layout doesn't place yet (a test keeps this empty)
items.push(MenuNode::Separator);
let mut extra_subs: Vec<String> = Vec::new();
for (i, e) in entries.iter().enumerate() {
@@ -921,7 +1047,7 @@ pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec<MenuNode>)> {
}
}
for name in extra_subs {
let children = sub(&name, &mut used);
let children = submenu_items(app, &entries, &mut used, title, &name, 1);
items.push(MenuNode::Submenu { label: name, children });
}
if !last.is_empty() {
+123 -17
View File
@@ -278,25 +278,11 @@ fn bar_follows_the_registry_and_state() {
}
#[test]
fn quit_ends_the_file_menu_after_unlisted_entries() {
let app = app();
// the File menu has registry entries the layout doesn't list (appended as fallbacks)
let listed = LAYOUT.iter().find(|(t, _)| *t == "File").unwrap().1;
let unlisted: Vec<String> = crate::menus::menu_entries(&app)
.into_iter()
.filter(|e| e.menu.first().map(String::as_str) == Some("File") && !listed.contains(&e.id.as_str()) && !HIDDEN.contains(&e.id.as_str()))
.map(|e| e.id)
.collect();
assert!(!unlisted.is_empty(), "no fallback File entries to order");
let bar = menu_bar(&app);
fn quit_ends_the_file_menu_alone_in_its_group() {
let bar = menu_bar(&app());
let file = &bar.iter().find(|(t, _)| t == "File").unwrap().1;
// Quit is the last item, alone in its separator group
assert!(matches!(file.last(), Some(MenuNode::Item { id, .. }) if id == "app.quit"), "{file:?}");
assert_eq!(file.get(file.len() - 2), Some(&MenuNode::Separator));
// every fallback entry is still reachable, before Quit
for id in &unlisted {
assert!(find(&file[..file.len() - 1], id).is_some(), "{id} missing before Quit");
}
}
#[test]
@@ -784,7 +770,7 @@ fn shortcut_text_orders_mac_modifiers_control_option_shift_command() {
assert_eq!(shortcut_text("Cmd+Alt+Shift+C", false), "Ctrl+Alt+Shift+C", "other platforms keep the binding as written");
}
/// Every item of a menu, submenus included.
/// Every item of a menu, submenus included, in order.
fn flat(nodes: &[MenuNode]) -> Vec<&MenuNode> {
nodes
.iter()
@@ -796,6 +782,126 @@ fn flat(nodes: &[MenuNode]) -> Vec<&MenuNode> {
.collect()
}
/// The app in each view whose menus differ (grid, loupe with a mask, compare).
fn apps_in_every_view() -> Vec<LightcraftApp> {
[ViewMode::PhotoGrid, ViewMode::Detail, ViewMode::Compare]
.into_iter()
.map(|v| {
let mut a = app();
a.ui.view = v;
a.ui.right = RightPanel::Masking;
a
})
.collect()
}
/// Given every command that names a menu, Then the layout gives it a place: a slot in its
/// menu's [`LAYOUT`] row (one-level path), or a submenu that [`LAYOUT`] or [`SUBMENUS`] places
/// (two-level path). Nothing lands in an unsorted group at the end.
#[test]
fn every_menu_command_has_a_place_in_the_layout() {
let placed = |e: &crate::menus::MenuEntry| -> bool {
let Some(title) = e.menu.first() else { return true };
let top = LAYOUT.iter().filter(|(t, _)| t == title).flat_map(|(_, l)| l.iter().copied());
match e.menu.get(1) {
None => top.clone().any(|s| s == e.id),
Some(sub) => {
let nested = SUBMENUS.iter().filter(|(t, _, _)| t == title).flat_map(|(_, _, l)| l.iter().copied());
top.chain(nested).any(|s| s.strip_prefix('@') == Some(sub.as_str()))
}
}
};
let unplaced: Vec<String> = crate::menus::menu_entries(&app())
.into_iter()
.filter(|e| !HIDDEN.contains(&e.id.as_str()) && !placed(e))
.map(|e| format!("{} ({})", e.id, e.menu.join(" ▸ ")))
.collect();
assert!(unplaced.is_empty(), "commands without a place in LAYOUT: {unplaced:#?}");
}
/// Given the grid, the loupe or Compare with library photos selected, When a menu is opened,
/// Then no command shows up twice in it (with the same parameters), under the same label or
/// another one. The one repeat on purpose: Custom… ends File ▸ Export with Preset with the
/// Export dialog.
#[test]
fn no_menu_offers_the_same_command_twice() {
const ON_PURPOSE: &[(&str, &str)] = &[("dialog.export", "Custom…")];
for a in apps_in_every_view() {
for (title, items) in menu_bar(&a) {
let mut seen: Vec<(&str, &Value, &str)> = Vec::new();
for n in flat(&items) {
let MenuNode::Item { id, params, label, .. } = n else { continue };
if ON_PURPOSE.contains(&(id.as_str(), label.as_str())) {
continue;
}
if let Some((_, _, first)) = seen.iter().find(|(i, p, _)| i == id && *p == params) {
panic!("{title} ({:?}): `{id}` {params} twice, as {first:?} and {label:?}", a.ui.view);
}
seen.push((id, params, label));
}
}
}
}
/// Given any view, Then every menu fits a laptop screen without scrolling: at most 40 rows,
/// a separator counting as half a row (about 45 fit on a 14-inch MacBook's screen).
#[test]
fn every_menu_fits_a_laptop_screen() {
for a in apps_in_every_view() {
for (title, items) in menu_bar(&a) {
let seps = items.iter().filter(|n| **n == MenuNode::Separator).count();
let rows = items.len() - seps;
let height = rows as f32 + seps as f32 / 2.0;
assert!(height <= 40.0, "{title} ({:?}): {rows} rows and {seps} separators", a.ui.view);
}
}
}
/// Given the loupe, When a mask overlay mode or colour is chosen in View ▸ Mask Overlay, Then
/// it is the one in use and the only one checked; the cycle items stay for their keys.
#[test]
fn mask_overlay_menu_lists_modes_and_colors_with_the_current_one_checked() {
use lightcraft_engine::pipeline::MaskView;
let mut a = app();
a.ui.view = ViewMode::Detail;
let mask_menu = |a: &LightcraftApp| -> Vec<MenuNode> {
let bar = menu_bar(a);
let view = &bar.iter().find(|(t, _)| t == "View").expect("View menu").1;
view.iter()
.find_map(|n| match n {
MenuNode::Submenu { label, children } if label == "Mask Overlay" => Some(children.clone()),
_ => None,
})
.expect("View ▸ Mask Overlay")
};
let checked_of = |kids: &[MenuNode], id: &str| -> Vec<Value> {
kids.iter()
.filter_map(|n| match n {
MenuNode::Item { id: i, params, checked: Some(true), .. } if i == id => Some(params.clone()),
_ => None,
})
.collect()
};
let kids = mask_menu(&a);
for id in ["view.maskOverlay", "view.maskOverlayAll", "view.maskPins"] {
assert!(find(&kids, id).is_some(), "{id} in Mask Overlay");
}
let modes = kids.iter().filter(|n| matches!(n, MenuNode::Item { id, params, .. } if id == "view.maskOverlayMode" && !params.is_null())).count();
assert_eq!(modes, MaskView::ALL.len());
let colors = kids.iter().filter(|n| matches!(n, MenuNode::Item { id, params, .. } if id == "view.maskOverlayColor" && !params.is_null())).count();
assert_eq!(colors, crate::panels::masking::OVERLAY_COLORS.len());
for id in ["view.maskOverlayMode", "view.maskOverlayColor"] {
assert!(kids.iter().any(|n| matches!(n, MenuNode::Item { id: i, params, .. } if i == id && params.is_null())), "the cycle item {id} stays");
let catalog_path = super::super::ui_commands::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.3);
assert_eq!(catalog_path, Some("View>Mask Overlay"), "the command catalog (ui.menu.list) places {id} where the menu does");
}
run_item(&mut a, "view.maskOverlayMode", json!({"mode": MaskView::WhiteOnBlack.name()})).unwrap();
run_item(&mut a, "view.maskOverlayColor", json!({"color": "#28c846"})).unwrap();
let kids = mask_menu(&a);
assert_eq!(checked_of(&kids, "view.maskOverlayMode"), vec![json!({"mode": MaskView::WhiteOnBlack.name()})]);
assert_eq!(checked_of(&kids, "view.maskOverlayColor"), vec![json!({"color": "#28c846"})]);
}
/// Given the menu bar, Then an item that turns something on or off is named for the thing,
/// with its check mark saying whether it is on: "Filmstrip ✓", never "Show Filmstrip ✓".
/// Show Original is a view (\), not a switch: it keeps Lightroom's name.
+1 -1
View File
@@ -704,7 +704,7 @@ fn ui_commands_4(app: &mut LightcraftApp, _ctx: &egui::Context, id: &str, p: &Va
}
"view.zoomToggle" => {
// the same ratio a click on the photo zooms to; zooming in centres on the camera's focus
// point when the photo has one (View ▸ Zoom to Focus Point)
// point when the photo has one (View ▸ Loupe Overlay ▸ Zoom to Focus Point)
let zoom_in = app.ui.zoom == Zoom::Fit;
app.ui.zoom = if zoom_in { Zoom::Percent(app.ui.click_zoom as f32) } else { Zoom::Fit };
app.ui.zoom_anim = true;
+29 -29
View File
@@ -72,9 +72,9 @@ pub const UI_COMMANDS: &[UiCommand] = &[
("view.survey", "Survey", Some("N"), "View"),
("view.people", "People", None, "View"),
("view.person", "Show Person", None, ""),
("view.faceBoxes", "Face Boxes", None, "View"),
("view.focusPoint", "Focus Point", Some("Alt+F"), "View"),
("view.zoomToFocus", "Zoom to Focus Point", None, "View"),
("view.faceBoxes", "Face Boxes", None, "View>Loupe Overlay"),
("view.focusPoint", "Focus Point", Some("Alt+F"), "View>Loupe Overlay"),
("view.zoomToFocus", "Zoom to Focus Point", None, "View>Loupe Overlay"),
("view.reduceMotion", "Reduce Motion", None, ""),
("view.reference", "Reference View", Some("Shift+R"), "View"),
("photo.setReference", "Set as Reference Photo", None, ""),
@@ -82,14 +82,14 @@ pub const UI_COMMANDS: &[UiCommand] = &[
("compare.set", "Show in Compare", None, ""),
("compare.makeSelect", "Make Candidate the Select", None, "View"),
("view.autoAdvance", "Auto Advance", None, "Photo"),
("view.filmstrip", "Filmstrip", Some("/"), "View"),
("view.leftPanel", "My Photos Panel", Some("Cmd+Shift+L"), "View"),
("view.rightPanel", "Right Panel", None, "View"),
("view.beforeAfter", "Before/After Side by Side", Some("Y"), "View"),
("view.beforeAfterSplit", "Before/After Split", Some("Shift+Y"), "View"),
("view.beforeAfterTopBottom", "Before/After Top/Bottom", Some("Alt+Y"), "View"),
("view.beforeAfterSplitTopBottom", "Before/After Split Top/Bottom", Some("Alt+Shift+Y"), "View"),
("view.showOriginal", "Show Original", Some("\\"), "View"),
("view.filmstrip", "Filmstrip", Some("/"), "Window"),
("view.leftPanel", "My Photos Panel", Some("Cmd+Shift+L"), "Window"),
("view.rightPanel", "Right Panel", None, "Window"),
("view.beforeAfter", "Before/After Side by Side", Some("Y"), "View>Before/After"),
("view.beforeAfterSplit", "Before/After Split", Some("Shift+Y"), "View>Before/After"),
("view.beforeAfterTopBottom", "Before/After Top/Bottom", Some("Alt+Y"), "View>Before/After"),
("view.beforeAfterSplitTopBottom", "Before/After Split Top/Bottom", Some("Alt+Shift+Y"), "View>Before/After"),
("view.showOriginal", "Show Original", Some("\\"), "View>Before/After"),
("view.zoomFit", "Zoom to Fit", Some("Cmd+0"), "View"),
("view.zoom100", "Zoom 100%", Some("Cmd+Alt+0"), "View"),
("view.zoomToggle", "Toggle Zoom", Some("Z"), "View"),
@@ -106,14 +106,14 @@ pub const UI_COMMANDS: &[UiCommand] = &[
("view.visualizeHdr", "Visualize HDR", None, "View"),
// in grids S expands/collapses stacks (the engine command it shadows)
("view.softProof", "Soft Proofing", Some("S"), "View"),
("view.histogram", "Histogram", Some("Cmd+Shift+H"), "View"),
("view.maskOverlay", "Mask Overlay", Some("O"), "View"),
("view.histogram", "Histogram", Some("Cmd+Shift+H"), "Window"),
("view.maskOverlay", "Mask Overlay", Some("O"), "View>Mask Overlay"),
// Ctrl+Shift+O / Cmd+Shift+O: every mask's region at once, not just the selected one
("view.maskOverlayAll", "All Mask Overlays", Some("Cmd+Shift+O"), "View"),
("view.maskOverlayAll", "All Mask Overlays", Some("Cmd+Shift+O"), "View>Mask Overlay"),
// Shift+O in the Masking panel (elsewhere it cycles the crop overlay)
("view.maskOverlayMode", "Cycle Mask Overlay Mode", None, "View"),
("view.maskOverlayColor", "Cycle Mask Overlay Color", None, "View"),
("view.maskPins", "Mask Pins", None, "View"),
("view.maskOverlayMode", "Cycle Mask Overlay Mode", None, "View>Mask Overlay"),
("view.maskOverlayColor", "Cycle Mask Overlay Color", None, "View>Mask Overlay"),
("view.maskPins", "Mask Pins", None, "View>Mask Overlay"),
// {mode?: auto | always | selected | never}: when spot and mask pins show (steps to the next
// mode when omitted; Shift+H, like Classic's H for pins, since H opens Remove). View ▸ Tool
// Overlay and the Remove panel list the modes.
@@ -122,8 +122,8 @@ pub const UI_COMMANDS: &[UiCommand] = &[
// A while the Crop panel is open: the aspect lock as a first-class row. Visualize Spots keeps
// the key outside the panel; the two are a contextual pair in shortcuts::handle
("crop.lockAspect", "Lock Aspect Ratio", Some("A"), ""),
("view.cropOverlay", "Cycle Crop Overlay", Some("Shift+O"), "View"),
("view.cropOverlayOrientation", "Cycle Crop Overlay Orientation", None, "View"),
("view.cropOverlay", "Cycle Crop Overlay", Some("Shift+O"), "View>Crop Overlay"),
("view.cropOverlayOrientation", "Cycle Crop Overlay Orientation", None, "View>Crop Overlay"),
("view.back", "Back to Grid", Some("Escape"), ""),
("tool.done", "Done", Some("Enter"), ""),
("view.filterBar", "Filter Bar", Some("Shift+F"), "View"),
@@ -135,13 +135,13 @@ pub const UI_COMMANDS: &[UiCommand] = &[
("view.fullScreenPreview", "Full Screen Preview", Some("F"), "View"),
("view.lightsOut", "Lights Out", Some("Shift+L"), "View"),
("view.enterFullScreen", "Enter Full Screen", Some("Cmd+Shift+F"), "View"),
("view.infoOverlay", "Cycle Info Overlay", Some("Cmd+I"), "View"),
("view.viewOptions", "View Options…", Some("Cmd+J"), "View"),
("view.infoOverlay", "Cycle Info Overlay", Some("Cmd+I"), "View>Loupe Overlay"),
("view.viewOptions", "View Options…", Some("Cmd+J"), "View>Loupe Overlay"),
("view.chooseLayoutImage", "Choose Layout Image…", None, "View"),
("view.layoutImage", "Layout Image", Some("Cmd+Alt+O"), "View"),
("view.layoutImageOpacity", "Layout Image Opacity", None, ""),
("view.layoutImageMatte", "Layout Image Matte", None, ""),
("view.navigator", "Navigator", None, "View"),
("view.navigator", "Navigator", None, "Window"),
("panel.edit", "Edit Panel", Some("E"), "Window"),
("panel.profiles", "Profile Browser", None, "Window"),
("panel.crop", "Crop & Rotate", Some("C"), "Window"),
@@ -182,13 +182,13 @@ pub const UI_COMMANDS: &[UiCommand] = &[
("dialog.newAlbum", "New Album…", Some("Cmd+N"), "File"),
("dialog.newFolder", "New Folder…", Some("Cmd+Shift+N"), "File"),
("dialog.smartAlbum", "New Smart Album…", None, "File"),
("view.photoCounts", "Photo Counts", None, "View"),
("view.photoCounts", "Photo Counts", None, "Window"),
("view.sidebarSection", "Show Sidebar Section", None, ""),
("view.sidebarMoveSection", "Move Sidebar Section", None, ""),
("view.sidebarReset", "Reset Sidebar Sections", None, ""),
("view.slideshow", "Slideshow", Some("Cmd+Alt+Enter"), "View"),
("view.slideshowOptions", "Slideshow Options…", None, "View"),
("dialog.slideshowExport", "Export Slideshow…", None, "View"),
("view.slideshow", "Slideshow", Some("Cmd+Alt+Enter"), "View>Slideshow"),
("view.slideshowOptions", "Slideshow Options…", None, "View>Slideshow"),
("dialog.slideshowExport", "Export Slideshow…", None, "View>Slideshow"),
("app.slideshowExport", "Export Slideshow", None, ""),
// the slideshow's playback controls (Space, ←/→ and Esc while it plays)
("slideshow.togglePause", "Pause / Resume Slideshow", None, ""),
@@ -204,7 +204,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[
("view.appearance", "Next Appearance Mode", None, ""),
// {theme: charcoal | midnight | silver | paper}: pick a theme and fix the mode to its family.
("view.theme", "Theme", None, ""),
("dialog.allMetadata", "All Metadata…", None, "Photo"),
("dialog.allMetadata", "All Metadata…", None, "Photo>Metadata"),
("dialog.faceModel", "Add Face Model…", None, ""),
("dialog.newSmartAlbum", "New Smart Album from Filter…", Some("Cmd+Alt+N"), "File"),
("dialog.createPreset", "Create Preset…", Some("Cmd+Shift+P"), "Photo"),
@@ -283,7 +283,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[
("app.openSamModelFolder", "Show in File Manager", None, ""),
("dialog.rename", "Rename Photos…", Some("F2"), "Photo"),
("dialog.labelNames", "Edit Color Label Names…", None, ""),
("dialog.captureTime", "Edit Capture Time…", None, "Photo"),
("photo.tagFromTracklog", "Auto-Tag from Tracklog…", None, "Photo"),
("dialog.captureTime", "Edit Capture Time…", None, "Photo>Metadata"),
("photo.tagFromTracklog", "Auto-Tag from Tracklog…", None, "Photo>Metadata"),
("app.exportPrevious", "Export with Previous", Some("Cmd+Alt+Shift+E"), "File"),
];
+2 -2
View File
@@ -1,7 +1,7 @@
use super::geometry::focus_box;
use super::{Color32, LightcraftApp, PhotoId, Pos2, Rect, Sense, Stroke, Tokens, json, pos2, register, register_geometry, vec2};
/// Draw the camera's focus box over a photo drawn in `img` (View ▸ Focus Point): green corner
/// Draw the camera's focus box over a photo drawn in `img` (View ▸ Loupe Overlay ▸ Focus Point): green corner
/// brackets with a dark keyline, the way cameras show their AF frame, never smaller than 14 pt.
/// `key` names it for tests and the control channel (`canvas:focusPoint`, `compare:focusPoint:<id>`).
pub(crate) fn draw_focus_point(p: &egui::Painter, img: Rect, photo: &lightcraft_catalog::Photo, key: &str) {
@@ -464,7 +464,7 @@ mod info_overlay_tests {
lines
}
/// View ▸ View Options: Info 1 and Info 2 each show the three lines chosen for them, in that
/// View ▸ Loupe Overlay ▸ View Options…: Info 1 and Info 2 each show the three lines chosen for them, in that
/// order, without the lines set to None.
#[test]
fn the_info_overlay_shows_the_lines_chosen_in_view_options() {
+1 -1
View File
@@ -178,7 +178,7 @@ pub fn section_drag_feedback(app: &mut LightcraftApp, ctx: &egui::Context) {
/// A section's header in `r`: a disclosure chevron in the gutter (where tree rows have their
/// chevron), then the bold title; a click folds or unfolds the section (kept in the UI state, so
/// it survives restarts), and what the section adds to its header (its button, see `header_button`) sits at
/// the visible edge. A folded section says how many rows it holds (`rows`, with View ▸ Show Photo
/// the visible edge. A folded section says how many rows it holds (`rows`, with Window ▸ Show Photo
/// Counts). `pinned`: this is the copy kept at the top of the sidebar (see `pinned_header`).
fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSection, r: Rect, rows: usize, pinned: bool) -> HeaderOutcome {
let t = Tokens::get(ui.ctx());
+2
View File
@@ -516,6 +516,8 @@ fn mask_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, id: u32, name: &str, vi
/// Overlay colours offered as swatches (the colour of the selected one is used for the tint).
pub const OVERLAY_COLORS: [[u8; 3]; 5] = [[230, 30, 40], [40, 200, 70], [40, 110, 240], [250, 210, 30], [255, 255, 255]];
/// The names of [`OVERLAY_COLORS`], in the same order (View ▸ Mask Overlay lists them).
pub const OVERLAY_COLOR_NAMES: [&str; 5] = ["Red", "Green", "Blue", "Yellow", "White"];
/// How the selected mask is shown: overlay mode, colour, opacity, pins.
fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) {
+1 -1
View File
@@ -262,7 +262,7 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) {
}
});
}
// where the camera focused, and how (View ▸ Focus Point draws it): only when known; the
// where the camera focused, and how (View ▸ Loupe Overlay ▸ Focus Point draws it): only when known; the
// whole card's width, so "AF-C · Expanded Flexible Spot · Face tracking" fits
if let Some(text) = focus_text(m.focus.as_ref()) {
ui.add_space(3.0);
+1 -1
View File
@@ -68,7 +68,7 @@ pub struct Services {
pub pick_model_file: Option<PickFiles>,
/// Open dialog for preset files (`.lcpreset`, `.xmp`, `.lrtemplate`, `.zip`, `.dng`, Luminar `.lmp` / `.mplumpack`).
pub pick_preset_files: Option<PickFiles>,
/// Open dialog for a GPS track log (`.gpx`; Photo ▸ Auto-Tag from Tracklog…).
/// Open dialog for a GPS track log (`.gpx`; Photo ▸ Metadata ▸ Auto-Tag from Tracklog…).
pub pick_tracklog: Option<PickFiles>,
/// Open dialog for a monitor ICC profile (`.icc` / `.icm`; Settings ▸ Display; desktop only).
pub pick_display_profile: Option<PickFiles>,
+2 -2
View File
@@ -50,7 +50,7 @@ pub enum Dialog {
ContactSheet {
options: lightcraft_engine::contact_sheet::Options,
},
/// View ▸ Export Slideshow…: format, size, quality, frame rate, container.
/// View ▸ Slideshow ▸ Export Slideshow…: format, size, quality, frame rate, container.
SlideshowExport {
settings: lightcraft_engine::slideshow_export::ExportSettings,
},
@@ -377,7 +377,7 @@ pub enum Dialog {
},
About,
Shortcuts,
/// View ▸ View Options (⌘J): the info overlay and the lines of Info 1 and Info 2. Changes apply
/// View ▸ Loupe Overlay ▸ View Options… (⌘J): the info overlay and the lines of Info 1 and Info 2. Changes apply
/// as they are made.
ViewOptions,
}
+4 -4
View File
@@ -166,7 +166,7 @@ pub struct AppSettings {
pub film_badges: bool,
/// Grid: when to show the rating / flag / edited badges.
pub grid_badges: GridBadges,
/// View ▸ View Options ▸ Show message when loading or rendering photos: the loupe says
/// View ▸ Loupe Overlay ▸ View Options… ▸ Show message when loading or rendering photos: the loupe says
/// "Rendering…" while the photo it shows is not the finished render.
pub loupe_messages: bool,
/// Settings ▸ Performance ▸ Prepare photos in the background, app-wide (a library may keep its
@@ -191,12 +191,12 @@ pub struct AppSettings {
/// The Keywording box: whole keyword paths, or grouped by the keyword they are inside.
#[serde(deserialize_with = "lenient")]
pub keyword_chips: KeywordChips,
/// View ▸ Focus Point: draw the box the camera focused on (`view.focusPoint`).
/// View ▸ Loupe Overlay ▸ Focus Point: draw the box the camera focused on (`view.focusPoint`).
pub focus_point: bool,
/// View ▸ Zoom to Focus Point: Toggle Zoom (Z) centres the zoomed view on the camera's focus point
/// View ▸ Loupe Overlay ▸ Zoom to Focus Point: Toggle Zoom (Z) centres the zoomed view on the camera's focus point
/// when the photo has one (`view.zoomToFocus`).
pub zoom_to_focus: bool,
/// View ▸ View Options: the lines the loupe's info overlay shows in Info 1 and Info 2.
/// View ▸ Loupe Overlay ▸ View Options…: the lines the loupe's info overlay shows in Info 1 and Info 2.
#[serde(deserialize_with = "lenient")]
pub loupe_info: LoupeInfo,
/// File ▸ Import Lightroom Catalog…: ask whether the catalog merges into the open library or
+1 -1
View File
@@ -183,7 +183,7 @@ impl InfoOverlay {
}
}
/// One line of the loupe's info overlay, chosen in View ▸ View Options (Lightroom Classic's Loupe
/// One line of the loupe's info overlay, chosen in View ▸ Loupe Overlay ▸ View Options… (Lightroom Classic's Loupe
/// Info 1 / Loupe Info 2). A line with nothing to show for a photo is left out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
+3 -3
View File
@@ -1,4 +1,4 @@
//! Headless tests of the camera's focus point (#1480): View ▸ Focus Point draws the box where the
//! Headless tests of the camera's focus point (#1480): View ▸ Loupe Overlay ▸ Focus Point draws the box where the
//! camera focused, through the user's rotation and crop; Toggle Zoom (Z) centres on it; the Info panel
//! names the focus mode.
@@ -158,7 +158,7 @@ fn compare_and_survey_draw_each_photos_focus_point() {
}
/// A photo imported before focus points were read gets its point from the background reader the frame loop drives
/// (`focus.pump`, started by itself once the library is open), and Photo ▸ Read Focus Points runs it on demand.
/// (`focus.pump`, started by itself once the library is open), and Photo ▸ Metadata ▸ Read Focus Points runs it on demand.
#[test]
fn the_frame_loop_reads_focus_points_for_photos_imported_earlier() {
let dir = std::env::temp_dir().join(format!("lc-ui-focus-scan-{}", std::process::id()));
@@ -181,7 +181,7 @@ fn the_frame_loop_reads_focus_points_for_photos_imported_earlier() {
// a photo added later is read when asked (the menu item runs the command)
add(&mut h.app, 9002, "later.ARW");
let spec = h.app.session.commands().into_iter().find(|c| c.id == "photo.readFocusPoints").expect("the command");
assert_eq!(spec.menu, vec!["Photo"]);
assert_eq!(spec.menu, vec!["Photo", "Metadata"]);
let r = run(&mut h, "photo.readFocusPoints", json!({}));
assert_eq!(r["queued"], 1, "{r}");
assert!(h.step_until(SETTLE, |h| has_point(h, 9002)));
+14 -8
View File
@@ -291,18 +291,18 @@ fn exec(h: &mut Headless, command: &str, params: serde_json::Value) -> serde_jso
r["result"].clone()
}
/// The View ▸ Sidebar Sections items: (section id or command, checked).
/// The Window ▸ Sidebar Sections items: (section id or command, checked).
fn sidebar_menu_items(h: &Headless) -> Vec<(String, Option<bool>)> {
use crate::menubar::MenuNode;
let bar = crate::menubar::menu_bar(&h.app);
let view = &bar.iter().find(|(t, _)| t == "View").expect("View menu").1;
let children = view
let window = &bar.iter().find(|(t, _)| t == "Window").expect("Window menu").1;
let children = window
.iter()
.find_map(|n| match n {
MenuNode::Submenu { label, children } if label == "Sidebar Sections" => Some(children.clone()),
_ => None,
})
.expect("View ▸ Sidebar Sections");
.expect("Window ▸ Sidebar Sections");
children
.iter()
.filter_map(|n| match n {
@@ -312,11 +312,11 @@ fn sidebar_menu_items(h: &Headless) -> Vec<(String, Option<bool>)> {
.collect()
}
/// Given the sidebar, when a section is unchecked in View ▸ Sidebar Sections, then it leaves the
/// Given the sidebar, when a section is unchecked in Window ▸ Sidebar Sections, then it leaves the
/// sidebar (header and rows) and the menu shows it unchecked; checking it again brings it back
/// as it was. The choice is part of the saved UI state.
#[test]
fn a_section_is_hidden_and_shown_from_the_view_menu() {
fn a_section_is_hidden_and_shown_from_the_window_menu() {
let mut h = demo([1400.0, 1400.0], json!({"view": "photoGrid", "leftPanel": true}));
let checked = |h: &Headless, id: &str| sidebar_menu_items(h).into_iter().find(|(s, _)| s == id).unwrap_or_else(|| panic!("no {id} item")).1;
assert_eq!(checked(&h, "byDate"), Some(true));
@@ -2517,7 +2517,8 @@ fn local_photos_cannot_be_added_to_albums_until_they_join_my_photos() {
assert_eq!(r["ok"], true, "{r}");
h.step();
// Photo ▸ Add to Album: the hint item first (off), the album and New Album… off
// Photo ▸ Add to Album: the album and New Album… off, and Add to My Photos is not repeated in it: the Photo
// menu's own item, right below the submenu, is the one row for that command (on for a Local photo)
let add_to_album = |app: &LightcraftApp| -> Vec<crate::menubar::MenuNode> {
let bar = crate::menubar::menu_bar(app);
let photo = &bar.iter().find(|(t, _)| t == "Photo").expect("Photo menu").1;
@@ -2536,7 +2537,12 @@ fn local_photos_cannot_be_added_to_albums_until_they_join_my_photos() {
})
};
let nodes = add_to_album(&h.app);
assert!(matches!(nodes.first(), Some(crate::menubar::MenuNode::Item { id, enabled: false, .. }) if id == "photo.addToLibrary"), "{nodes:?}");
assert_eq!(enabled_of(&nodes, "photo.addToLibrary"), None, "{nodes:?}");
let bar = crate::menubar::menu_bar(&h.app);
let photo = &bar.iter().find(|(t, _)| t == "Photo").expect("Photo menu").1;
let rows = photo.iter().filter(|n| matches!(n, crate::menubar::MenuNode::Item { id, .. } if id == "photo.addToLibrary")).count();
assert_eq!(rows, 1, "one Add to My Photos row in the Photo menu: {photo:?}");
assert_eq!(enabled_of(photo, "photo.addToLibrary"), Some(true), "{photo:?}");
assert_eq!(enabled_of(&nodes, "album.addPhotos"), Some(false), "{nodes:?}");
assert_eq!(enabled_of(&nodes, "dialog.newAlbum"), Some(false), "{nodes:?}");
+161
View File
@@ -318,5 +318,166 @@ impl WindowWatch {
}
}
/// How long after the window first shows it is maximized (Windows): a frame or two, so that it is on
/// its screen and the system maximizes it to that screen's work area.
const MAXIMIZE_AFTER_SECONDS: f64 = 0.1;
/// How long after asking the window is checked: the system animates a maximize.
const MAXIMIZE_CHECK_SECONDS: f64 = 0.6;
/// A maximized window this much of its screen across, and down, fills it (the taskbar, and the
/// borders Windows keeps off screen, take the rest).
const MAXIMIZED_ACROSS: f32 = 0.9;
const MAXIMIZED_DOWN: f32 = 0.75;
/// `zoom` when it is a usable interface zoom, else 1.
fn interface_zoom(zoom: f32) -> f32 {
if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 }
}
/// The window's minimum in the system's points: [`MIN_SIZE`] is in the interface's, which `zoom` scales (at 2× a
/// 900 × 560 minimum holds the window to 1800 × 1120).
fn native_min(zoom: f32) -> [f32; 2] {
[MIN_SIZE[0] * zoom, MIN_SIZE[1] * zoom]
}
/// When the window's minimum (at `zoom`) is larger than `room` (system points) on either side: the command that lowers
/// it to `room`, in the interface's points. Nothing when the minimum fits.
fn min_within(room: [f32; 2], zoom: f32) -> Vec<egui::ViewportCommand> {
let min = native_min(zoom);
if min[0] > room[0] || min[1] > room[1] {
let lowered = [min[0].min(room[0]), min[1].min(room[1])];
return vec![egui::ViewportCommand::MinInnerSize(egui::vec2(lowered[0] / zoom, lowered[1] / zoom))];
}
Vec::new()
}
/// A window opened larger than its screen is fitted to this much of it.
const FIT_TO_SCREEN: f32 = 0.9;
/// How long after its first frame the window is placed at most: one that stays unseen, full
/// screen or minimized that long is left as it is.
const PLACE_WITHIN_SECONDS: f64 = 5.0;
/// The window as it first shows. On Windows a window built maximized could open
/// covering half the screen while the system took it for maximized: its maximize button then
/// restored it, smaller. So there it opens at its remembered size and is maximized once it is on its
/// screen ([`StartPlace::new`] with `maximize_after`); if it then says it is maximized but doesn't
/// fill its screen, it is restored and maximized again, once. A window remembered larger than the
/// screen it opens on (a display unplugged, a smaller one, another scale) is fitted to that screen.
#[derive(Debug)]
pub struct StartPlace {
/// Maximize once the window shows.
maximize: bool,
/// When it was asked to (seconds), and whether it has been asked again.
asked: Option<f64>,
retried: bool,
/// When the window first showed, and when it was first looked at.
shown: Option<f64>,
first_step: Option<f64>,
done: bool,
/// The size it was remembered at (system points), before the system or eframe fitted it to its screen.
remembered: Option<[f32; 2]>,
}
impl StartPlace {
/// `maximize_after`: the window was built at its size and should be maximized once it shows.
pub fn new(maximize_after: bool) -> StartPlace {
StartPlace { maximize: maximize_after, asked: None, retried: false, shown: None, first_step: None, done: false, remembered: None }
}
/// The size the window was remembered at and built with (`size`, system points): a window remembered larger
/// than its screen is fitted to it even when it was clamped to the whole screen before it was first seen
/// (eframe clamps a remembered 1600 × 1000 to a 1280 × 720 screen).
pub fn remembered(mut self, size: Option<[f32; 2]>) -> StartPlace {
self.remembered = size.filter(|s| s.iter().all(|v| v.is_finite()));
self
}
/// Whether there is nothing more to do.
pub fn done(&self) -> bool {
self.done
}
/// The window is `seen` at time `now` (seconds), with the interface zoomed by `zoom`: what to
/// tell it.
pub fn step(&mut self, seen: &Seen, now: f64, zoom: f32) -> Vec<egui::ViewportCommand> {
if self.done {
return Vec::new();
}
// (not shown yet, its screen unknown, full screen or minimized: wait, but not for ever)
if self.out_of_time(now) {
return Vec::new();
}
if seen.full_screen || seen.minimized {
return Vec::new();
}
let (Some(size), Some(screen)) = (seen.size, seen.screen) else { return Vec::new() };
let shown = *self.shown.get_or_insert(now);
if !self.maximize {
self.done = true;
// remembered larger than this screen: fitted to it, and never larger than it (a screen smaller than
// the window's minimum lowers the minimum to the screen)
let larger = |s: [f32; 2]| s[0] > screen[0] + SAME_WITHIN || s[1] > screen[1] + SAME_WITHIN;
if !seen.zoomed && (larger(size) || self.remembered.is_some_and(larger)) {
// (`seen` is in the system's points, the commands in the interface's)
let zoom = interface_zoom(zoom);
let min = native_min(zoom);
let side = |i: usize| (screen[i] * FIT_TO_SCREEN).max(min[i]).min(screen[i]);
let fit = [side(0), side(1)];
// a minimum larger than the fitted size (a small screen, a zoomed interface) is lowered to it first
let mut told = min_within(fit, zoom);
told.push(egui::ViewportCommand::InnerSize(egui::vec2(fit[0] / zoom, fit[1] / zoom)));
return told;
}
return Vec::new();
}
let fills = size[0] >= screen[0] * MAXIMIZED_ACROSS && size[1] >= screen[1] * MAXIMIZED_DOWN;
match self.asked {
None if now - shown >= MAXIMIZE_AFTER_SECONDS => {
self.asked = Some(now);
// a screen smaller than the window's minimum lowers it first, or the maximized window would stay wider
let mut told = min_within(screen, interface_zoom(zoom));
told.push(egui::ViewportCommand::Maximized(true));
told
}
None => Vec::new(),
Some(at) if now - at < MAXIMIZE_CHECK_SECONDS => Vec::new(),
Some(_) if seen.zoomed && fills => {
self.done = true;
Vec::new()
}
Some(_) if !self.retried => {
// maximized in name only (or not at all): restore it, and maximize it again
self.retried = true;
self.asked = Some(now);
vec![egui::ViewportCommand::Maximized(false), egui::ViewportCommand::Maximized(true)]
}
Some(_) => {
self.done = true;
Vec::new()
}
}
}
/// A pass with nothing to place by (the window is hidden: its size is stale) at time `now`: the time limit
/// still runs, so a window kept hidden ends the placement and stops asking to be looked at.
pub fn idle(&mut self, now: f64) {
if !self.done {
self.out_of_time(now);
}
}
/// Whether placing has gone on for longer than it may (it is then done); its clock starts at the first pass.
fn out_of_time(&mut self, now: f64) -> bool {
let first = *self.first_step.get_or_insert(now);
if now - first > PLACE_WITHIN_SECONDS {
self.done = true;
}
self.done
}
/// When to look again while it waits (the app may have nothing else to draw).
pub fn waits(&self) -> Option<std::time::Duration> {
(!self.done).then(|| std::time::Duration::from_millis(100))
}
}
#[cfg(test)]
mod tests;
+110
View File
@@ -592,3 +592,113 @@ fn what_was_remembered_is_checked_and_never_costs_the_other_settings() {
assert_eq!(place(size, false).checked(), None, "{size:?}");
}
}
/// On Windows the window opens at its size and is maximized once it shows; a
/// window that says it is maximized but covers half its screen is restored and maximized again,
/// once; a window remembered larger than its screen is fitted to it.
#[test]
fn the_window_is_maximized_once_it_shows_and_again_if_it_only_says_so() {
use egui::ViewportCommand as C;
let mut s = StartPlace::new(true);
assert!(s.step(&Seen::default(), 0.0, 1.0).is_empty(), "not shown yet");
assert!(s.step(&window([1300.0, 800.0]), 0.0, 1.0).is_empty(), "a frame first");
assert_eq!(s.step(&window([1300.0, 800.0]), 0.2, 1.0), vec![C::Maximized(true)]);
assert!(s.step(&window([1300.0, 800.0]), 0.3, 1.0).is_empty(), "the system animates");
// maximized in name, half the screen: once more
let half = Seen { zoomed: true, ..window([1280.0, 1400.0]) };
assert_eq!(s.step(&half, 1.0, 1.0), vec![C::Maximized(false), C::Maximized(true)]);
let full = Seen { zoomed: true, ..window([2560.0, 1392.0]) };
assert!(s.step(&full, 1.2, 1.0).is_empty());
assert!(s.step(&full, 1.7, 1.0).is_empty() && s.done());
assert_eq!(s.waits(), None);
// it filled its screen the first time: nothing more
let mut s = StartPlace::new(true);
s.step(&window([1300.0, 800.0]), 0.0, 1.0);
s.step(&window([1300.0, 800.0]), 0.2, 1.0);
assert!(s.step(&full, 1.0, 1.0).is_empty() && s.done());
// never more than one retry
let mut s = StartPlace::new(true);
s.step(&window([1300.0, 800.0]), 0.0, 1.0);
s.step(&window([1300.0, 800.0]), 0.2, 1.0);
assert_eq!(s.step(&half, 1.0, 1.0).len(), 2);
assert!(s.step(&half, 2.0, 1.0).is_empty() && s.done());
// not to be maximized: a window larger than its screen is fitted to it
let mut s = StartPlace::new(false);
let big = Seen { size: Some([3000.0, 2000.0]), screen: Some([1920.0, 1080.0]), ..Default::default() };
assert_eq!(s.step(&big, 0.0, 1.0), vec![C::InnerSize(egui::vec2(1728.0, 972.0))]);
assert!(s.done() && s.step(&big, 1.0, 1.0).is_empty());
let mut s = StartPlace::new(false);
assert!(s.step(&window([1300.0, 800.0]), 0.0, 1.0).is_empty() && s.done());
// full screen or minimized: left alone
let mut s = StartPlace::new(true);
assert!(s.step(&Seen { full_screen: true, ..window([2560.0, 1440.0]) }, 1.0, 1.0).is_empty());
// ... but not for ever: it stops asking for frames
assert!(s.step(&Seen { full_screen: true, ..window([2560.0, 1440.0]) }, 6.5, 1.0).is_empty());
assert!(s.done() && s.waits().is_none());
// a window that never says its size or screen is given up on too
let mut s = StartPlace::new(true);
assert!(s.step(&Seen::default(), 0.0, 1.0).is_empty());
assert!(s.step(&Seen::default(), 5.5, 1.0).is_empty() && s.done());
// the interface zoomed 2×: the fitted size is asked for in its points, half the system's
let mut s = StartPlace::new(false);
// (its 900 × 560 minimum is 1800 × 1120 there, taller than the 1080 screen: lowered to the fitted size first)
assert_eq!(s.step(&big, 0.0, 2.0), vec![C::MinInnerSize(egui::vec2(900.0, 540.0)), C::InnerSize(egui::vec2(900.0, 540.0))]);
}
/// A screen smaller than the window's minimum (800 × 600 beside a 900 pt minimum): the window is fitted within it
/// and the minimum is lowered to it, so it never asks for more than the screen (CodeRabbit on #2974).
#[test]
fn a_window_on_a_screen_smaller_than_its_minimum_fits_within_the_screen() {
use egui::ViewportCommand as C;
let mut s = StartPlace::new(false);
let small = Seen { size: Some([900.0, 560.0]), screen: Some([800.0, 600.0]), ..Default::default() };
assert_eq!(s.step(&small, 0.0, 1.0), vec![C::MinInnerSize(egui::vec2(800.0, 560.0)), C::InnerSize(egui::vec2(800.0, 560.0))]);
// remembered maximized on that screen: the minimum is lowered before it is maximized, or it would stay wider
let mut s = StartPlace::new(true);
s.step(&small, 0.0, 1.0);
assert_eq!(s.step(&small, 0.2, 2.0), vec![C::MinInnerSize(egui::vec2(400.0, 300.0)), C::Maximized(true)]);
// a screen larger than the minimum, but not than the minimum the zoomed interface makes of it (CodeRabbit on #2974)
let mut s = StartPlace::new(true);
let laptop = Seen { size: Some([1100.0, 700.0]), screen: Some([1200.0, 800.0]), ..Default::default() };
s.step(&laptop, 0.0, 2.0);
assert_eq!(s.step(&laptop, 0.2, 2.0), vec![C::MinInnerSize(egui::vec2(600.0, 400.0)), C::Maximized(true)]);
let mut s = StartPlace::new(false);
let wide = Seen { size: Some([1600.0, 1000.0]), ..laptop };
assert_eq!(s.step(&wide, 0.0, 2.0), vec![C::MinInnerSize(egui::vec2(600.0, 400.0)), C::InnerSize(egui::vec2(600.0, 400.0))]);
// a screen the minimum fits on keeps the minimum
let mut s = StartPlace::new(true);
s.step(&window([1300.0, 800.0]), 0.0, 1.0);
assert_eq!(s.step(&window([1300.0, 800.0]), 0.2, 1.0), vec![C::Maximized(true)]);
let mut s = StartPlace::new(false);
let big = Seen { size: Some([3000.0, 2000.0]), screen: Some([1920.0, 1080.0]), ..Default::default() };
assert_eq!(s.step(&big, 0.0, 1.0), vec![C::InnerSize(egui::vec2(1728.0, 972.0))]);
}
/// eframe clamps a remembered 1600 × 1000 window to a 1280 × 720 screen before it is first seen: the remembered
/// size still has it fitted to 90 % of the screen, not left covering all of it (CodeRabbit on #2974).
#[test]
fn a_window_clamped_to_its_screen_before_it_shows_is_still_fitted() {
use egui::ViewportCommand as C;
let clamped = Seen { size: Some([1280.0, 720.0]), screen: Some([1280.0, 720.0]), ..Default::default() };
let mut s = StartPlace::new(false).remembered(Some([1600.0, 1000.0]));
assert_eq!(s.step(&clamped, 0.0, 1.0), vec![C::InnerSize(egui::vec2(1152.0, 648.0))]);
// remembered within the screen: left as it is
let mut s = StartPlace::new(false).remembered(Some([1200.0, 700.0]));
assert!(s.step(&clamped, 0.0, 1.0).is_empty() && s.done());
// nothing remembered: as before
let mut s = StartPlace::new(false);
assert!(s.step(&clamped, 0.0, 1.0).is_empty());
}
/// A window kept hidden while it is being placed still ends the placement in time, and then stops asking to be
/// looked at (CodeRabbit on #2974).
#[test]
fn placement_ends_in_time_while_the_window_is_hidden() {
let mut s = StartPlace::new(true);
s.idle(0.0);
assert!(!s.done() && s.waits().is_some(), "still within its time");
s.idle(PLACE_WITHIN_SECONDS + 0.1);
assert!(s.done());
assert_eq!(s.waits(), None);
assert!(s.step(&window([1300.0, 800.0]), PLACE_WITHIN_SECONDS + 0.2, 1.0).is_empty());
}
+57
View File
@@ -0,0 +1,57 @@
# Catalog persistence
The catalog is two files in the library folder (`crates/catalog/src/journal.rs`): `catalog.snap`, a JSON snapshot of
the whole catalog, and `catalog.log`, one JSON line per change made since. Every change is handed to the log before
its command returns; natively the log's own thread writes and fsyncs it right after, so appending a change never waits for the
drive (a write that fails is held and retried, and switching the library or quitting waits for it). `library.compact` does
wait: it writes and syncs its snapshot before it returns, and the first snapshot after a deferred upgrade copies the files
it keeps on the caller's thread. Now and then the log is
compacted into a new snapshot. This page covers what happens to a library's files when a newer version opens it.
## Going back to an older version
Opening a library saved in an older catalog format with a newer LightCraft rewrites it in that version's format, and
versions that don't know that format then refuse it (safely: they say so and change nothing). So that this is not a
one-way step, the upgrade first keeps the files the library was, byte for byte, beside it:
- `catalog.snap.v<format>-<seq>` and `catalog.log.v<format>-<seq>`, where `<format>` is the format they are in and
`<seq>` the number of the last change the library held when it was upgraded (or, where the upgrade was left for a
later snapshot, when the library was opened; a library that had no log, or only a log, has only the one file). `Journal::open` reports their names (`LoadReport::kept`) and logs them.
A file already there under such a name is never replaced or removed (a library restored from an older backup can reach
the same format and change as a set kept before): if it holds other bytes, the new files are kept as `…-2` (then
`-3`, and so on, up to 100 sets, after which the upgrade is refused) instead, both alike; if it holds the same bytes, it is the copy already.
- The files kept at open stay unless the library is known to be in its old format still, because the upgrade at open
did not happen (then the files that open wrote are removed again; a copy kept earlier stays): once the upgrade is written, nothing that fails
after it takes them away. The files a later snapshot keeps (below) stay too, even if that snapshot then fails and
the library is still in its old format.
- A library whose files can't be kept, or whose upgrade can't be written (a full disk, a folder that can't be written
to), is not upgraded: it opens as it is, with no copy of this attempt left lying about, and the next open tries again. If what is on
disk after a failed write can't be read back to say whether the upgrade was written, the library is refused instead
(its way back stays). A library left like that is upgraded by its next snapshot, during the session or when it is
closed, and that snapshot keeps the files first too (and is not written when they can't be kept). When a snapshot
during the session does that, LightCraft tells where the files are kept, as it does at open (a snapshot when the
library is closed, or switched away from in Settings, has no one left to tell: the files are in the folder, named
as above). The files kept are the library as it was when it opened (the snapshot, and the log up to where it ended
then): what was changed since is in the files that replace them, not in the kept ones. (An earlier session of this
version may have added changes while the library stayed in its old format: they are in the log it opened with, and
an older version may refuse them.) Until then, changes
go on being appended to the library as it is, so that they can be saved at all where there is no room for a copy of
its files. (If the session ends without that snapshot, the next open keeps the log as it is then, which holds
those changes, and tells so; the files kept earlier stay beside it.)
- A library whose log was damaged is upgraded like any other. What it was is then its snapshot, kept under the name
above, and its log, kept as `catalog.log.damaged-<seq>`: the snapshot alone is the library without the changes
that log held. If the snapshot can't be kept, the library is refused and left as it was; if the damaged log can't
be replaced after the upgrade was written, it is refused too, and its way back (the kept snapshot and
`catalog.log.damaged-<seq>`) stays (changes made in it would be appended after the damage, where the next open
would not read them).
- Nothing removes the kept files. They are as large as the library was; LightCraft says so once when it has upgraded
a library (and `library.info` lists it under `settingsWarnings`). Delete them once the older version is no longer
wanted. The browser build keeps none (it always runs the newest version).
**To go back**, with LightCraft closed: move `catalog.snap` and `catalog.log` away, then rename each kept file that exists
to `catalog.snap` and `catalog.log` (a library that had no log, or only a log, kept only the one file: rename only that
one, and leave the other name unused). Where the log was damaged, the kept log is `catalog.log.damaged-<seq>`: it takes
the place of `catalog.log` like any kept log (the older version reads it up to the damage and handles it as it did
before), beside the kept snapshot when there is one. The older version opens the library as it was when it was upgraded (where the upgrade came
from a later snapshot: as it was when it was opened, so the changes made between that and the upgrade are not carried
back either); changes made since, in the newer version, are in the files that were moved away.
+1 -1
View File
@@ -119,7 +119,7 @@ filmstrip is visible.
| `engine.execute {command: "slideshow.templates.import"}` / `export` | `{path}` / `{id, path}` | Import a template `.json` (at most 256 KB; format, version and every setting checked; a taken name gets " (2)") → `{id, name, renamed, warnings}`; export any template as `.json` |
| `engine.execute {command: "slideshow.export"}` | `{format: "pdf"\|"jpeg"\|"video", path, size?, quality?, fps?, container?: "mp4"\|"webm", fullScreen?, speed?, name?, ids?, wait?}` | The slideshow (the photos in view, or `ids`, as composed slides between the intro and ending screens that are on) as a PDF (one page per slide; `size` = long side 64–8192 px, default 1920), a JPEG sequence (`path` = the folder, files `<name>-001.jpg`…) or AV1 video in MP4 / WebM (`size` = frame height 64–2160 or `"720p"` / `"1080p"`, `fps` 24 / 25 / 30 / 60; fades rendered as frames; no audio; at most 2 hours). Runs in the background → `{taskId, background, slides, seconds, total, width, height, warnings}`; its row is in `activity.list` (`kind: "export"`, label "Exporting slideshow"), `activity.cancel {id: taskId}` stops it and leaves no file (outputs are written as `.part` and renamed when complete). `wait: true` runs it in the call and replies with the result. One at a time |
| `engine.execute {command: "slideshow.exportStatus"}` | — | The last slideshow export: `{taskId, format, path, running, done, total, cancelled, result?, error?}`; `result` has `pages` (PDF), `files` (JPEG) or `frames`, `samples`, `keyFrames`, `seconds`, `fps`, `container`, `codec: "av1"`, `audio: false` (video), and `skipped` / `warnings` for photos that could not be rendered |
| `engine.execute {command: "dialog.slideshowExport"}` / `app.slideshowExport` | `{format?}` / `{format, size?, quality?, fps?, container?, fullScreen?, path?}` | View ▸ Export Slideshow…: opens the dialog; `app.slideshowExport` asks for the path with a save dialog when none is given, then starts `slideshow.export` |
| `engine.execute {command: "dialog.slideshowExport"}` / `app.slideshowExport` | `{format?}` / `{format, size?, quality?, fps?, container?, fullScreen?, path?}` | View ▸ Slideshow ▸ Export Slideshow…: opens the dialog; `app.slideshowExport` asks for the path with a save dialog when none is given, then starts `slideshow.export` |
| `app.quit` | — | Close the app |
White balance (`develop.set` with `wb.temp` / `wb.tint`, `develop.wb`, `develop.wbPick`) is in Kelvin and tint on
+4 -4
View File
@@ -11,7 +11,7 @@ No model weights are part of LightCraft. Each one is a file you choose to get, f
- **Face detection:** [YuNet](https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet) (232 KB, MIT).
It runs in LightCraft's own code, with no extra runtime. It was trained on the WIDER FACE dataset; an MIT licence on
weights does not settle that dataset's terms, so this is flagged for the maintainer. It finds faces; it does not
identify anyone. **Photo ▸ Detect Faces** offers the download the first time you use it.
identify anyone. **Photo ▸ Metadata ▸ Detect Faces** offers the download the first time you use it.
- **Face recognition models** are large (AuraFace is 261 MB), and their licences and training data deserve a decision by
the person installing them. Everything works without one: names from XMP, the People view, the face boxes.
- **Recognition runs in LightCraft's own pure-Rust CPU interpreter**, shared with the detector. Dense
@@ -39,7 +39,7 @@ does check is listed under "Agreement and regression coverage".
## Downloading a model
**Settings ▸ Faces ▸ Download** (or Photo ▸ Detect Faces, which offers it for the detector):
**Settings ▸ Faces ▸ Download** (or Photo ▸ Metadata ▸ Detect Faces, which offers it for the detector):
1. A dialog shows the model's licence, whether commercial use is allowed, what it was trained on (or that this is not
known) and which site the file comes from. **Download stays disabled until you tick "I have read these terms and
@@ -226,7 +226,7 @@ a ResNet-100 (so it is not the accuracy choice its size suggests). InsightFace's
## Finding faces yourself
**Photo ▸ Detect Faces** (`faces.detect`) runs the YuNet detector on the selected photos and adds what it finds as
**Photo ▸ Metadata ▸ Detect Faces** (`faces.detect`) runs the YuNet detector on the selected photos and adds what it finds as
unnamed face boxes, in one undo step. A new run replaces earlier detections; boxes that came from XMP, or that you drew or
named, are never touched (and a face that already has one is not boxed a second time), and no sidecar is written. It looks at the photo upright and uncropped with default settings,
so your edits and crops do not matter. `apply: false` only reports. It finds faces of about 10 pixels and up in a
@@ -248,7 +248,7 @@ suggest names for the ones you have not:
- **Nothing is ever named for you.** A suggestion is only a label until you confirm it, and a suggestion appears only when
the match is strong *and* clearly ahead of the next person: it is better to leave a face unnamed than to name it wrongly.
Naming a face also makes it one of the faces the others are compared with, so the suggestions improve as you go.
- Faces come from the names other apps wrote into your photos (read from XMP), from Photo ▸ Detect Faces, or both. A face is
- Faces come from the names other apps wrote into your photos (read from XMP), from Photo ▸ Metadata ▸ Detect Faces, or both. A face is
aligned using the detector's five landmarks (eyes, nose, mouth corners) when it finds the same face, and cut out by its box
otherwise.
- Everything stays on your computer. The embeddings (one short list of numbers per face) are cached in the library folder in
+3 -3
View File
@@ -6,10 +6,10 @@ zooms to it, so checking whether the subject is sharp takes one key while cullin
## Using it
- **View ▸ Focus Point** (⌥F; `view.focusPoint {on?}`) draws the camera's AF frame as green corner brackets in
- **View ▸ Loupe Overlay ▸ Focus Point** (⌥F; `view.focusPoint {on?}`) draws the camera's AF frame as green corner brackets in
Detail, Compare and Survey. It follows Rotate, flips and the crop; a point cropped away is not drawn. Off by
default; the choice is saved with the app's settings.
- **View ▸ Zoom to Focus Point** (`view.zoomToFocus {on?}`, on by default): Toggle Zoom (Z or Space) zooms in
- **View ▸ Loupe Overlay ▸ Zoom to Focus Point** (`view.zoomToFocus {on?}`, on by default): Toggle Zoom (Z or Space) zooms in
centred on the focus point instead of the last position. A click on the photo still zooms where you click, and a
photo without a focus point zooms as before. On by default because it changes nothing for photos without a point,
and for those with one the focus point is what a 1:1 check is for. In Compare the two panes share one pan, so Z
@@ -29,7 +29,7 @@ unchanged (no catalog format change).
A library imported before focus points were read gets them by itself: when a library opens and some of its photos
from a supported body have no point and haven't been looked at, LightCraft reads them in the background, with a
**Reading focus points** row in the activity stack (n of N; ✕ stops it). **Photo ▸ Read Focus Points**
**Reading focus points** row in the activity stack (n of N; ✕ stops it). **Photo ▸ Metadata ▸ Read Focus Points**
(`photo.readFocusPoints`) starts the same job by hand. Photo ▸ Reload from Disk still fills a missing point too, but it
re-reads and hashes whole files and runs while you wait, so it is for a few photos, not a library.
+22 -19
View File
@@ -54,13 +54,13 @@ every PR would edit and conflict on. A row marked ✅ that is wrong or incomplet
| U. Map & location (MAP) | 0 | 1 | 1 | 0 | — | 0/1 (0%) |
| V. Preferences (PREF) | 6 | 2 | 2 | 2 | 1/1 (100%) | 4/5 (80%) |
| W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — |
| X. Cross-cutting behaviours (BEHAV) | 22 | 7 | 1 | 1 | 7/8 (88%) | 7/10 (70%) |
| X. Cross-cutting behaviours (BEHAV) | 22 | 8 | 1 | 1 | 7/8 (88%) | 7/10 (70%) |
| Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) |
| Z. Keyboard shortcuts (desktop) | 77 | 5 | 2 | 1 | 49/52 (94%) | 24/26 (92%) |
| Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) |
| **Total** | 417 | 73 | 56 | 35 | 192/203 (95%) | 146/163 (90%) |
| **Total** | 417 | 74 | 56 | 35 | 192/203 (95%) | 146/163 (90%) |
Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 546 in-scope rows — P0 97.3% of 203 · P1 93.9% of 163 · P2 57.0% of 179.
Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.0%** of 547 in-scope rows — P0 97.3% of 203 · P1 93.9% of 163 · P2 56.9% of 180.
<!-- /parity:summary -->
## Top gaps and shortcut notes
@@ -102,7 +102,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-LIB-BYDATE | Browse by date | P1 | ✅ | `cmd:library.filter` (`date`), `crates/ui-egui/src/panels/left.rs` (`date_row`), `crates/catalog/src/query.rs` (`date_groups`) | year → month → day tree with library-wide counts; a row filters the current source by that date. Active filters show as removable chips under the grid header (`crates/ui-egui/src/panels/chips.rs`, with “+N more” and Clear all), the header counts “N of M photos” (matching of the source's total), a badge on the top-bar filter icon counts them, and an empty result says no photos match the active filters |
| LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests/albums_local.rs`, `crates/ui-egui/src/tests/panels.rs`, `crates/ui-egui/src/tests/drag_contract.rs` | photos dragged from the grid onto an album row are added to it: the dragged label says how many it adds, and the toast how many were there already (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:<id>`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder); album commands only take photos the library has (`album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` drop ids it lacks) and `album.addPhotos` with nothing to add (all photos already in, or none left) records no undo step and leaves redo alone; `album.toggleTarget` with none left changes nothing (`added` is null, no toast) |
| LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests/panels.rs` | Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:<id>`; the row folds them too; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) |
| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; an edit to a few photos is followed photo by photo (a keyword created in the keyword list too: no rule reads the list), and a count of every photo (an album's rules or photos changed, a stack, an edit to more than 256 photos) runs on a worker thread while the sidebar keeps the counts it showed (none before the first count), so the window doesn't freeze; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once |
| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; an edit to a few photos is followed photo by photo (a keyword created in the keyword list too: no rule reads the list), and a count of every photo (an album's rules or photos changed, a stack, an edit to more than 256 photos) runs on a worker thread while the sidebar keeps the counts it showed (none before the first count), so the window doesn't freeze; View ▸ Sort ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once |
| LR-LIB-SHARED-ALBUM | Shared albums | P2 | ⬜ | | needs a sharing service |
| LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library |
| LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS |
@@ -110,7 +110,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-LIB-FLAG | Pick / reject flags | P0 | ✅ | `cmd:photo.pick`, `cmd:photo.reject`, `cmd:photo.unflag`, `cmd:photo.flag`, `crates/ui-egui/src/thumb.rs` | a rejected photo is dimmed on the grids and on the filmstrip, under its marks (the flag keeps its red); P pick, X reject, U clear; a flag or rating never waits for the drive: the catalog log is written and synced by a thread of its own, a failed write is held, retried and counted as unsaved (`crates/catalog/src/log_writer.rs`, PERF-STEP-STALL); Shift+P picks and advances in both grids (Presets elsewhere); Shift+X/U and legacy Shift+Z advance; no flag cycle; rejection does not delete the file; a pick shows as a filled flag on thumbnails, in Compare, in the loupe and on the Pick button, a reject outlined (#1013) |
| LR-LIB-LABEL | Colour labels | P1 | ✅ | `cmd:photo.label`, `cmd:photo.clearLabel`, `cmd:label.setNames`, `cmd:label.names`, `cmd:dialog.labelNames`, keys 6–9 in `crates/ui-egui/src/shortcuts.rs`, `crates/ui-egui/src/thumb.rs` | Photo menu and grid context menu (coloured, named), Info-panel swatches, the label is a dot in the marks row on every surface (justified grid, square grid, filmstrip) plus translucent colour on the square-grid and filmstrip surrounds; nothing is laid over the photo's pixels (the justified grid's tinted footer band is gone). On the justified grid, which has no surround, the dot is kept before the stars and flag on a narrow photo and stays when Ratings & flags is Never; elsewhere the surround says the label; colour-label toasts have pale matching backgrounds; setting/clearing through keys (including Shift), menus or Info swatches shows the same bottom toast as ratings, with the colour/custom name; editable label names (undoable, journaled); no purple key (as in Lightroom), Clear Color Label (`photo.clearLabel`) has no key until one is given in Help → Keyboard Shortcuts, no custom extra labels |
| LR-LIB-KEYWORD | Keywords | P0 | ✅ | `cmd:panel.keywords`, `cmd:photo.setMeta` (`addKeywords`/`removeKeywords`), `cmd:keyword.list`, `cmd:keyword.rename`, `cmd:keyword.delete`, `cmd:keyword.merge`, `cmd:keyword.suggest`, `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/left.rs` | left-panel keyword tree with counts (click filters, children included; context menu rename / merge / delete / add / remove); library-wide ops are one undo step and replay from the op log; suggestions (co-occurring / most used / completions) in the Keywords panel; keywords reorganize by drag and drop in the Keyword List (LRC-LIB-KEYWORDS) |
| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging, no writing regions back |
| LR-LIB-PEOPLE | People / faces | P2 | 🟡 | `cmd:faces.detect`, `cmd:view.people`, `cmd:view.faceBoxes`, `cmd:photo.removeRegion`, `cmd:photo.setRegion`, `cmd:library.filter`, `crates/ui-egui/src/panels/people.rs`, `crates/catalog/src/query.rs` (`people`), `crates/engine/src/media.rs` (`face_job`), `crates/meta/src/xmp.rs` | MVP: named face regions read from XMP (MWG-RS, read-only, see `docs/xmp-interop.md`; clipped to the photo; Lightroom's `Rotation` of ±π/2 and π handled, mirrored orientations taken as written; boxes follow Rotate Left/Right and flips; a sidecar stating `mwg-rs:Regions`, even empty, replaces the photo's on re-read, one without leaves them) become cards in the People view (View ▸ People, or the People button in the toolbar): a close-up of the person's largest face, name and photo count; a click filters the grid (`person` in `library.filter`, `person:` search token, filter chip). Face boxes in the loupe can be switched off (View ▸ Loupe Overlay ▸ Face Boxes, toolbar) resized with eight drag handles and removed with the × shown on hover (catalog-only and undoable, one undo step per drag; the sidecar is never rewritten for either); no moving a box by dragging it yet. Photo ▸ Metadata ▸ Detect Faces (`cmd:faces.detect`) finds faces with the YuNet detector (pure Rust, about 200 ms a photo, matches OpenCV's own YuNet on a 45-photo test set; the 232 KB model is a one-time download offered in the same step, never part of LightCraft) and adds them as unnamed boxes; names are suggested from the faces already named (recognition models are opt-in downloads, run on the CPU in a background thread; a face is named only when you confirm it); a person's page shows their cropped faces and the unnamed faces that look like them (LRC-LIB-PEOPLE), with a user-triggered ↑ action or targeted A key to name all shown suggestions at or above one score in one undo step; with recognition on, a background scan finds faces in photos that have none and embeds every face (one to three worker threads, raws through their embedded preview); an Unnamed faces section orders faces by likeness and names a selected group at once; no separated clusters, no manual tagging, no writing regions back |
| LR-LIB-STACK | Stacks | P1 | ✅ | `cmd:stack.group`, `cmd:stack.ungroup`, `cmd:stack.toggle`, `cmd:stack.setTop`, `cmd:stack.remove`, `cmd:stack.auto`, `cmd:photo.delete`, `crates/catalog/src/stacks.rs`, `crates/ui-egui/src/thumb.rs` | grid/filmstrip count badges (the same badge on both, a click expands or collapses the stack, selected or not, one translated tooltip; widgets `stack:<id>`, `film:stack:<id>`), expand/collapse (a click or double-click on a grid badge toggles the stack once, #2233), auto-stack by capture time; delete / remove folder drop the photo from the stack so `i/n` updates (#1493); no visual-similarity auto-stack |
| LR-LIB-VERSIONS | Versions | P1 | ✅ | `cmd:version.create` | see section M |
| LR-LIB-DELETE | Delete / Recently Deleted | P0 | ✅ | `cmd:photo.delete`, `cmd:photo.restore`, `cmd:photo.deletePermanently` | Delete and Delete Permanently retain surviving selected photos; if none remain, select the next visible survivor (previous at the end) in the current source/filter/sort; permanent deletion removes catalog records, not files on disk; Restore and Delete Permanently in the Photo menu and the photo context menus for photos in Recently Deleted (before, the UI had no way to restore); importing a file that is in Recently Deleted again restores the photo with its edits, rating and albums (issues #298, #706: before, the import skipped it as "already in the library" while the grid showed it deleted) — the review dialog checks it, badges it "Will be restored", counts it as "in Recently Deleted" rather than "already in the library", and its choice Restore them / Import as new / Leave them starts on Restore; with Leave them such a file starts unchecked and Check All and the file-type toggles leave it out, but a click still checks it and it is restored (issue #1285: before, the click did nothing and the "In Recently Deleted" badge was drawn over the checkbox, which now sits above it); dropped files restore too ("Restored 1 photo from Recently Deleted"); a deleted photo matched by content whose file is gone is relinked to the imported file; Photo ▸ Empty Recently Deleted (`cmd:library.emptyRecentlyDeleted`, one undo step, shown while the trash is the source); import takes `onDeleted` restore (default) / skip / fresh for files in the trash (`cmd:library.import`; the report lists `restored`, and with skip flags the duplicate `existingDeleted`); browsing a folder in Local (`cmd:library.browse`), Auto Import and a Lightroom catalog import never restore a deleted photo; no confirmation dialog, no auto-purge after N days (needs a deleted-at date in the catalog); Delete asks first ("Move this photo to Recently Deleted?") from the key, the Photo menu and the photo context menu, on by default and switched off in Settings ▸ General (#1239: before, it was off by default and the context menu never asked); no auto-purge after N days (needs a deleted-at date in the catalog) |
@@ -136,13 +136,13 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-VIEW-FULLSCREEN | Full-screen preview | P1 | ✅ | `cmd:view.fullScreenPreview`, `cmd:view.enterFullScreen` | photo on black, arrows step, Esc exits; ⇧⌘F window full screen |
| LR-VIEW-FILMSTRIP | Filmstrip | P0 | ✅ | `cmd:view.filmstrip`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/thumb.rs` | its thumbnails wear the overlay of the grid's (one painter, `thumb.rs`): the virtual-copy tag, a clickable stack badge with the grid's tooltip, the label dot, the grid's placeholder until the picture is drawn, a rejected photo dimmed as in the grid, and a failure mark that says why on hover (`film:failed:<id>`); on a narrow thumbnail the marks degrade (edited mark, then the stars as ★ and the number, then what does not fit); the stack badge sheds its icon, then the `i/n`) and nothing is painted outside the photo; the preview pill keeps clear of the stack badge; right-click on the stack badge opens the photo menu; the photo context menu on right-click; the mouse wheel scrolls it sideways, a third of its width per notch as in Lightroom Classic (trackpads scroll the points they report); it follows the active photo only when that changes (centred if off screen), so a scrolled strip stays put; every selected photo has the selected background; selected photos with a loaded thumbnail also show a ring, the active one in the heavier two-tone ring and the others in the lighter one, in the theme's colours, as in the grid (a selected cell with no thumbnail, still loading or failed, has the background and the same ring (the filmstrip paints the ring on its placeholder too, as the grid does)); a drag from a cell carries the selection (a photo outside it drags alone and replaces it; in Compare it drags alone and leaves the selection, the active photo and the pair as they are) to the same sidebar rows as a drag from the grid, and a click without movement works as before (it selects the photo; in Compare it goes to the active side, see LR-VIEW-COMPARE) |
| LR-VIEW-ZOOM | Zoom & pan | P0 | ✅ | `cmd:view.zoomFit`, `cmd:view.zoom100`, `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.clickZoom`, `cmd:view.navigate`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/headless.rs` | continuous native pinch / modifier-wheel zoom (Fit–800%, anchored under the pointer), two-finger scroll / touch pan with edge limits; in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); Detail (including tools, Before/After and full-screen preview), Compare and Reference; fractional percentages preserve small gestures; image, picker and targeted-adjustment cursors stay steady between gesture events; keyboard steps 25–800 % (not 6–1600 %); Fill in the bottom bar; click / Z / Space eases to the chosen ratio (1:1 default, 2:1, 3:1, 4:1, 8:1). The loupe's cost follows the canvas, not the zoom (issue #323): the whole frame is rendered at about canvas size (at most the 2560 px preview source level unless a larger Preview size is chosen, and never above the GPU's texture side), and once the view is zoomed well past that (more than 25 %) the window on screen is rendered too, cut from a frame of at most the photo's own pixels, so beyond 100 % the GPU magnifies it (`region::plan`, `RenderRequest::window`, `Session::region_job`, `crates/ui-egui/src/region.rs`); 1:1 and 2:1–8:1 are sharp at any photo size. A slider tick takes 7–12 ms on a 1400 × 900 canvas and 11–25 ms on a 2800 × 1700 one at 100 % and 400 % of a 24 MP photo (M1 Max, GPU, `profile_slider_drag`); about 20–25 ms at 100 % on the big canvas is over a 16 ms frame. A slider drag renders the whole frame at full size where the GPU draws the view, so the fit view stays sharp while dragging, and at 0.6 of it where that would be too slow: on the CPU, with an output-device profile proof or the HDR range shown, or for a control whose full-size drafts on this photo went clearly over the 16 ms slider budget (more than 20 ms) in two drags in a row (a LUT profile or refined mask the CPU renders, a photo past a GPU limit, a slow GPU); a draft's time is its render plus the frame that uploads and shows it, and a host frame time over 1 s (a hidden or stalled window) counts as unknown. A slow verdict is per photo and control (the same control on another photo, or another control on this one, is timed afresh) and expires: after 30 s a drag tries full size again, the wait doubling after each slow retry up to 240 s. Only a drag timed at full size changes it: one whose full-size drafts' median time (leaving out the first) is at most 20 ms forgets it; a drag that drafts small from its start (while the verdict holds, or where the GPU does not draw the view) or times fewer than two full-size drafts leaves it unchanged. At most 256 (photo, control) pairs are remembered, the oldest forgotten first. The size is chosen when a drag starts and kept until it ends, unless its full-size drafts take more than twice the budget, when it drops to 0.6 after three of them (`region::DragScale`, issue #330). Zoomed in, the whole-frame draft under the window is the 0.6 one (only the histogram and the window's stand-in use it). Render workers convert the pixels for their textures, not the UI thread. Handing GPU renders to egui without a CPU readback is #1228. A continuous pinch holds the render sizes (and the windows there are) and the size the fit view is shrunk to until it is quiet. A fit view on a canvas up to about 3200 px (a Retina Mac) never decodes the original; larger displays get a window at fit, which does. Diagnostic overlays (Visualize Spots, Point Color range, HDR range) get windows too, tested equal to the whole-frame render's pixels. Photos whose spots or Auto Mask strokes read too far for one window (only photos longer than 8192 px) render the whole frame at the size it is drawn, as before windows; while a preset or profile is hovered, or over a picture that is not the frame (an unsupported raw's embedded JPEG), the whole frame stays canvas-sized. Before/After (side by side, stacked, `\\` and both wipes) gets the same windows on both sides, clipped to their pane or side of the line. Windows render on the GPU like whole frames (equivalence-tested against the CPU), in the browser build too (windows no wider than its GPU's texture side, at most 3072 px), and are not made while hovering a look, nor over a picture that is not the frame (an unsupported raw's embedded JPEG with another crop). No texture is larger than the GPU allows. Spots and Auto Mask brushes work while what a window reads fits one render (8192 px along an axis, 4096 in the bLine truncated
| LR-VIEW-FOCUSPOINT | Camera focus point overlay and zoom (beyond Lightroom) | P2 | 🟡 | `cmd:view.focusPoint`, `cmd:view.zoomToFocus`, `cmd:view.zoomToggle`, `cmd:photo.reload`, `cmd:photo.readFocusPoints`, `cmd:focus.pump`, `crates/meta/src/focus.rs`, `crates/meta/src/focus.rs`, `crates/engine/src/focus_scan.rs`, `crates/engine/src/tests/focus_scan.rs`, `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `draw_focus_point`), `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests/focus_point.rs`, `docs/focus-points.md` | an extra (Lightroom shows no focus points): the AF frame read from the file at import; photos imported earlier get it in the background from a header-only read of each file (about 32 KB, ~100 photos/s from a spinning disk; activity row, cancellable, resumable; Photo ▸ Read Focus Points) as a box on the upright photo, drawn in Detail, Compare and Survey through rotation and crop (View ▸ Focus Point, ⌥F); Toggle Zoom centres on it (View ▸ Zoom to Focus Point, on by default); Info panel row `AF-C · Wide · Animal Eye Tracking`; `meta.focus` in `photo.inspect`. Partial: Sony ILCE-1 and ILCE-7SM3 only (layout checked against 333 files); other Sony bodies and other makers not yet; manual focus and centre-only Wide reports show nothing; Compare panes share one pan, so Z centres on the active photo's point only |
| LR-VIEW-FOCUSPOINT | Camera focus point overlay and zoom (beyond Lightroom) | P2 | 🟡 | `cmd:view.focusPoint`, `cmd:view.zoomToFocus`, `cmd:view.zoomToggle`, `cmd:photo.reload`, `cmd:photo.readFocusPoints`, `cmd:focus.pump`, `crates/meta/src/focus.rs`, `crates/meta/src/focus.rs`, `crates/engine/src/focus_scan.rs`, `crates/engine/src/tests/focus_scan.rs`, `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `draw_focus_point`), `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests/focus_point.rs`, `docs/focus-points.md` | an extra (Lightroom shows no focus points): the AF frame read from the file at import; photos imported earlier get it in the background from a header-only read of each file (about 32 KB, ~100 photos/s from a spinning disk; activity row, cancellable, resumable; Photo ▸ Metadata ▸ Read Focus Points) as a box on the upright photo, drawn in Detail, Compare and Survey through rotation and crop (View ▸ Loupe Overlay ▸ Focus Point, ⌥F); Toggle Zoom centres on it (View ▸ Loupe Overlay ▸ Zoom to Focus Point, on by default); Info panel row `AF-C · Wide · Animal Eye Tracking`; `meta.focus` in `photo.inspect`. Partial: Sony ILCE-1 and ILCE-7SM3 only (layout checked against 333 files); other Sony bodies and other makers not yet; manual focus and centre-only Wide reports show nothing; Compare panes share one pan, so Z centres on the active photo's point only |
| LR-VIEW-NAVIGATOR | Navigator mini map | P1 | ✅ | `cmd:view.navigator`, `crates/ui-egui/src/panels/detail.rs` | shown while zoomed (bottom right); click/drag pans |
| LR-VIEW-BEFOREAFTER | Before / after | P0 | ✅ | `cmd:view.showOriginal`, `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom`, `cmd:beforeAfter.setBefore`, `cmd:beforeAfter.copyAfterToBefore`, `cmd:beforeAfter.copyBeforeToAfter`, `cmd:beforeAfter.swap`, `cmd:beforeAfter.resetBefore` | all four layouts; before = the import state (defaults + import preset) or a chosen history step / version / the current settings; copy and swap (View → Before/After Settings, History row menu). The chosen before lasts for the session; in side by side and top / bottom, clicks with the white-balance selector, colour samplers and targeted adjustment work in the Before view too (`crates/ui-egui/src/tests/before_after.rs`). Zoomed in, the side by side and stacked views each stay in their pane, with their labels under it. Click zoom animates both panes together, including cached window tiles; input follows the displayed image and render requests use the final size (#1821) |
| LR-VIEW-BEFOREAFTER | Before / after | P0 | ✅ | `cmd:view.showOriginal`, `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom`, `cmd:beforeAfter.setBefore`, `cmd:beforeAfter.copyAfterToBefore`, `cmd:beforeAfter.copyBeforeToAfter`, `cmd:beforeAfter.swap`, `cmd:beforeAfter.resetBefore` | all four layouts; before = the import state (defaults + import preset) or a chosen history step / version / the current settings; copy and swap (View → Before/After, History row menu). The chosen before lasts for the session; in side by side and top / bottom, clicks with the white-balance selector, colour samplers and targeted adjustment work in the Before view too (`crates/ui-egui/src/tests/before_after.rs`). Zoomed in, the side by side and stacked views each stay in their pane, with their labels under it. Click zoom animates both panes together, including cached window tiles; input follows the displayed image and render requests use the final size (#1821) |
| LR-VIEW-COMPARE | Compare two photos | P1 | ✅ | `cmd:view.compare`, `cmd:compare.swap`, `cmd:compare.makeSelect`, `cmd:compare.set`, `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests/compare.rs` | select / candidate, synced zoom + pan, arrows move the candidate; a filmstrip click puts the photo into the active side (a photo on the other side swaps), so the active photo is always one of the two shown; a ⌘/Ctrl- or Shift-click on the filmstrip changes the selection as in the grid while the two photos shown stay selected and the active photo is unchanged (#187); the active pane is framed in the active photo's two-tone selection ring (theme tokens, 3 pt), as in the grids; 1:1 to 8:1 sharp on both sides (zoom windows, see LR-VIEW-ZOOM); no zoom-link toggle; each pane says “Rendering…” (widget `compare:rendering:<pane>`) or “This photo can't be opened” (`compare:renderFailed:<pane>`) as the loupe does |
| LR-VIEW-SURVEY | Survey view [Classic] | P2 | ✅ | `cmd:view.survey`, `crates/ui-egui/src/panels/compare.rs` | selection tiled (≤ 48), keys, the bottom bar and the Info panel's stars and colour labels act on the active photo (ringed as in the grid), each tile's caption shows its colour label, hover × or ⌘/Ctrl-click removes a photo; the tiles fit the photos' shapes (the column count that shows the most of them, so four portrait photos stand side by side; an incomplete last row is centred) and glide to their new places when a photo leaves or joins, each keeping its render (`crates/ui-egui/src/panels/compare/survey.rs`) |
| LR-VIEW-INFOOVERLAY | Info overlay on the photo | P1 | ✅ | `cmd:view.infoOverlay`, `cmd:view.viewOptions`, `crates/ui-egui/src/panels/detail.rs` (`info_overlay`) | off / Info 1 (by default file name, capture date, size) / Info 2 (file name, exposure, camera + lens), each three lines chosen in View Options; ⌘I cycles (I in full screen; elsewhere I stays the Info panel); the star rating and flag show under the lines when the photo has them, and in the full-screen preview on macOS the overlay starts below the window controls (issue #2460) |
| LR-VIEW-SLIDESHOW | Slideshow | P2 | ✅ | `cmd:view.slideshow` | View ▸ Slideshow (⌥⌘↩): the photos in view full screen from the selected one, played with the library's playback settings (see LRC-SS-PLAYBACK: fades, random order, repeat, previews prepared ahead; `interval` / any setting overrides one run); Space pauses, ←/→ step (a cut), Esc ends; playback controls on pointer movement |
| LR-VIEW-SLIDESHOW | Slideshow | P2 | ✅ | `cmd:view.slideshow` | View ▸ Slideshow ▸ Slideshow (⌥⌘↩): the photos in view full screen from the selected one, played with the library's playback settings (see LRC-SS-PLAYBACK: fades, random order, repeat, previews prepared ahead; `interval` / any setting overrides one run); Space pauses, ←/→ step (a cut), Esc ends; playback controls on pointer movement |
| LR-VIEW-SECONDWINDOW | Second display window [Classic] | P2 | ✅ | `cmd:view.secondWindow`, `crates/ui-egui/src/panels/second.rs` | Window ▸ Second Window (⌘F11): the active photo fitted in its own native window with its own render (a floating panel where there are no native windows); loupe view only (no grid / compare / survey there) |
| LR-VIEW-CLIPPING | Clipping indicators | P0 | ✅ | `cmd:view.clipping` | |
| LR-VIEW-HISTOGRAM | Histogram | P0 | ✅ | `cmd:view.histogram`, `crates/ui-egui/src/panels/edit/histogram.rs`, `crates/ui-egui/src/panels/right.rs`, `crates/pipeline/src/lib.rs` (`hdr_histogram`) | stays at the top of the Edit panel while its sliders scroll under it (issue #2679, `the_histogram_stays_in_view_while_the_sliders_scroll`); HDR edits: SDR on the left half, the HDR range (0 to 5 stops above SDR white, a fixed scale) on the right with the headroom limit marked; colour bar (white, or Visualize HDR range's colours when that is on) and SDR / HDR labels; the plot's five tonal zones also drag to adjust their Basic control (LRC-DEV-HISTOGRAM-DRAG); it follows slider drags of an HDR edit live (a small render beside the drafts, `Slot::HdrHistogram`) and never drops to the SDR layout mid-drag; an edit with HDR switched off keeps its SDR histogram while it is dragged (#2819); turning HDR on or off flows between the layouts (`crates/ui-egui/src/panels/edit/hdr_flow.rs`: the SDR curve squeezes into the HDR layout's SDR section as the HDR section and legend open, and stretches back); the shadow and highlight clipping buttons at its top corners are the theme's raised fill with a chevron that stands 3:1 on it in every theme and state |
@@ -478,9 +478,9 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests/dialog_fit.rs`, `crates/ui-egui/src/tests/dialog_copy.rs`, `crates/ui-egui/src/tests/dialogs.rs` (`a_click_outside_closes_the_dialog_when_settings_allow_it`) | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / confirm row stay on screen (the confirm button names its action: Create, Rename, Create Stacks, Export 3 Photos…, with "OK" kept only for a one-field prompt opened with a command that has no verb, `crates/ui-egui/src/tests/dialog_copy.rs`); lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window; Settings → Dialogs → Close a dialog by clicking outside it (off by default, so a stray click never throws away a dialog's choices): a click pressed and released on the dimmed backdrop closes the dialog like Esc and doesn't reach the panels below, while a drag that ends outside (a slider pulled past the edge) or a click that closes a dropdown keeps it; the import review never closes this way (`clicked_backdrop`); a one-line prompt (Rename Folder, New Folder on Disk, the preset and version names, New Library when its name can't be used, Auto-Tag from Tracklog) the engine refuses stays open with its text and shows the reason in a toast, so the name can be corrected, where it used to close without a word; a New Folder on Disk that works says so (“Created folder “Selects” in “2026/Shoot””, naming the parent by its last two folders as dialogs do) |
| LR-BEHAV-SIDEBAR-COLLAPSE | Collapsible left-sidebar sections | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`section`, `section_header`), `crates/ui-egui/src/sidebar.rs` (`SidebarLayout`), `crates/ui-egui/src/tests/panels.rs` | click the Albums, Local, By Date, Folders or Keywords header (or drive `ui.clickWidget` `sidebarSection:<albums\|local\|byDate\|folders\|keywords>`) to fold or unfold the section; a chevron before the title shows the state; the choice is kept across restarts (`sidebar` in the UI state; the `collapsedSidebar` list of older settings files is still read). the click itself is UI-only, like the By Date / Keywords disclosure triangles, and `cmd:view.sidebarSection` `{section, collapsed}` folds and unfolds for agents; photos dropped on a folded Albums section have no target |
| LR-BEHAV-SIDEBAR-SECTIONS | Left-sidebar sections share one frame and one arrangement | P2 | ✅ | `crates/ui-egui/src/sidebar.rs` (`SidebarSection`, `SidebarLayout`), `crates/ui-egui/src/panels/left.rs` (`section`, `section_header`, `tree_toggle`), `crates/ui-egui/src/tests/panels.rs`, `crates/ui-egui/tests/it/sidebar_branch.rs` | Albums, Local, By Date, Folders and Keywords are drawn by one `section` frame (the same gap above, header, fold and accessibility name) from one arrangement, `sidebar` in the UI state: a list of `{id, hidden, collapsed}` top to bottom, also settable with `ui.set`. Whatever is read, every section is in it exactly once (unknown and repeated entries are dropped, the rest follow in the usual order), so a damaged or newer settings file never loses the other settings. Rows that open (album folders, Local folders, dates, library folders, keywords) share `tree_toggle`: the same triangle, the same remembered open state, announced as Expand / Collapse. A click on the triangle with Option (Alt on Windows and Linux) held opens or folds the row and all the rows inside it, however many and also those not drawn yet: it is kept for the session as one thing said of all the rows inside the row (a row is as the last thing said of it, or of a row above it, has it), so a folder made inside the branch later follows it; in Local it folds everything inside a folder and opens the one folder (opening them all would read every folder from the disk); `ui.clickWidget` takes `alt: true` for it. A section with nothing to list (Folders before anything is imported, Keywords before any is added) stays, open, with a one-line note in place of rows (`sidebarEmpty:<id>`) instead of disappearing. `ui.set` reads `sidebar` strictly (`SidebarLayout::parse`): an unknown or repeated section, or a flag that is not true / false, is refused and changes nothing; sections left out follow in the usual order, shown and open; the older `collapsedSidebar` list still folds and unfolds. A section may have one button at the end of its header, declared in one place (`header_button`: an icon, a tooltip, and either an action or a menu): the frame draws it at the visible edge in the header and its pinned copy, keeps its click from folding the section and leaves it room beside a folded section's count. Albums has + (`icon:albumNew`: Create Album / Smart Album / Folder…), Keywords has + (`icon:keywordNew`: Create Keyword Tag, for a keyword inside the default parent, not inside what the Keyword List has picked; once made, Keywords is shown and opened down to it). My Photos (All Photos, Recently Added, Picks, Missing Photos, Recently Deleted) is not a section: it stays on top |
| LR-BEHAV-SIDEBAR-HIDE | Show and hide left-sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset`, `crates/ui-egui/src/sidebar.rs`, `crates/ui-egui/src/panels/left.rs` (`sections_menu`), `crates/ui-egui/src/menus/menubar.rs`, `crates/ui-egui/src/tests/panels.rs` | View ▸ Sidebar Sections lists Albums, Local, By Date, Folders and Keywords in the sidebar's order, each checked while shown; unchecking one takes its header and rows off the sidebar, checking it puts it back where and how it was (still folded if it was). The same list opens with a right-click on any section header (with Hide This Section first; widgets `sidebarMenu:hide`, `sidebarMenu:section:<id>`, `sidebarMenu:reset`) and on the My Photos title (`sidebarTitle`), which is always there, so hidden sections can always come back. Reset Sidebar Sections (enabled once something changed) shows and opens every section in the usual order. `view.sidebarSection` `{section, show?, collapsed?}` flips shown / hidden when neither flag is given and refuses an unknown section or a flag that is not true / false. Hiding the section of what the grid shows (an album, a keyword filter) leaves the grid as it is; an album made while Albums is hidden or folded brings Albums back, open. Kept with the UI state (`sidebar`). My Photos itself can't be hidden |
| LR-BEHAV-SIDEBAR-HIDE | Show and hide left-sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset`, `crates/ui-egui/src/sidebar.rs`, `crates/ui-egui/src/panels/left.rs` (`sections_menu`), `crates/ui-egui/src/menus/menubar.rs`, `crates/ui-egui/src/tests/panels.rs` | Window ▸ Sidebar Sections lists Albums, Local, By Date, Folders and Keywords in the sidebar's order, each checked while shown; unchecking one takes its header and rows off the sidebar, checking it puts it back where and how it was (still folded if it was). The same list opens with a right-click on any section header (with Hide This Section first; widgets `sidebarMenu:hide`, `sidebarMenu:section:<id>`, `sidebarMenu:reset`) and on the My Photos title (`sidebarTitle`), which is always there, so hidden sections can always come back. Reset Sidebar Sections (enabled once something changed) shows and opens every section in the usual order. `view.sidebarSection` `{section, show?, collapsed?}` flips shown / hidden when neither flag is given and refuses an unknown section or a flag that is not true / false. Hiding the section of what the grid shows (an album, a keyword filter) leaves the grid as it is; an album made while Albums is hidden or folded brings Albums back, open. Kept with the UI state (`sidebar`). My Photos itself can't be hidden |
| LR-BEHAV-SIDEBAR-REORDER | Reorder left-sidebar sections | P2 | ✅ | `cmd:view.sidebarMoveSection`, `crates/ui-egui/src/sidebar.rs` (`move_before`, `move_by`), `crates/ui-egui/src/panels/left.rs` (`section_drag`, `section_drop_before`, `section_drag_feedback`), `crates/ui-egui/src/tests/panels.rs` | drag a section by its header: its name follows the pointer, a line (`sidebarSectionDrop`) shows the gap it would go to (above the section whose upper half the pointer is over, or below the last), releasing over the sidebar moves it there, Esc or releasing elsewhere leaves it; the sidebar scrolls when the drag nears its top or bottom edge, also over a pinned header (a section picked up by the pinned header scrolls once the pointer has left it). A press on a header's button is never a section drag. A click on the header still folds the section, and an album dragged onto the Albums header is still an album drag. The header's menu has Move Up / Move Down (`sidebarMenu:moveUp` / `moveDown`), one shown section at a time, stepping over hidden ones, disabled at the ends. `view.sidebarMoveSection` `{section, direction: up\|down}` or `{section, before: <section>\|null}` (null: last) answers `{moved, order}`. The order is kept with the UI state (`sidebar`). Recently Deleted is listed with My Photos (below Picks / Missing Photos), not after the sections. Not here: dragging My Photos, or rows from one section into another |
| LR-BEHAV-SIDEBAR-STICKY | Pinned section header and section look | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`pinned_header`, `section_header`, `empty_hint`), `crates/ui-egui/src/tests/panels.rs` | while the rows of an open section are in view but its header has scrolled away, a copy of the header (`sidebarSectionPinned:<id>`, with the section's buttons and menu) stays at the top of the sidebar; the next section's header pushes it out; folding from it brings the section's own header into view. Rows scrolled beneath the pinned header are covered by it: an album or photos dropped on the pinned Albums header go to the top level / nowhere, never to the row under it; folding from it keeps the sideways scroll. Sections are told apart by a hairline in the gap above each; the fold chevron sits in the gutter, in the column of the rows' triangles (`sidebarSectionChevron:<id>`); a header highlights under the pointer; a folded section shows how many top-level rows it holds (`sidebarSectionCount:<id>`, with View ▸ Photo Counts); a count of 0 is fainter. Not here: a height of its own per section (one scroll area serves the whole sidebar), a count for Recently Added, Local's Browse Folder… as a header button |
| LR-BEHAV-SIDEBAR-STICKY | Pinned section header and section look | P2 | ✅ | `crates/ui-egui/src/panels/left.rs` (`pinned_header`, `section_header`, `empty_hint`), `crates/ui-egui/src/tests/panels.rs` | while the rows of an open section are in view but its header has scrolled away, a copy of the header (`sidebarSectionPinned:<id>`, with the section's buttons and menu) stays at the top of the sidebar; the next section's header pushes it out; folding from it brings the section's own header into view. Rows scrolled beneath the pinned header are covered by it: an album or photos dropped on the pinned Albums header go to the top level / nowhere, never to the row under it; folding from it keeps the sideways scroll. Sections are told apart by a hairline in the gap above each; the fold chevron sits in the gutter, in the column of the rows' triangles (`sidebarSectionChevron:<id>`); a header highlights under the pointer; a folded section shows how many top-level rows it holds (`sidebarSectionCount:<id>`, with Window ▸ Photo Counts); a count of 0 is fainter. Not here: a height of its own per section (one scroll area serves the whole sidebar), a count for Recently Added, Local's Browse Folder… as a header button |
| LR-BEHAV-PANEL-RESIZE | Resizable side panels | P1 | ✅ | `crates/ui-egui/src/panels.rs` (`resizable_side`), `crates/ui-egui/src/state.rs` (`LEFT_WIDTH`, `RIGHT_WIDTH`), `crates/ui-egui/src/tests/panels.rs`, `crates/ui-egui/src/tests/panel_restore.rs` | closing a tool panel (Crop, Remove, Masking, Red Eye) puts back the panel shown before it in the same frame, at the same width and scroll position, or leaves it hidden if it was (`UiState::leave_tool`); drag the left sidebar's right edge (200–480 pt) or the right panel's left edge (250–520 pt); the photo area keeps ≥ 360 pt; widths are kept across panels, views and restarts (`leftWidth` / `rightWidth` in the UI state); the Presets column stays fixed |
| LR-BEHAV-EMPTY-STATES | Empty states | P1 | ✅ | `crates/ui-egui/src/panels.rs` (`empty_message`, `empty_state`), `crates/ui-egui/src/panels/empty_library.rs`, `cmd:file.addPhotos`, `cmd:file.importLightroom`, `crates/ui-egui/src/tests/empty_library.rs` | each view says why it is empty (no photo selected, filters, an empty folder). A library with no photos (none, or only deleted or browsed ones) opens on the Photo Grid (Square Grid stays) with the sidebar, and the grid and Detail view (not while a folder is browsed under Local) offer Import Photos… (primary) and Import Lightroom Catalog… (desktop) as buttons, with a line saying photos and folders can be dropped into the window and the key Import Photos… is bound to now; the right-hand panel says to import photos first. The top bar has an Import button beside Export in every library. Files dragged over the window dim it and a card says what dropping will do; a drop of photos or folders opens the same import review as File ▸ Import |
| LR-BEHAV-TOOLTIPS | Tooltips with shortcuts | P0 | ✅ | `crates/ui-egui/src/panels/bottombar.rs` | |
@@ -493,6 +493,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-BEHAV-WHATSNEW | What's new | P2 | ✅ | `cmd:app.whatsNew`, `docs/whats-new.md` | Help ▸ What's New: release highlights |
| LR-BEHAV-AI-EA | Early-access badges | P2 | ⬜ | | |
| LR-BEHAV-TITLEBAR | Title bar drag and double-click zoom (macOS) | P2 | 🟡 | `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/tests/titlebar.rs` | the native title bar is hidden on macOS, so the top bar's empty space (including the traffic-light margin) moves the window and a double-click does what System Settings › “Double-click a window's title bar to” says (zoom or restore, minimize, nothing; craft-window's `title_bar`); buttons and the search field keep their clicks; ignored in full screen, where the traffic lights are gone and the bar's left buttons move into their space (#1763). A press that starts on a button, the search field or a panel floating over the bar never moves the window (AppKit's `movable` is off while the pointer is there). While a dialog is open the bar is not dimmed, so it stays level with the window buttons AppKit draws over it (as under a macOS sheet): its controls are inactive, a click on it does not close the dialog, and its empty space still moves the window; not on a window with its native title bar, nor in full screen. Known gap: egui-winit reads the zoomed state only at start-up and after our own `Maximized` command, so a window zoomed another way (green button, Window ▸ Zoom, snapping) makes the first double-click a no-op before the toggle catches up. Checked by hand on a real macOS window (drag, zoom, restore) |
| LR-BEHAV-WINDOW | Window size and maximized state remembered | P2 | 🟡 | `crates/ui-egui/src/window_place.rs`, `apps/lightcraft/src/prefs.rs`, `apps/lightcraft/src/main.rs` | the window opens at the size it was left at, zoomed / maximized if it was; full screen and the place on the desktop are not remembered; Windows: a maximized window is built at its size and maximized once it shows (built maximized it could cover half the screen while Windows took it for maximized), and restored and maximized again once if it only says so; a window remembered larger than its screen is fitted to it. Not verified on several monitors with different scales on hardware |
## Y. Menus
@@ -553,12 +554,12 @@ visible menu bar yet: the menu model is only exposed through the control channel
| MENU-VIEW-BEFOREAFTER | Before/After submenu | P0 | ✅ | `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom` | |
| MENU-VIEW-ZOOM | Zoom in / out / toggle / fit / 1:1 | P0 | ✅ | `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.zoomFit`, `cmd:view.zoom100` | |
| MENU-VIEW-CLIPPING | Clipping | P0 | ✅ | `cmd:view.clipping` | |
| MENU-VIEW-MASKOVERLAY | Mask overlay / cycle colour | P0 | ✅ | `cmd:view.maskOverlay`, `cmd:view.maskOverlayMode`, `cmd:view.maskOverlayColor` | colour cycles through the panel's swatches (no params) or takes `color` / `opacity` |
| MENU-VIEW-MASKOVERLAY | Mask overlay / cycle colour | P0 | ✅ | `cmd:view.maskOverlay`, `cmd:view.maskOverlayMode`, `cmd:view.maskOverlayColor` | colour cycles through the panel's swatches (no params) or takes `color` / `opacity`; View ▸ Mask Overlay also lists every overlay mode and colour, with the current one checked |
| MENU-VIEW-INCLUDESUBFOLDERS | Include subfolders | P1 | ✅ | `cmd:library.browse` (`subfolders`) | toggle in the folder header; imports of folders are recursive |
| MENU-VIEW-SORT | Sort submenu | P0 | ✅ | `cmd:library.sort`, `cmd:library.shuffle` | Random + Reshuffle; no colour-label key |
| MENU-VIEW-STACKS | Expand/collapse stacks | P1 | ✅ | `cmd:stack.expandAll`, `cmd:stack.collapseAll` | |
| MENU-VIEW-PHOTOCOUNT | Show photo counts | P2 | ✅ | `cmd:view.photoCounts` | View ▸ Photo Counts toggles the left panel's counts |
| MENU-VIEW-SIDEBARSECTIONS | Sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset` | View ▸ Sidebar Sections ▸ a checkable item per left-sidebar section, then Reset Sidebar Sections (see LR-BEHAV-SIDEBAR-HIDE) |
| MENU-VIEW-PHOTOCOUNT | Show photo counts | P2 | ✅ | `cmd:view.photoCounts` | Window ▸ Photo Counts toggles the left panel's counts |
| MENU-VIEW-SIDEBARSECTIONS | Sidebar sections | P2 | ✅ | `cmd:view.sidebarSection`, `cmd:view.sidebarReset` | Window ▸ Sidebar Sections ▸ a checkable item per left-sidebar section, then Reset Sidebar Sections (see LR-BEHAV-SIDEBAR-HIDE) |
| MENU-VIEW-HDR | HDR display options | P2 | ⬜ | | |
| MENU-PHOTO-ADDTOALBUM | Add to album | P0 | ✅ | `cmd:album.addPhotos` | off for a Local-only selection, with an Add to My Photos First hint item (issue #684) |
| MENU-PHOTO-REMOVEFROMALBUM | Remove from album | P0 | ✅ | `cmd:album.removePhotos` | Photo ▸ Remove from Album, shown in a normal album only, carries the ⌫ shortcut there (Delete Photo then has none) (issue #1805) |
@@ -637,7 +638,7 @@ From `06-shortcuts.md` part 1. Evidence is our binding; conflicts are explained
| KEY-FILMSTRIP | Filmstrip — / | P0 | ✅ | `cmd:view.filmstrip` | |
| KEY-SHOWORIGINAL | Show original — \ | P0 | ✅ | `cmd:view.showOriginal` | |
| KEY-TOGGLEZOOM | Toggle zoom — Space | P0 | ✅ | `cmd:view.zoomToggle`, `crates/ui-egui/src/space_hand.rs`, `crates/ui-egui/src/tests/space_hand.rs` | Space is a secondary binding (primary Z); held, it toggles once (the key's auto-repeat no longer flips the zoom back and forth). With a tool on the photo (Crop, Masking, Remove, Red Eye, the white-balance / colour-range / point-colour pickers, a targeted adjustment) held Space is the view's hand until the key is up, as in Lightroom: a click zooms to the click-zoom ratio at the point clicked (or back to Fit), a drag pans the zoomed photo (grab cursor; zoom-in cursor at Fit), and the tool gets neither; a tap (under 0.4 s, no click) toggles the zoom on its release (issue #1895) |
| KEY-MASKCOLOR | Cycle mask colour — ⇧O | P1 | ✅ | `cmd:view.maskOverlayColor`, `crates/ui-egui/src/shortcuts.rs` | ⇧O while masking cycles the overlay colour (while cropping: the guides' orientation); the overlay mode is in View ▸ Cycle Mask Overlay Mode |
| KEY-MASKCOLOR | Cycle mask colour — ⇧O | P1 | ✅ | `cmd:view.maskOverlayColor`, `crates/ui-egui/src/shortcuts.rs` | ⇧O while masking cycles the overlay colour (while cropping: the guides' orientation); the overlay mode is in View ▸ Mask Overlay ▸ Cycle Mask Overlay Mode |
| KEY-EXPORTPREV | Export with previous — ⌘E | P0 | ✅ | `cmd:app.exportPrevious` | ⌘E (alias) and ⌥⇧⌘E (Classic) |
| KEY-EXPORTDIALOG | Export dialog — ⇧E | P0 | ✅ | `cmd:dialog.export` | secondary binding (primary ⌘⇧E) |
| KEY-ENTERFULLSCREEN | Window full screen — ⇧⌘F | P1 | ✅ | `cmd:view.enterFullScreen` | |
@@ -719,7 +720,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-
| LRC-LIB-VC | Virtual copies | P1 | ✅ | `cmd:photo.virtualCopy` | ⌘' |
| LRC-LIB-LABELS | Colour-label sets | P1 | ✅ | `cmd:label.sets`, `cmd:label.applySet`, `cmd:label.saveSet`, `cmd:label.deleteSet`, `cmd:label.setNames`, `crates/engine/src/cmd/manage.rs` | built-in Colors / Review sets + user sets (Photo ▸ Set Color Label, Edit Label Names… dialog); names written to and read from `xmp:Label` |
| LRC-LIB-KEYWORDS | Hierarchical keywords, sets, painter, Keyword List | P1 | ✅ | `crates/catalog/src/keywords.rs`, `crates/ui-egui/src/panels/keyword_list.rs`, `cmd:keyword.list`, `cmd:keyword.create`, `cmd:keyword.edit`, `cmd:keyword.move`, `cmd:keyword.info`, `cmd:keyword.purgeUnused`, `cmd:keyword.setDefaultParent`, `cmd:keyword.sets`, `cmd:keyword.toggleFromSet`, `cmd:keyword.saveSet`, `cmd:keyword.nextSet`, `cmd:keyword.previousSet`, `cmd:tool.keywordPainter`, `cmd:tool.enablePainting` | hierarchical `a\|b\|c` keywords (tree, parent filters include children, rename moves children); keyword sets + Recent Keywords (⌥1–⌥9; ⌥0 / ⌥⇧0 go to the next / previous set and wrap around at either end); keyword painter (Keywords panel ▸ Paint: click photos in the grid to toggle a keyword, Esc stops; Photo ▸ Enable Painting, ⌘⌥K / Ctrl+Alt+K, paints the painter box's keyword, stops painting when pressed again, and with the box empty opens the Keywords panel). Keyword List (Keywords panel): every keyword, those without photos too (a keyword list in the catalog, format version 4), with counts, a filter box, a tri-state tick box for the selection and an arrow to show its photos; + / Create Keyword Tag (name, synonyms, put inside, add to selected photos), double-click / Edit Keyword Tag, − / Delete with confirmation, context menu (create inside, Put New Keywords Inside This Keyword, purge unused keywords); drag a keyword onto another to nest it or onto the list's title for the top level (a merge asks first), drag photos onto a keyword to tag them (the dragged label says how many photos get it; when all have it, it says so and a drop does nothing); a keyword dragged over itself or what is inside it shows the not-allowed cursor and says why; Esc gives up a drag. The list is there without a selection too; Put New Keywords Inside This Keyword (kept with the keyword in the library, undoable) also places new keywords typed in the Keywords panel. Keyword tag options include on export, export containing keywords and export synonyms shape exported files (names in `dc:subject`, paths in `lr:hierarchicalSubject`), and files' `lr:hierarchicalSubject` paths come back as keywords on import and from sidecars; Person is stored only. Keywording box (`crates/ui-egui/src/panels/keywording.rs`): the selection's keywords as chips (one only some selected photos have marked with an asterisk; × only removes, from every selected photo; with no selection, the active photo's), an Enter Keywords / Keywords / & Containing / Will Export switch (Lightroom Classic's Keyword Tags views: the keywords as text or as chips to edit, them with their parents, what exported files carry), keyword-set buttons and suggestions that follow the selection, shared text fields for typing and painting. Enter Keywords (`keywordView:enter`, `field:enterKeywords`) shows the selection's keywords as text, commas between them and an asterisk after one only some selected photos have: Return or leaving the box applies the edit to the photos selected when it began as one undo step (a keyword left out comes off every one of them, a name typed goes to all of them, `>` and `<` mark a hierarchy as `\|` does (`animal > dog` and `dog < animal` are both `animal\|dog`), a marked keyword stays on the photos that have it and without its asterisk goes to all), Esc gives the edit up, another selection gives it up too, an asterisk after any other name is refused with the text kept, and containing keywords and synonyms stay out of the text (the rules for mixed keywords and for when an edit applies are LightCraft's own). Settings ▸ Interface ▸ Keywords of the selection ▸ Grouped by parent (`keywordChips: grouped` in the app settings; Whole names stays the default): keywords inside the same keyword share a line naming it (`keywordGroup:<parent>`: the deepest keyword a chip shares with another) and their chips say only what is below it, side by side; a list of more than ten lines stops after eight with “+N more” (`keywordChipsMore`, then `keywordChipsFewer`); the whole list is for the selection it was asked of, another selection's is short again, and the suggestions say the keyword's own name (its whole path when two share a name, and in the tooltip). The titles of Keywords and of the Keyword List fold their sections shut (`section:keywording`, `section:keywordList`; kept in the UI state as `foldedSections`), and a selection without keywords says “No keywords yet”. The Add keyword box offers the library's keywords for what is being typed (after the last comma) right under itself (`kwComplete:<keyword>`, at most eight, those every selected photo has left out, a keyword spelled two ways once; above the box where the window has no room under it, and not at all while the box is scrolled out of the panel): ↓ / ↑ without Shift or Alt move through them (`kwCompleteAt:<keyword>`; the highlight stays with its keyword when the library changes), Return or a clicLine truncated
| LRC-LIB-METADATA | Metadata panel & presets | P1 | ✅ | `cmd:photo.setMeta`, `cmd:metadata.savePreset`, `cmd:metadata.applyPreset`, `cmd:metadata.presets`, `cmd:metadata.deletePreset`, `cmd:dialog.captureTime` | IPTC core, accessibility, place, capture-time edit; copyright status (unknown / copyrighted / public domain), rights usage terms and copyright info URL (`photo.setMeta` `copyrightStatus`, `usageTerms`, `copyrightUrl`; XMP Rights Management fields, kept by "copyright only" exports, a smart-album rule); metadata presets (Photo → Metadata Preset, Save Metadata Preset… from the active photo; applied on import from Settings) |
| LRC-LIB-METADATA | Metadata panel & presets | P1 | ✅ | `cmd:photo.setMeta`, `cmd:metadata.savePreset`, `cmd:metadata.applyPreset`, `cmd:metadata.presets`, `cmd:metadata.deletePreset`, `cmd:dialog.captureTime` | IPTC core, accessibility, place, capture-time edit; copyright status (unknown / copyrighted / public domain), rights usage terms and copyright info URL (`photo.setMeta` `copyrightStatus`, `usageTerms`, `copyrightUrl`; XMP Rights Management fields, kept by "copyright only" exports, a smart-album rule); metadata presets (Photo ▸ Metadata ▸ Metadata Preset, Save Metadata Preset… from the active photo; applied on import from Settings) |
| LRC-LIB-QUICKDEV | Quick develop | P2 | ✅ | `cmd:develop.quickAdjust`, `crates/ui-egui/src/panels/edit.rs` (`quick_develop`) | grid with several photos selected: Edit panel ▸ Quick Develop steps (exposure ⅓ / 1 stop, contrast, highlights, shadows, whites, blacks, clarity, vibrance, temperature) added to each photo's own value, one undo step |
| LRC-LIB-PEOPLE | People view | P2 | 🟡 | `cmd:view.people`, `cmd:view.person`, `cmd:faces.person`, `cmd:faces.unnamed`, `cmd:faces.nameFaces`, `crates/ui-egui/src/panels/people.rs`, `crates/ui-egui/src/panels/person.rs`, `crates/ui-egui/src/panels/unnamed.rs`, `crates/engine/src/face_tiles.rs` | Named People cards (face close-up, the photo count on the picture, name) for the photos the active filters let through, with the filter chips shown above them, sized by the thumbnail slider. Below them the **Unnamed faces**: every face nobody has named as a cropped picture, look-alikes next to each other once recognition has looked at them, a suggested name on a face the named ones recognise; click or Shift-click to select, type a name, Enter names the whole group in one undo step. A click on a person opens their page: only cropped faces, then **More** (unnamed faces that look like them, best first; click to confirm one, × to hide for the session, or ↑ / hovered-or-focused A key to confirm all currently shown non-hidden suggestions at or above that face's score, including ties, in one undo step). Every face is shown by the detector's box where the scan has one, so faces are equally close. Until recognition is set up a line at the top offers the next step (Settings ▸ Faces, or Turn on), as does the loupe's name box. Face pictures of unedited raws are cut from the largest embedded preview (planned read: header and JPEG only, never the sensor data) when it holds at least ¾ of the tile's pixels across the face, else developed as before; all are kept in the thumbnail disk cache at 16 px size steps, so a later launch shows them without reading the originals (#1440, `docs/faces.md`). No clusters with separators between groups, no persistent reject, no merge of two people
| LRC-LIB-COMMENTS | Comments panel | P2 | ⬜ | | |
@@ -738,14 +739,14 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-
| LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | |
| LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import: raw default and per-camera presets |
| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632), V6 takes colour noise reduction to the joint method (#815), V7 draws film grain from crystal layers, V8 keeps the gaps in dark lettering under Highlights and Shadows (#3460), V10 checks the Bradford white-balance fallback (craft-libs#587), V13 eases global Shadows off at large amounts and has negative Texture and the Global grading wheel act less, as measured against Lightroom exports (#523), V14 pins Heal and Remove spots to the photo on the spot's edge. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. |
| LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option |
| LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ Loupe Overlay ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option |
| LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders |
| LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | |
| LRC-DEV-HISTOGRAM-DRAG | Drag on the histogram to adjust tone regions | P2 | ✅ | `crates/ui-egui/src/panels/histogram.rs`, `crates/ui-egui/src/panels/edit.rs`, `crates/develop/src/controls.rs`, `crates/ui-egui/src/tests/histogram_drag.rs`, `cmd:develop.set`, `cmd:develop.beginInteraction`, `cmd:develop.endInteraction`, `ctl:light.blacks`, `ctl:light.shadows`, `ctl:light.exposure`, `ctl:light.highlights`, `ctl:light.whites` | five zones across the plot's width, each moving the Basic control it names: Blacks 0.00–0.15, Shadows 0.15–0.35, Exposure 0.35–0.65, Highlights 0.65–0.85, Whites 0.85–1.00; every step is a `develop.set` between `develop.beginInteraction` and `develop.endInteraction` (the sliders' own path), so the draft render follows the drag live and the whole drag lands as one undo step; the zone the press landed in stays locked for the drag, so dragging across the others changes nothing; sideways travel of the plot's width sweeps that control's whole range (Shift a tenth, as on the sliders), clamped to its spec; hovering a zone tints it and shows its value in the strip under the plot ("Exposure: +0.45 EV"), with the sideways-resize cursor; a double-click resets that zone's control to its default in one undo step; the strip under the plot (readout / EXIF) and the clipping buttons in the plot's top corners are not zones |
| LRC-MAP-VIEW | Map view | P2 | ⬜ | | |
| LRC-MAP-GEOTAG | Drag photos onto the map | P2 | ⬜ | | |
| LRC-MAP-LOCATIONS | Saved locations | P2 | ⬜ | | |
| LRC-MAP-TRACKLOG | GPS track logs | P2 | ✅ | `cmd:photo.autoTagTracklog`, `cmd:photo.tagFromTracklog`, `crates/meta/src/lib.rs` | Photo ▸ Auto-Tag from Tracklog…: a GPX 1.0 / 1.1 track log sets the GPS of the selected photos by capture time — interpolated between the points of a track segment, else the nearest point within `maxGap` (10 min); never across segment breaks. XML character references in coordinate attributes and point text decode before parsing; malformed or unknown references return an error; CDATA stays literal. The camera's time zone comes from the photo (Exif offset) or is asked for; photos that already have a location keep it unless `replace`; `dryRun` previews; one undo step. No track drawn on a map (no Map module); incomplete or malformed ISO point times are untimed and cannot match a photo |
| LRC-MAP-TRACKLOG | GPS track logs | P2 | ✅ | `cmd:photo.autoTagTracklog`, `cmd:photo.tagFromTracklog`, `crates/meta/src/lib.rs` | Photo ▸ Metadata ▸ Auto-Tag from Tracklog…: a GPX 1.0 / 1.1 track log sets the GPS of the selected photos by capture time — interpolated between the points of a track segment, else the nearest point within `maxGap` (10 min); never across segment breaks. XML character references in coordinate attributes and point text decode before parsing; malformed or unknown references return an error; CDATA stays literal. The camera's time zone comes from the photo (Exif offset) or is asked for; photos that already have a location keep it unless `replace`; `dryRun` previews; one undo step. No track drawn on a map (no Map module); incomplete or malformed ISO point times are untimed and cannot match a photo |
| LRC-MAP-FILTER | Location filter bar | P2 | ⬜ | | |
| LRC-MAP-REVGEO | Reverse geocoding | P2 | 🟡 | `cmd:metadata.reverseGeocode` | offline from GeoNames (City / State / Country, no sublocation); the list holds towns of 15 000 people or more, so a smaller town gets the nearest larger one (the tooltip and command help say so); `maxDistance` leaves City empty past a distance and names the town as `nearestCity` (issue #2242); no online provider |
| LRC-BOOK-SETTINGS | Book settings | P2 | ⬜ | | |
@@ -765,8 +766,8 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-
| LRC-SS-BACKDROP | Slideshow backdrop | P2 | ✅ | `cmd:slideshow.layout`, `path:crates/slideshow/src/compose.rs` | Background colour, Color Wash (a gradient from a second colour, full at the side its angle points to, at an opacity), Background Image (a library photo filling the slide at an opacity: "Use selected photo" in Settings ▸ Slideshow, `backgroundImage` in `slideshow.layout`; rendered once and shared by the slides). In the web build the composition runs on the main thread when a worker's render comes back |
| LRC-SS-TITLES | Slideshow titles | P2 | 🟡 | `cmd:slideshow.titles`, `cmd:slideshow.preview`, `path:crates/engine/src/slide_title.rs`, `path:crates/ui-egui/src/dialogs/settings/slide_titles.rs` | Intro screen and ending screen, each on or off (library preference, `slideshow.titles`; Settings ▸ Slideshow ▸ Titles): a background colour and, centred on it, the identity plate of the Overlays section (its text or image; Add Identity Plate) or the screen's own line of text, in the plate's colour or an override colour, at a scale (height as a share of the slide's shorter side; text wider than the slide shrinks to fit), for its own duration (default: the slide duration). Titles are items of the playback timeline: composed off the UI thread by the same composer at the screen's size, prepared ahead, waited for and faded like slides; the intro plays once before the first photo, the ending after the last photo when repeat is off; random order never moves them; ←/→ step across them; they never change the selection and the control bar shows Intro / End instead of n / N. `slideshow.preview {title}` renders a screen; the Settings preview shows Photo / Intro / Ending. An empty view still refuses to play ("no photos to show"). Missing: Classic's exact behaviour with Repeat on is not verified (we never show the ending, and show the intro only at the start, while repeating), the Identity Plate Editor's styled text (Inter SemiBold only), override colour leaves an image plate's colours alone, the Slideshow module's Titles panel (settings live in Settings ▸ Slideshow). Slideshow export (LRC-SS-EXPORT) includes them: a PDF page / JPEG each, and in video they hold and fade like slides |
| LRC-SS-MUSIC | Slideshow music | P2 | ⬜ | | |
| LRC-SS-PLAYBACK | Slideshow playback | P2 | 🟡 | `cmd:slideshow.playback`, `cmd:view.slideshowOptions`, `cmd:slideshow.togglePause`, `cmd:slideshow.next`, `cmd:slideshow.previous`, `cmd:slideshow.end`, `path:crates/slideshow/src/motion.rs` | Playback settings (library preference, `slideshow.playback`; Settings ▸ Slideshow, View ▸ Slideshow Options…): slide duration 0.5–120 s, fade 0–10 s (≤ slide; 0 = cut) as a crossfade or through a colour, random order (seeded shuffle, every photo once per pass, a new order each pass), repeat (off: ends after the last slide), prepare previews in advance (the next 2 slides render off the UI thread; a transition never starts before its slide is rendered — the current one is held), manual slideshow (`manual`: a slide, the intro or the ending stays up until ←/→ or the control bar changes it; exports keep the slide duration), pan and zoom (`panAndZoom`, off by default, with a Low–High amount `panAndZoomAmount` 0–1, default 0.5: each photo moves at constant speed from one window of itself to another over its slide's time, its fade in included, zooming in or out between about 1.0025× and 1.01× at Low and 1.03× and 1.12× at High, on a path from the playback seed, the pass and the photo, so every photo and every pass has its own path and a seed replays it; the photo moves inside its image cell and the backdrop stays still, except that with overlays on the whole slide moves with them; title screens don't move; pause freezes it, a photo fading out stays at its end view, a manual slideshow holds each photo at its start view, a single repeating photo starts each new path where the last one ended; these motion rules are LightCraft's own). Space / ←/→ (cut) / Esc and a control bar (previous, play/pause, next, n / N, end) that shows on pointer movement. Missing: the Slideshow module view and its "preview in the view" (phase 2 of the module plan), music and sync to music (LRC-SS-MUSIC), pan and zoom in exports (LRC-SS-EXPORT), choosing the screen to play on. Intro and ending screens play as items of the same timeline (LRC-SS-TITLES). Slides are composed with the layout, options and backdrop (LRC-SS-LAYOUT / OPTIONS / BACKDROP) and carry the overlays (LRC-SS-OVERLAYS) |
| LRC-SS-EXPORT | Slideshow export | P2 | 🟡 | `cmd:slideshow.export`, `cmd:slideshow.exportStatus`, `cmd:dialog.slideshowExport`, `cmd:app.slideshowExport`, `path:crates/engine/src/slideshow_export.rs`, `path:crates/codecs/src/video.rs`, `path:crates/ui-egui/src/dialogs/slideshow_export.rs` | View ▸ Export Slideshow… (and Export PDF / JPEG / Video in Settings ▸ Slideshow): the photos in view as their composed slides (layout, overlays) between the intro and ending screens that are on, in view order. **PDF**: one page per slide at 1024 / 1920 / 3840 px (any 64–8192 by command; page = slide pixels in points, aspect from the aspect preview, "screen" = 16:9), JPEG quality, each page carrying the slide duration and a fade transition for presentation mode, "Automatically show full screen" (`/PageMode /FullScreen`). **JPEG**: `<name>-001.jpg`… in a new folder. **Video**: AV1 (rav1e, fast preset) in MP4 or WebM written by our own muxers, 720p / 1080p (64–2160 by command), 24 / 30 fps (25 / 60 by command); each slide held for its duration (one long sample: variable frame rate) and fades rendered as blended frames (crossfade or through the fade colour); at most 2 hours. Runs in the background with a row in the activity stack (frames or slides done, ✕ cancels); files are written as `.part` and renamed when complete, so a cancelled or failed export leaves nothing; a photo that can't be rendered is skipped with a warning. Missing: H.264 (Classic's codec; patents, no pure-Rust encoder), audio / music in the video (LRC-SS-MUSIC), random order and pan & zoom in exports, the PDF's per-page fades follow the viewer (Acrobat), export presets, Classic's export dialog sizes beyond these, the web build (no export) |
| LRC-SS-PLAYBACK | Slideshow playback | P2 | 🟡 | `cmd:slideshow.playback`, `cmd:view.slideshowOptions`, `cmd:slideshow.togglePause`, `cmd:slideshow.next`, `cmd:slideshow.previous`, `cmd:slideshow.end`, `path:crates/slideshow/src/motion.rs` | Playback settings (library preference, `slideshow.playback`; Settings ▸ Slideshow, View ▸ Slideshow ▸ Slideshow Options…): slide duration 0.5–120 s, fade 0–10 s (≤ slide; 0 = cut) as a crossfade or through a colour, random order (seeded shuffle, every photo once per pass, a new order each pass), repeat (off: ends after the last slide), prepare previews in advance (the next 2 slides render off the UI thread; a transition never starts before its slide is rendered — the current one is held), manual slideshow (`manual`: a slide, the intro or the ending stays up until ←/→ or the control bar changes it; exports keep the slide duration), pan and zoom (`panAndZoom`, off by default, with a Low–High amount `panAndZoomAmount` 0–1, default 0.5: each photo moves at constant speed from one window of itself to another over its slide's time, its fade in included, zooming in or out between about 1.0025× and 1.01× at Low and 1.03× and 1.12× at High, on a path from the playback seed, the pass and the photo, so every photo and every pass has its own path and a seed replays it; the photo moves inside its image cell and the backdrop stays still, except that with overlays on the whole slide moves with them; title screens don't move; pause freezes it, a photo fading out stays at its end view, a manual slideshow holds each photo at its start view, a single repeating photo starts each new path where the last one ended; these motion rules are LightCraft's own). Space / ←/→ (cut) / Esc and a control bar (previous, play/pause, next, n / N, end) that shows on pointer movement. Missing: the Slideshow module view and its "preview in the view" (phase 2 of the module plan), music and sync to music (LRC-SS-MUSIC), pan and zoom in exports (LRC-SS-EXPORT), choosing the screen to play on. Intro and ending screens play as items of the same timeline (LRC-SS-TITLES). Slides are composed with the layout, options and backdrop (LRC-SS-LAYOUT / OPTIONS / BACKDROP) and carry the overlays (LRC-SS-OVERLAYS) |
| LRC-SS-EXPORT | Slideshow export | P2 | 🟡 | `cmd:slideshow.export`, `cmd:slideshow.exportStatus`, `cmd:dialog.slideshowExport`, `cmd:app.slideshowExport`, `path:crates/engine/src/slideshow_export.rs`, `path:crates/codecs/src/video.rs`, `path:crates/ui-egui/src/dialogs/slideshow_export.rs` | View ▸ Slideshow ▸ Export Slideshow… (and Export PDF / JPEG / Video in Settings ▸ Slideshow): the photos in view as their composed slides (layout, overlays) between the intro and ending screens that are on, in view order. **PDF**: one page per slide at 1024 / 1920 / 3840 px (any 64–8192 by command; page = slide pixels in points, aspect from the aspect preview, "screen" = 16:9), JPEG quality, each page carrying the slide duration and a fade transition for presentation mode, "Automatically show full screen" (`/PageMode /FullScreen`). **JPEG**: `<name>-001.jpg`… in a new folder. **Video**: AV1 (rav1e, fast preset) in MP4 or WebM written by our own muxers, 720p / 1080p (64–2160 by command), 24 / 30 fps (25 / 60 by command); each slide held for its duration (one long sample: variable frame rate) and fades rendered as blended frames (crossfade or through the fade colour); at most 2 hours. Runs in the background with a row in the activity stack (frames or slides done, ✕ cancels); files are written as `.part` and renamed when complete, so a cancelled or failed export leaves nothing; a photo that can't be rendered is skipped with a warning. Missing: H.264 (Classic's codec; patents, no pure-Rust encoder), audio / music in the video (LRC-SS-MUSIC), random order and pan & zoom in exports, the PDF's per-page fades follow the viewer (Acrobat), export presets, Classic's export dialog sizes beyond these, the web build (no export) |
| LRC-PRINT-LAYOUTSTYLE | Print layout styles | P2 | ✅ | `cmd:dialog.print`, `cmd:print.set`, `cmd:print.get`, `cmd:print.exportPdf`, `cmd:export.contactSheet`, `crates/ui-egui/src/dialogs/print_view.rs` | File → Print… (⌘P): Single Image, Contact Sheet, Picture Package and Custom Package, one page preview each; also `print.*` commands for the CLI, control channel and MCP; the older File → Contact Sheet PDF stays |
| LRC-PRINT-IMAGESETTINGS | Print image settings | P2 | ✅ | `cmd:print.set`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/dialogs/print_view.rs` | Zoom to Fill Frame, Rotate to Fit, Photo Border (width, colour; package styles) and Inner Stroke (width in points, colour) in the dialog, drawn in the preview and in the PDF; pixel-tested |
| LRC-PRINT-LAYOUT | Print layout | P2 | 🟡 | `cmd:print.set`, `cmd:print.layout.autoLayout`, `cmd:print.layout.newPage`, `cmd:print.layout.clear`, `cmd:app.print`, `cmd:export.contactSheet`, `crates/engine/src/print/layout.rs` | A3/A4/A5/Letter/Legal/Tabloid/4x6/5x7/8x10/13x19, the Japanese photo and postcard sizes (L判 89×127, 2L判 127×178, KG判 102×152, はがき 100×148, 往復はがき 148×200, 六切 203×254, 四切 254×305, 名刺 55×91 mm, by their customary names) and custom paper, portrait/landscape, per-side margins, grid with column/row spacing and square cells, 72–720 ppi, in a Print dialog with a scaled page preview; no printer-driver Page Setup, no cell size / alignment presets |
@@ -830,6 +831,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-10-28 | minor | LR-EDIT-OPTICS-PROFILE: lensfun's database offered once on the first launch and downloaded on request (Download / Not Now, Settings) (pinned, CC BY-SA, never bundled), the library looked up when it arrives or Enable Lens Corrections is ticked, the Optics panel names the profile or the lens without one; status unchanged (🟡) |
| 2026-10-26 | minor | LR-BEHAV-PANEL-RESIZE, KEY-INFO: closing a tool panel (Crop, Remove, Masking, Red Eye) puts back the panel shown before it, hidden if it was hidden, at the same width and scroll position; a panel key or button (I, M, C, H…) pressed again puts back exactly what the right column showed before it (Edit → I → I = Edit, closed → I → I = closed); status unchanged (✅) |
| 2026-10-25 | patch | LRC-LIB-KEYWORDS: a file whose keyword list is one `dc:subject` (or `lr:hierarchicalSubject`) entry with a keyword a line is read as one keyword a line; a library holding such a keyword is repaired when it opens (journaled, not an undo step); sidebar and Keyword List rows draw a name on one line; status unchanged |
| 2026-10-25 | minor | LR-BEHAV-WINDOW (new row, 🟡): on Windows a window remembered maximized is built at its size and maximized once it shows (built maximized it could cover half the screen while Windows took it for maximized), and restored and maximized again once if it only says so; a window remembered larger than the screen it opens on is fitted to it, on every platform |
| 2026-10-25 | minor | LR-EDIT-GEOM-UPRIGHT: ✅ → 🟡 (real shots of posts among people were not corrected; tuned on synthetic scenes only): a vertical family wins over a crowd of disagreeing lines unless they gather at a rival point, Vertical follows long posts rather than decks, drapes or gown folds; a mode that finds nothing says why |
| 2026-10-30 | patch | LR-BEHAV-ACCESS: the Flatpak manifests grant `--talk-name=org.a11y.Bus`, so AccessKit can find out whether a screen reader is running and publish the window inside the sandbox; packaging lint requires it in both manifests; status unchanged (🟡), not tried with Orca |
| 2026-10-27 | patch | LR-LIB-LABEL, MENU-PHOTO-LABEL, KEY-LABELS: Clear Color Label (`photo.clearLabel`) is a command of its own, so Help → Keyboard Shortcuts can give it a key (#2980); the Photo ▸ Set Color Label ▸ None row runs it; status unchanged |
@@ -1097,3 +1099,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-10-23 | patch | LR-BEHAV-MULTISELECT: `album.delete` and `album.move` take `ids`, `keyword.delete` and `keyword.move` take `keywords`, `library.removeFolder` and `folder.label` take `paths`, each as one undo step that checks everything before it changes anything (engine only; the sidebar's Cmd/Shift-click rows are the caller to come); downgraded ✅ → 🟡 until they exist |
| 2026-10-17 | minor | LR-BEHAV-DRAGDROP: Esc gives up a photo drag (and only the drag); album rows say how many photos a drop adds or that they are there already (a no-op drop changes nothing); smart albums, album folders and the sidebar's Keywords rows refuse photos with the not-allowed cursor and a reason; the Keyword List says how many photos get a keyword and refuses a keyword dropped inside itself; LR-LIB-ALBUM and LRC-LIB-KEYWORDS text updated; status unchanged (✅) |
| 2026-10-27 | patch | MENU-HELP-FEEDBACK: on macOS the Help menu no longer shows the system's `Send <app> Feedback` row beside Send Feedback… |
| 2026-10-17 | minor | LR-LIB-SMARTALBUM, LR-LIB-PEOPLE, LR-VIEW-FOCUSPOINT, LR-VIEW-BEFOREAFTER, LR-VIEW-SLIDESHOW, LR-BEHAV-SIDEBAR-HIDE, MENU-VIEW-PHOTOCOUNT, MENU-VIEW-SIDEBARSECTIONS, KEY-MASKCOLOR, LRC-LIB-METADATA, LRC-MAP-TRACKLOG, LRC-SS-PLAYBACK, LRC-SS-EXPORT, LRC-DEV-VIEWOPTIONS: menu bar reorganised; the rows now cite the new paths (View ▸ Loupe Overlay, Before/After, Mask Overlay, Slideshow, Sort; Window for panel toggles; Photo ▸ Metadata); no command changed and no status changed |
+3 -3
View File
@@ -2,8 +2,8 @@
LightCraft's slideshow follows Lightroom Classic's Slideshow module (no Adobe assets, templates or designs): the photos
in view played full screen with a layout, overlays, intro and ending screens and fades, and exported as PDF, JPEG or
video. There is no Slideshow module view yet: the settings live in Settings ▸ Slideshow (View ▸ Slideshow Options…)
next to a live preview of the selected photo's slide, and View ▸ Slideshow (⌥⌘↩) plays.
video. There is no Slideshow module view yet: the settings live in Settings ▸ Slideshow (View ▸ Slideshow ▸ Slideshow Options…)
next to a live preview of the selected photo's slide, and View ▸ Slideshow ▸ Slideshow (⌥⌘↩) plays.
| Part | Commands | Code |
|---|---|---|
@@ -21,7 +21,7 @@ the same pixels through the same composer.
## Export
View ▸ Export Slideshow… (or Export PDF / JPEG / Video at the end of Settings ▸ Slideshow) chooses a format and size,
View ▸ Slideshow ▸ Export Slideshow… (or Export PDF / JPEG / Video at the end of Settings ▸ Slideshow) chooses a format and size,
then asks where to write. The slides are the photos in view, in view order, between the intro and ending screens that
are on; random order, repeat, manual slideshow and pan and zoom are playback choices and don't apply. The slide aspect is the Layout's aspect preview
(Screen exports 16:9).
+23
View File
@@ -543,6 +543,11 @@
itself".
- Esc gives up a drag of photos, as it already did for albums, sidebar sections and keywords: that press ends the drag and does nothing else
(it does not also close a dialog, leave full screen or light back on). A drag started before entering full screen or a slideshow now ends with the mouse button, so Esc works there again.
### A library keeps a copy of itself before it is upgraded
- Opening a library saved in an older catalog format upgrades it, and versions that don't know the new format can't
open it afterward. In the desktop app, the library as it was is now kept beside it (`catalog.snap.v<format>-<seq>`,
`catalog.log.v<format>-<seq>`), and LightCraft says where once: to go back, see `docs/catalog-persistence.md`. A
library that can't be kept is not upgraded. The browser build keeps no copy (it always runs the newest version).
### A right-click on a text field while you carry photos opens no menu
- While you drag photos from the grid, a right-click on a text field, such as the search box, opens no Cut, Copy and
Paste menu. Before, the menu opened over the field the photos were on. Right-clicking a field without a drag works
@@ -650,6 +655,13 @@
- When an archive with the history settings would be too big (over 32 MiB), it is now saved without them, with a
warning, instead of not at all.
### Big libraries take less memory
- Photos whose develop settings are equal now hold them once in memory: every unedited JPEG, PNG or other rendered
file, every raw on the same import look, and the equal history steps, versions and import looks of one photo. (A
raw's unedited Kelvin settings carry its own as-shot white balance, so those share only with raws of the very same
white balance.) On a test library of 100,000 photos, 90 % unedited JPEGs, 8 % raws with one as-shot white balance
and 2 % edited, a photo takes about 2.8 kB where it took 4.4 kB (285 MB instead of 441 MB). Nothing changes on
screen, and the library's files are byte for byte what they were, so earlier versions open them as before.
## 2026-10-23
### AI Denoise works out of the box
@@ -1023,6 +1035,17 @@
over from a Lightroom catalog don't until you run Photo ▸ Reload from Disk on them, so they match nothing until
then, even when their files are identical.
### Menus that fit the screen
- The View menu is down from 63 rows to 36, so it opens without scrolling on a laptop's menu bar. Its overlays,
before/after and slideshow items sit in submenus: Loupe Overlay, Before/After, Mask Overlay (every overlay mode and
colour, with the current one checked), Crop Overlay and Slideshow.
- The panel toggles (My Photos Panel, Right Panel, Sidebar Sections, Photo Counts, Filmstrip, Histogram, Navigator) moved to
the Window menu. Photo ▸ Metadata gathers the metadata commands, including Metadata Preset, Save Metadata to File
and Detect Faces.
- File no longer lists Discard Preview Cache twice (it is one command), View no longer lists
Choose and Layout Image twice, and every command has a fixed place instead of sitting in a pile at the end of
its menu.
- Keyboard shortcuts are unchanged.
### Sharper resampling in HDR and panorama merges
- Merged photos (HDR and panorama) are resampled with a sharper filter (Lanczos-3 instead of bilinear). Moving a
photo by half a pixel used to lose a third of its finest detail; now it keeps most of it, without halos around
+1 -1
View File
@@ -9,7 +9,7 @@ other tools), and let LightCraft pick up edits made elsewhere.
| | |
|---|---|
| Name | `<stem>.xmp` by default (`IMG_0001.CR3` → `IMG_0001.xmp`); `<file>.xmp` (`IMG_0001.CR3.xmp`) with `naming: "full"`. Reading accepts either (preferred first) and `.XMP`. With stem naming, files sharing a stem don't share a sidecar: see *Shared names* below. |
| Write | `photo.saveMetadataToFile {ids?}` (Photo ▸ Save Metadata to File, ⌘S), or automatically after every change with `library.xmpPreferences {autoWrite: true}` (File ▸ Automatically Write Changes into XMP). Slider drags are written once, when the drag ends; undo/redo rewrite the sidecar. An existing sidecar is **merged into, never replaced** (see *Saving into an existing sidecar*). Written atomically (temp file, fsync, rename). The result lists `written`, `merged` and `backups`. |
| Write | `photo.saveMetadataToFile {ids?}` (Photo ▸ Metadata ▸ Save Metadata to File, ⌘S), or automatically after every change with `library.xmpPreferences {autoWrite: true}` (File ▸ Automatically Write Changes into XMP). Slider drags are written once, when the drag ends; undo/redo rewrite the sidecar. An existing sidecar is **merged into, never replaced** (see *Saving into an existing sidecar*). Written atomically (temp file, fsync, rename). The result lists `written`, `merged` and `backups`. |
| Read | On import (`library.import`, the report counts `sidecars`), and `photo.readMetadataFromFile {ids?}` (one undo step). Manual rereading uses embedded XMP in raw/DNG and JPEG files when no sidecar exists. A discovered sidecar that cannot be read or parsed is reported in `failed`, without applying embedded values. `photo.readMetadataFromFile` never writes the sidecar, even with auto-write on: writing back what it has just read would add `lc:settings`, which later reads prefer over another app's `crs:` edits (issue #934). A file arriving in an import is ranked as if it were catalogued already: it reads its own `<file>.xmp` when another file of its stem (a raw first) owns the shared stem sidecar (issue #1905). |
| Preferences | `library.xmpPreferences {autoWrite?, naming?: stem\|full}`, stored in the library's `prefs.json`. |
+2
View File
@@ -45,6 +45,8 @@ const EMBEDDED: &[(&str, &[&str])] = &[
("xtask/src/raw_samples.rs", &["lightcraft-raw"]),
("crates/ui-egui/src/menus.rs", &["xtask"]),
("crates/ui-egui/src/menus/", &["xtask"]),
("crates/catalog/src/fixtures/v6-catalog.snap.json", &["lightcraft-engine"]),
("crates/catalog/src/fixtures/v6-catalog.log.jsonl", &["lightcraft-engine"]),
];
/// The packages that compile in `path` from outside their own directory.