LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Library: Random sort with a stable seed and Reshuffle
Nathaniel Ledforda72118ec6e65
diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rsindex 097a71790..208a86d09 100644--- a/crates/catalog/src/lib.rs+++ b/crates/catalog/src/lib.rs@@ -35,7 +35,7 @@ use lightcraft_develop::DevelopSettings;pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, folder_of};pub use lock::{LibraryLock, LockError, LockOwner};pub use model::*;-pub use query::{DateGroup, Filter, Person, RatingOp, Sort, SortKey};+pub use query::{DateGroup, Filter, Person, RatingOp, Sort, SortKey, mix64};pub use rules::{Match, Rule, RuleSet};use serde::{Deserialize, Serialize};pub use store::{FsStore, MemStore, Store};diff --git a/crates/catalog/src/query.rs b/crates/catalog/src/query.rsindex 384c2ae55..d06e13700 100644--- a/crates/catalog/src/query.rs+++ b/crates/catalog/src/query.rs@@ -72,6 +72,9 @@ pub enum SortKey {FileName,Rating,FileSize,+ /// A shuffle fixed by [`Sort::seed`]: the same seed always gives the same order, and photos+ /// added or edited later never reshuffle the others. Pick a new seed to reshuffle.+ Random,}#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]@@ -81,14 +84,30 @@ pub struct Sort {pub ascending: bool,/// Date headers in the grid (date sort keys only).pub group: crate::GroupBy,+ /// Which shuffle [`SortKey::Random`] gives (ignored by the other keys).+ pub seed: u64,}impl Default for Sort {fn default() -> Self {- Sort { key: SortKey::CaptureDate, ascending: false, group: crate::GroupBy::Auto }+ Sort { key: SortKey::CaptureDate, ascending: false, group: crate::GroupBy::Auto, seed: 0 }}}+/// splitmix64 finaliser: a stateless, platform-independent mix (no RNG state, no `rand` version+/// to drift), so a seed names the same shuffle on every machine.+pub fn mix64(x: u64) -> u64 {+ let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15);+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);+ z ^ (z >> 31)+}++/// A photo's place in the shuffle for `seed`.+fn shuffle_rank(seed: u64, id: PhotoId) -> u64 {+ mix64(mix64(seed) ^ id.0)+}+fn token_matches(p: &Photo, tok: &str) -> bool {let t = tok.to_lowercase();if let Some((field, val)) = t.split_once(':') {@@ -307,6 +326,7 @@ impl Catalog {SortKey::FileName => a.file_name.to_lowercase().cmp(&b.file_name.to_lowercase()),SortKey::Rating => a.rating.cmp(&b.rating),SortKey::FileSize => a.file_size.cmp(&b.file_size),+ SortKey::Random => shuffle_rank(sort.seed, a.id).cmp(&shuffle_rank(sort.seed, b.id)),}.then(a.id.cmp(&b.id));if sort.ascending { o } else { o.reverse() }diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rsindex 6f76b694e..49f0ac4de 100644--- a/crates/catalog/src/tests.rs+++ b/crates/catalog/src/tests.rs@@ -380,3 +380,69 @@ fn empty_regions_are_not_serialized_and_default_when_missing() {let back: Meta = serde_json::from_str(&serde_json::to_string(&with).unwrap()).unwrap();assert_eq!(back, with);}++// ---- random sort: Given a seed, the order is a stable, reproducible shuffle of the matching photos++fn many(c: &mut Catalog, n: usize) -> Vec<PhotoId> {+ (0..n).map(|i| photo(c, &format!("p{i:03}.jpg"), &format!("2026-04-{:02}T10:00:00", i % 28 + 1))).collect()+}++fn random(seed: u64) -> Sort {+ Sort { key: SortKey::Random, seed, ..Default::default() }+}++#[test]+fn random_sort_is_a_reproducible_permutation() {+ let mut c = Catalog::new();+ let ids = many(&mut c, 50);+ let a = c.query(&Filter::default(), &random(7));+ assert_eq!(a, c.query(&Filter::default(), &random(7)), "same seed, same order");+ let mut sorted = a.clone();+ sorted.sort();+ let mut all = ids.clone();+ all.sort();+ assert_eq!(sorted, all, "every photo exactly once");+ assert_ne!(a, c.query(&Filter::default(), &random(8)), "another seed, another order");+ assert_ne!(a, c.query(&Filter::default(), &Sort::default()), "not just the date order");+}++#[test]+fn random_sort_keeps_the_relative_order_when_the_set_changes() {+ let mut c = Catalog::new();+ let ids = many(&mut c, 30);+ let before = c.query(&Filter::default(), &random(3));+ let added = photo(&mut c, "new.jpg", "2026-05-01T10:00:00");+ c.apply(Op::SetRating { id: ids[0], rating: 5 }).unwrap();+ let after: Vec<PhotoId> = c.query(&Filter::default(), &random(3)).into_iter().filter(|id| *id != added).collect();+ assert_eq!(after, before, "adding a photo or editing metadata must not reshuffle the others");+}++#[test]+fn random_sort_respects_the_filter_and_handles_tiny_sets() {+ let mut c = Catalog::new();+ assert!(c.query(&Filter::default(), &random(1)).is_empty());+ let ids = many(&mut c, 10);+ c.apply(Op::SetRating { id: ids[4], rating: 5 }).unwrap();+ assert_eq!(c.query(&Filter { rating: 5, ..Default::default() }, &random(1)), vec![ids[4]]);+}++#[test]+fn random_sort_direction_reverses_and_serde_defaults_hold() {+ let mut c = Catalog::new();+ many(&mut c, 20);+ let desc = c.query(&Filter::default(), &Sort { ascending: false, ..random(5) });+ let mut asc = c.query(&Filter::default(), &Sort { ascending: true, ..random(5) });+ asc.reverse();+ assert_eq!(desc, asc);+ // saved sorts from before the seed existed still load+ let old: Sort = serde_json::from_str(r#"{"key":"fileName","ascending":true}"#).unwrap();+ assert_eq!(old.seed, 0);+ assert_eq!(serde_json::from_str::<Sort>(r#"{"key":"random","seed":9}"#).unwrap(), Sort { key: SortKey::Random, seed: 9, ..Default::default() });+}++#[test]+fn random_sort_has_no_date_headers() {+ let mut c = Catalog::new();+ let ids = many(&mut c, 5);+ assert!(c.date_runs(&ids, SortKey::Random, GroupBy::Day).is_empty());+}diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rsindex 841006387..da4debf23 100644--- a/crates/engine/src/cmd/library.rs+++ b/crates/engine/src/cmd/library.rs@@ -224,6 +224,22 @@ fn select_by(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"selected": n}))}+/// `seed` as a non-negative integer, or `default` when absent; anything else is an error.+fn seed_param(p: &Value, cmd: &str, default: u64) -> Result<u64> {+ match p.get("seed") {+ None | Some(Value::Null) => Ok(default),+ Some(v) => v.as_u64().ok_or_else(|| bad(cmd, "seed must be a non-negative integer")),+ }+}++/// The seed after `prev` at time `now`: a mix of `prev` and the clock text, so repeated reshuffles+/// within one clock tick still differ (barring a 2^-53 collision). Kept below 2^53 so JSON+/// clients that read numbers as doubles (web, MCP agents) get the same seed back.+fn next_seed(prev: u64, now: &str) -> u64 {+ let t = now.bytes().fold(0u64, |h, b| lightcraft_catalog::mix64(h ^ u64::from(b)));+ (lightcraft_catalog::mix64(prev.wrapping_add(1)) ^ t) & ((1 << 53) - 1)+}+pub fn specs() -> Vec<CommandSpec> {vec![// ---- view source / filter / sort@@ -281,7 +297,7 @@ pub fn specs() -> Vec<CommandSpec> {"Sort",["View", "Sort"],None,- "{key?: captureDate|importDate|editDate|fileName|rating|fileSize, ascending?: bool, group?: auto|none|day|month|year}",+ "{key?: captureDate|importDate|editDate|fileName|rating|fileSize|random, ascending?: bool, group?: auto|none|day|month|year, seed?: u64 (the shuffle `random` gives)}",always,|s, p| {let key: SortKey = match p.get("key") {@@ -292,7 +308,26 @@ pub fn specs() -> Vec<CommandSpec> {Some(g) => GroupBy::parse(g).ok_or_else(|| bad("library.sort", "group must be auto|none|day|month|year"))?,None => s.sort.group,};- s.sort = Sort { key, ascending: bool_or(p, "ascending", s.sort.ascending), group };+ let seed = seed_param(p, "library.sort", s.sort.seed)?;+ s.sort = Sort { key, ascending: bool_or(p, "ascending", s.sort.ascending), group, seed };+ ok()+ }+ ),+ cmd!(+ "library.shuffle",+ "Reshuffle",+ ["View", "Sort"],+ None,+ "{seed?: u64} — sort at random; without `seed` a new shuffle each time",+ always,+ |s, p| {+ let seed = match seed_param(p, "library.shuffle", s.sort.seed)? {+ given if p.get("seed").is_some() => given,+ // derived from the previous seed and the session clock: reproducible under a test+ // clock, and no RNG needed+ prev => next_seed(prev, &(s.clock)()),+ };+ s.sort = Sort { key: SortKey::Random, seed, ..s.sort };ok()}),diff --git a/crates/engine/src/tests_libops.rs b/crates/engine/src/tests_libops.rsindex 909414984..9bc6f0551 100644--- a/crates/engine/src/tests_libops.rs+++ b/crates/engine/src/tests_libops.rs@@ -466,3 +466,72 @@ fn tracklog_auto_tag() {assert!(s.execute("photo.autoTagTracklog", &json!({"gpx": GPX, "ids": [ids[0]], "offset": "noon"})).is_err());let _ = std::fs::remove_dir_all(&dir);}++// ---- random sort: Given the library, When the user picks Random, Then the grid is a stable shuffle++#[test]+fn random_sort_is_stable_until_reshuffled() {+ use lightcraft_catalog::SortKey;+ let mut s = Session::with_demo();+ let dated = s.visible_cloned();+ s.execute("library.sort", &json!({"key": "random", "seed": 11})).unwrap();+ assert_eq!((s.sort.key, s.sort.seed), (SortKey::Random, 11));+ let a = s.visible_cloned();+ assert_ne!(a, dated);+ let mut sorted = a.clone();+ sorted.sort();+ let mut all = dated.clone();+ all.sort();+ assert_eq!(sorted, all, "a permutation of the same photos");+ // an unrelated catalog change must not move anything+ let first = a[0];+ s.execute("photo.rate", &json!({"rating": 4, "ids": [first.0]})).unwrap();+ assert_eq!(s.visible_cloned(), a, "same seed, same grid after an edit");+ assert_eq!(s.execute("library.groups", &json!({})).unwrap(), json!([]), "no date headers for a shuffle");+ // Reshuffle picks a new seed (and works even with a frozen clock)+ s.execute("library.shuffle", &json!({})).unwrap();+ let seed1 = s.sort.seed;+ assert_eq!(s.sort.key, SortKey::Random);+ assert_ne!(seed1, 11);+ assert_ne!(s.visible_cloned(), a);+ s.execute("library.shuffle", &json!({})).unwrap();+ assert_ne!(s.sort.seed, seed1, "every reshuffle is new");+ assert!(s.sort.seed < 1 << 53, "seeds survive a round trip through a JSON double");+ // an explicit seed is reproducible+ s.execute("library.shuffle", &json!({"seed": 11})).unwrap();+ assert_eq!(s.visible_cloned(), a);+}++#[test]+fn random_sort_rejects_bad_params() {+ let mut s = Session::with_demo();+ let before = s.sort;+ assert!(s.execute("library.sort", &json!({"seed": "x"})).is_err());+ assert!(s.execute("library.sort", &json!({"seed": -1})).is_err());+ assert!(s.execute("library.shuffle", &json!({"seed": 1.5})).is_err());+ assert_eq!(s.sort, before, "a rejected command leaves the sort alone");+}++#[test]+fn random_sort_applies_to_albums_and_folders_too() {+ let mut s = Session::with_demo();+ s.execute("library.sort", &json!({"key": "random", "seed": 5})).unwrap();+ let all = s.visible_cloned();+ let ids: Vec<u64> = all.iter().take(12).map(|i| i.0).collect();+ let album = s.execute("album.create", &json!({"name": "Shuffled"})).unwrap()["id"].as_u64().unwrap();+ s.execute("album.addPhotos", &json!({"id": album, "ids": ids})).unwrap();+ s.execute("library.source", &json!({"kind": "album", "id": album})).unwrap();+ let in_album = s.visible_cloned();+ assert_eq!(in_album.len(), 12);+ let expect: Vec<_> = all.iter().filter(|i| in_album.contains(i)).copied().collect();+ assert_eq!(in_album, expect, "the album shows its photos in the shuffle's order, not manual order");+}++/// The shuffle comes back after a restart (the sort is part of the saved view state).+#[test]+fn random_sort_survives_view_state_round_trip() {+ use lightcraft_catalog::{Sort, SortKey};+ let sort = Sort { key: SortKey::Random, seed: u64::MAX, ..Default::default() };+ let back: Sort = serde_json::from_str(&serde_json::to_string(&sort).unwrap()).unwrap();+ assert_eq!(back, sort);+}diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.jsonindex f131d0b46..ca2089af2 100644--- a/crates/ui-egui/locales/ja.json+++ b/crates/ui-egui/locales/ja.json@@ -287,6 +287,8 @@"File Name": "ファイル名","File Path": "ファイルの場所","File Size": "ファイルサイズ",+ "Random": "ランダム",+ "Reshuffle": "シャッフルし直す","File name": "ファイル名","Fill Edges": "境界を補完","Filmstrip": "フィルムストリップ",diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.jsonindex 7dc4d7c3b..9bf5a5972 100644--- a/crates/ui-egui/locales/zh-hans.json+++ b/crates/ui-egui/locales/zh-hans.json@@ -287,6 +287,8 @@"File Name": "文件名","File Path": "文件路径","File Size": "文件大小",+ "Random": "随机",+ "Reshuffle": "重新随机排序","File name": "文件名","Fill Edges": "填充边缘","Filmstrip": "胶片窗格",diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.jsonindex 79c952917..db538f485 100644--- a/crates/ui-egui/locales/zh-hant.json+++ b/crates/ui-egui/locales/zh-hant.json@@ -389,6 +389,8 @@"File Name": "檔案名稱","File Path": "檔案路徑","File Size": "檔案大小",+ "Random": "隨機",+ "Reshuffle": "重新隨機排序","File name": "檔案名稱","Fill Edges": "填補邊緣","Film": "底片",diff --git a/crates/ui-egui/src/menubar.rs b/crates/ui-egui/src/menubar.rsindex 7e8054f27..f47d86dea 100644--- a/crates/ui-egui/src/menubar.rs+++ b/crates/ui-egui/src/menubar.rs@@ -458,13 +458,16 @@ fn expanded(app: &LightcraftApp, name: &str) -> Option<Vec<MenuNode>> {("File Name", FileName, "fileName"),("Rating", Rating, "rating"),("File Size", FileSize, "fileSize"),+ ("Random", Random, "random"),].into_iter().map(|(label, key, k)| item("library.sort", json!({"key": k}), label, None, true, Some(cur.key == key))).collect();+ v.push(item("library.shuffle", json!({}), "Reshuffle", None, cur.key == Random, None));v.push(MenuNode::Separator);- v.push(item("library.sort", json!({"ascending": true}), "Ascending", None, true, Some(cur.ascending)));- v.push(item("library.sort", json!({"ascending": false}), "Descending", None, true, Some(!cur.ascending)));+ // a shuffle has no direction worth choosing+ v.push(item("library.sort", json!({"ascending": true}), "Ascending", None, cur.key != Random, Some(cur.ascending)));+ v.push(item("library.sort", json!({"ascending": false}), "Descending", None, cur.key != Random, Some(!cur.ascending)));v.push(MenuNode::Separator);use lightcraft_catalog::GroupBy;let groups = [diff --git a/crates/ui-egui/src/panels/bottombar.rs b/crates/ui-egui/src/panels/bottombar.rsindex e36cba6a5..7ae6f3fe6 100644--- a/crates/ui-egui/src/panels/bottombar.rs+++ b/crates/ui-egui/src/panels/bottombar.rs@@ -242,19 +242,26 @@ fn sort_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) {("File Name", FileName, "fileName"),("Rating", Rating, "rating"),("File Size", FileSize, "fileSize"),+ ("Random", Random, "random"),] {if ui.selectable_label(cur.key == key, crate::i18n::tr(label)).clicked() {let _ = app.run("library.sort", json!({"key": k}));}}- ui.separator();- if ui.selectable_label(cur.ascending, crate::i18n::tr("Ascending")).clicked() {- let _ = app.run("library.sort", json!({"ascending": true}));- }- if ui.selectable_label(!cur.ascending, crate::i18n::tr("Descending")).clicked() {- let _ = app.run("library.sort", json!({"ascending": false}));+ if cur.key == Random && ui.button(crate::i18n::tr("Reshuffle")).clicked() {+ let _ = app.run("library.shuffle", json!({}));}ui.separator();+ // a shuffle has no direction worth choosing+ ui.add_enabled_ui(cur.key != Random, |ui| {+ if ui.selectable_label(cur.ascending, crate::i18n::tr("Ascending")).clicked() {+ let _ = app.run("library.sort", json!({"ascending": true}));+ }+ if ui.selectable_label(!cur.ascending, crate::i18n::tr("Descending")).clicked() {+ let _ = app.run("library.sort", json!({"ascending": false}));+ }+ });+ ui.separator();ui.label(egui::RichText::new(crate::i18n::tr("Group by date")).weak());for (label, g, k) in [("Automatic", GroupBy::Auto, "auto"),diff --git a/docs/parity.md b/docs/parity.mdindex 827299711..e1198880c 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -199,7 +199,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins.| LR-FILT-LOCATION | Location filter | P2 | ✅ | `cmd:library.filter` (`text`, `ruleSet` field `location`) | free text, or a rule on location / city / state / country (smart albums, `library.filter`) || LR-FILT-PEOPLE | People filter | P2 | 🟡 | `cmd:library.filter`, `crates/catalog/src/query.rs` | filter by a person's name (case-insensitive, named Face regions only) from the People view, a filter chip or `person:`; no unnamed / suggested people || LR-FILT-CULL | Culling-score filters | P2 | ✅ | `cmd:library.filter` (`ruleSet` fields `sharpness`, `bestOfGroup`) | Focus and Best of Similar Shots in the rule editor / smart albums |-| LR-FILT-SORT | Sort | P0 | ✅ | `cmd:library.sort`, `crates/ui-egui/src/panels/bottombar.rs` | no colour-label or custom (manual) order |+| LR-FILT-SORT | Sort | P0 | ✅ | `cmd:library.sort`, `cmd:library.shuffle`, `crates/ui-egui/src/panels/bottombar.rs` | Random sort (seeded, stable under edits; Reshuffle picks a new seed); the shuffle is part of the saved view state; no effect in Recently Added (always newest import first); no colour-label or custom (manual) order || LR-FILT-SAVED | Filter presets [Classic] | P2 | ✅ | `cmd:filter.savePreset`, `cmd:filter.applyPreset`, `cmd:filter.presets`, `cmd:filter.deletePreset`, `crates/ui-egui/src/panels/filterbar.rs` | filter bar → Presets: apply, save current filter, delete (right-click); saved with the library |## E. Metadata (META)@@ -570,7 +570,7 @@ visible menu bar yet: the menu model is only exposed through the control channel| MENU-VIEW-CLIPPING | Show 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-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` | no colour-label key |+| 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 ▸ Show Photo Counts toggles the left panel's counts || MENU-VIEW-HDR | HDR display options | P2 | ⬜ | | |