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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 64 additions & 10 deletions crates/engine/src/cmd/library/specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,53 @@ fn seed_param(p: &Value, cmd: &str, default: u64) -> Result<u64> {
}
}

/// The seed after `prev` at time `now`: a mix of `prev` and the clock text, so repeated reshuffles
/// The seed after `prev` at time `now`, with `count` shuffles made before: a mix of the three, 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)));
fn next_seed(prev: u64, now: &str, count: u64) -> u64 {
let t = now.bytes().fold(count, |h, b| lightcraft_catalog::mix64(h ^ u64::from(b)));
(lightcraft_catalog::mix64(prev.wrapping_add(1)) ^ t) & (MAX_SEED - 1)
}

/// How many replaced shuffles `library.previousShuffle` can step back through.
const MAX_SHUFFLE_HISTORY: usize = 32;

/// Change the sort. While shuffling, a different seed replaces the order shown, so the seed it replaces is kept for
/// `library.previousShuffle` (the oldest is dropped past [`MAX_SHUFFLE_HISTORY`]); leaving Random forgets them all, as
/// they would restore an order nobody sees any more.
fn set_sort(s: &mut crate::Session, new: Sort) {
let old = s.sort;
if new.key == SortKey::Random && old.key == SortKey::Random {
if new.seed != old.seed {
if s.shuffle_history.len() >= MAX_SHUFFLE_HISTORY {
s.shuffle_history.remove(0);
}
s.shuffle_history.push(old.seed);
}
} else {
s.shuffle_history.clear();
}
s.sort = new;
}

/// `library.previousShuffle` is on while sorting at random with a replaced shuffle to go back to.
fn can_go_back(s: &crate::Session) -> std::result::Result<(), String> {
if s.sort.key != SortKey::Random {
Err("the view is not sorted at random".into())
} else if s.shuffle_history.is_empty() {
Err("no earlier shuffle".into())
} else {
Ok(())
}
}

/// A new shuffle after `prev`. The clock only ticks in seconds, and Previous Shuffle can return to a seed whose successor
/// was already made, so the count of shuffles made this session goes in too: a Reshuffle is never the order just left.
fn fresh_seed(s: &mut crate::Session, prev: u64) -> u64 {
s.shuffle_count += 1;
next_seed(prev, &(s.clock)(), s.shuffle_count)
}

pub fn specs() -> Vec<CommandSpec> {
vec![
// ---- view source / filter / sort
Expand Down Expand Up @@ -233,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Sort",
["View", "Sort"],
None,
"{key?: captureDate|importDate|editDate|fileName|rating|fileSize|random, ascending?: bool, group?: auto|none|day|month|year, seed?: u64 (the shuffle `random` gives)}",
"{key?: captureDate|importDate|editDate|fileName|rating|fileSize|random, ascending?: bool, group?: auto|none|day|month|year, seed?: u64 (the shuffle `random` gives)} — the sort is kept as asked in every view, but Recently Added is always newest import first whatever it says (its menus turn the keys and the direction off; it still groups by import date, at the chosen grouping). Elsewhere only the date keys (captureDate, importDate, editDate) draw date headers, so `group` is kept but unused for the other keys, and Recently Deleted draws none",
always,
|s, p| {
let key: SortKey = match p.get("key") {
Expand All @@ -248,9 +287,10 @@ pub fn specs() -> Vec<CommandSpec> {
let explicit = p.get("seed").is_some_and(|v| !v.is_null());
if key == SortKey::Random && s.sort.key != SortKey::Random && !explicit {
// switching to Random is a fresh shuffle, not whatever seed was left behind
seed = next_seed(seed, &(s.clock)());
seed = fresh_seed(s, seed);
}
s.sort = Sort { key, ascending: bool_or(p, "ascending", s.sort.ascending), group, seed };
let sort = Sort { key, ascending: bool_or(p, "ascending", s.sort.ascending), group, seed };
set_sort(s, sort);
ok()
}
),
Expand Down Expand Up @@ -296,17 +336,31 @@ pub fn specs() -> Vec<CommandSpec> {
"library.shuffle",
"Reshuffle",
["View", "Sort"],
None,
"{seed?: 0..2^53-1} — sort at random; without `seed` a new shuffle each time",
Some("Cmd+Alt+Shift+R"),
"{seed?: 0..2^53-1} — sort at random; without `seed` a new shuffle each time (the one it replaces can come back with `library.previousShuffle`). Recently Added ignores the sort and stays newest import first, so a reshuffle there only switches the stored sort to Random with a new seed and changes no order on screen (it still ends a held view, like any sort change; the menus keep Reshuffle off in that view)",
always,
|s, p| {
let seed = match seed_param(p, "library.shuffle", s.sort.seed)? {
given if p.get("seed").is_some_and(|v| !v.is_null()) => 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)()),
prev => fresh_seed(s, prev),
};
s.sort = Sort { key: SortKey::Random, seed, ..s.sort };
let sort = Sort { key: SortKey::Random, seed, ..s.sort };
set_sort(s, sort);
ok()
}
),
cmd!(
"library.previousShuffle",
"Previous Shuffle",
["View", "Sort"],
Some("Cmd+Alt+Shift+P"),
"{} — go back to the shuffle a Reshuffle (or a new `seed` given while sorting at random) replaced: the same seed, so the exact earlier order. Steps back through up to 32 of them, newest first; going back is not itself kept, so a Reshuffle after it is a new shuffle. Only while sorting at random with an earlier shuffle; the list lives in the session only (never saved with the view) and is forgotten when the sort leaves Random or another library opens",
can_go_back,
|s, _| {
let seed = s.shuffle_history.pop().ok_or_else(|| bad("library.previousShuffle", "no earlier shuffle"))?;
s.sort = Sort { seed, ..s.sort };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2. Restore the sort direction with the previous shuffle seed. Random order also honors ascending, but this history saves only the seed. Shuffle while ascending, reshuffle, change direction, then use Previous Shuffle: it restores the old seed under the new direction. Store both values or clear the history on a direction change. Cover that sequence in the shuffle regression.

ok()
}
),
Expand Down
12 changes: 12 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,11 @@ pub struct Session {
/// The filter `library.toggleFilters` put aside (Library > Enable Filters off); not persisted.
pub(crate) shelved_filter: Option<Filter>,
pub sort: Sort,
/// The seeds Reshuffle replaced during this stay in Random, newest last (`library.previousShuffle`). Session-only:
/// never saved with the view. Empty unless the sort is Random.
pub(crate) shuffle_history: Vec<u64>,
/// New shuffles made this session; mixed into each new seed so two in the same clock second differ.
pub(crate) shuffle_count: u64,
pub selection: Selection,
/// The grid order for the current source/filter/sort (cached by catalog revision).
/// Shared, so frontends can hold it across frames without copying ([`Session::visible_shared`]).
Expand Down Expand Up @@ -453,6 +458,8 @@ impl Session {
filter: Filter::default(),
shelved_filter: None,
sort: Sort::default(),
shuffle_history: Vec::new(),
shuffle_count: 0,
selection: Selection::default(),
visible: Vec::new().into(),
visible_key: None,
Expand Down Expand Up @@ -1213,6 +1220,11 @@ impl Session {
f
}

/// Whether `library.previousShuffle` has a replaced shuffle to go back to (only while the sort is Random).
pub fn has_previous_shuffle(&self) -> bool {
self.sort.key == lightcraft_catalog::SortKey::Random && !self.shuffle_history.is_empty()
}

/// Let go of what a held view kept: the view shows what matches now ([`Session::hold_view`]).
pub fn refresh_view(&mut self) {
self.base = None;
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,8 @@ impl Session {
self.selection = Selection::default();
self.source = LibrarySource::All;
self.library_folder = None;
// (the orders of the last library's shuffles don't exist in this one)
self.shuffle_history.clear();
if report.created && seed_demo {
crate::demo::load(self);
journal.snapshot(&self.catalog)?;
Expand Down
90 changes: 90 additions & 0 deletions crates/engine/src/tests/libops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,96 @@ fn random_sort_is_stable_until_reshuffled() {
assert_eq!(s.visible_cloned(), a);
}

// ---- Previous Shuffle: Given a reshuffle that replaced a good order, When the user asks for the previous shuffle, Then that exact order is back

fn previous_shuffle_enabled(s: &Session) -> bool {
crate::cmd::find_command("library.previousShuffle").expect("the command exists").info(s).enabled
}

#[test]
fn previous_shuffle_restores_the_exact_earlier_order_one_reshuffle_at_a_time() {
let mut s = Session::with_demo();
s.execute("library.sort", &json!({"key": "random", "seed": 11})).unwrap();
let first = s.visible_cloned();
assert!(!previous_shuffle_enabled(&s), "no reshuffle has replaced anything yet");
s.execute("library.shuffle", &json!({})).unwrap();
let second = s.visible_cloned();
s.execute("library.shuffle", &json!({})).unwrap();
let third = s.visible_cloned();
assert!(first != second && second != third, "each reshuffle is a new order");
assert!(previous_shuffle_enabled(&s));
s.execute("library.previousShuffle", &json!({})).unwrap();
assert_eq!(s.visible_cloned(), second, "the order the last reshuffle replaced");
s.execute("library.previousShuffle", &json!({})).unwrap();
assert_eq!((s.visible_cloned(), s.sort.seed), (first, 11), "and the one before it, by its seed");
assert!(!previous_shuffle_enabled(&s), "nothing earlier is left");
assert!(matches!(s.execute("library.previousShuffle", &json!({})), Err(crate::EngineError::Disabled(..))));
// going back is not a reshuffle: a new reshuffle after it is again a new order, and goes back to the one it replaced
s.execute("library.shuffle", &json!({})).unwrap();
assert!(previous_shuffle_enabled(&s));
assert_ne!(s.visible_cloned(), second, "the clock may not have moved, yet it is a new order, not the one just left");
assert_ne!(s.visible_cloned(), third, "nor the one before that");
s.execute("library.previousShuffle", &json!({})).unwrap();
assert_eq!(s.sort.seed, 11);
}

#[test]
fn opening_a_library_forgets_the_earlier_shuffles() {
let dir = std::env::temp_dir().join(format!("lc-prev-shuffle-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new().with_fs();
s.open_library(dir.join("one"), false).unwrap();
s.execute("library.sort", &json!({"key": "random", "seed": 3})).unwrap();
s.execute("library.shuffle", &json!({})).unwrap();
assert!(previous_shuffle_enabled(&s));
s.open_library(dir.join("two"), false).unwrap();
assert!(!previous_shuffle_enabled(&s), "the other library never showed those orders");
let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn previous_shuffle_keeps_a_bounded_history_of_seeds() {
let mut s = Session::with_demo();
s.execute("library.sort", &json!({"key": "random", "seed": 100})).unwrap();
for seed in 1..=40u64 {
s.execute("library.shuffle", &json!({"seed": seed})).unwrap();
}
// 40 replaced seeds (100, 1 … 39), the oldest 8 forgotten
let mut back = Vec::new();
for _ in 0..64 {
if !previous_shuffle_enabled(&s) {
break;
}
s.execute("library.previousShuffle", &json!({})).unwrap();
back.push(s.sort.seed);
}
assert_eq!(back.len(), 32, "a bounded history");
assert_eq!((back.first(), back.last()), (Some(&39), Some(&8)), "newest first, the oldest dropped");
}

#[test]
fn previous_shuffle_is_off_unless_sorting_at_random_with_an_earlier_shuffle() {
let mut s = Session::with_demo();
assert!(!previous_shuffle_enabled(&s), "a date sort");
s.execute("library.sort", &json!({"key": "random", "seed": 5})).unwrap();
s.execute("library.shuffle", &json!({})).unwrap();
assert!(previous_shuffle_enabled(&s));
// leaving Random forgets the shuffles of that stay: they would restore an order nobody sees any more
s.execute("library.sort", &json!({"key": "fileName"})).unwrap();
assert!(!previous_shuffle_enabled(&s));
s.execute("library.sort", &json!({"key": "random"})).unwrap();
assert!(!previous_shuffle_enabled(&s), "coming back starts a new shuffle with nothing before it");
// an explicit seed given while shuffling replaces the order shown, a repeat of the seed in force does not
let seed = s.sort.seed;
s.execute("library.sort", &json!({"seed": seed})).unwrap();
s.execute("library.shuffle", &json!({"seed": seed})).unwrap();
assert!(!previous_shuffle_enabled(&s), "the same order again replaced nothing");
s.execute("library.sort", &json!({"seed": 77})).unwrap();
s.execute("library.previousShuffle", &json!({})).unwrap();
assert_eq!(s.sort.seed, seed);
}

#[test]
fn random_sort_rejects_bad_params() {
let mut s = Session::with_demo();
Expand Down
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -2408,5 +2408,8 @@
"Import dropped files without review": "Importovat přetažené soubory bez kontroly",
"An import is running": "Import už běží",
"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"
"Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky",
"Recently Added always shows the newest imports first.": "Nedávno přidané vždy zobrazuje nejnovější importy jako první.",
"Recently Deleted shows no date groups.": "Nedávno odstraněné nezobrazuje skupiny podle data.",
"Previous Shuffle": "Předchozí promíchání"
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -3440,5 +3440,8 @@
"Import dropped files without review": "Abgelegte Dateien ohne Prüfung importieren",
"An import is running": "Ein Import läuft",
"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"
"Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst",
"Recently Added always shows the newest imports first.": "Zuletzt hinzugefügt zeigt immer die neuesten Importe zuerst.",
"Recently Deleted shows no date groups.": "Zuletzt gelöscht zeigt keine Datumsgruppen.",
"Previous Shuffle": "Vorheriges Mischen"
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2358,5 +2358,8 @@
"Import dropped files without review": "Importar los archivos soltados sin revisión",
"An import is running": "Hay una importación en curso",
"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"
"Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos",
"Recently Added always shows the newest imports first.": "Añadidas recientemente siempre muestra primero las importaciones más recientes.",
"Recently Deleted shows no date groups.": "Eliminadas recientemente no muestra grupos por fecha.",
"Previous Shuffle": "Mezcla anterior"
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -2327,5 +2327,8 @@
"Drop to open the face model": "Pudota avataksesi kasvomallin",
"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"
"Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta",
"Recently Added always shows the newest imports first.": "Äskettäin lisätyt näyttää aina uusimmat tuonnit ensin.",
"Recently Deleted shows no date groups.": "Äskettäin poistetut ei näytä päivämääräryhmiä.",
"Previous Shuffle": "Edellinen sekoitus"
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -2390,5 +2390,8 @@
"Checking recent libraries": "Vérification des bibliothèques récentes",
"The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte",
"Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages",
"This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :"
"This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :",
"Recently Added always shows the newest imports first.": "Ajoutées récemment affiche toujours les importations les plus récentes en premier.",
"Recently Deleted shows no date groups.": "Supprimées récemment n'affiche aucun groupe par date.",
"Previous Shuffle": "Mélange précédent"
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -2339,5 +2339,8 @@
"Drop to open the face model": "Jatuhkan untuk membuka model wajah",
"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"
"Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan",
"Recently Added always shows the newest imports first.": "Baru ditambahkan selalu menampilkan impor terbaru lebih dulu.",
"Recently Deleted shows no date groups.": "Baru dihapus tidak menampilkan grup tanggal.",
"Previous Shuffle": "Acakan sebelumnya"
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -2361,5 +2361,8 @@
"Import dropped files without review": "Importa i file rilasciati senza revisione",
"An import is running": "Un'importazione è in corso",
"An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita",
"Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto"
"Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto",
"Recently Added always shows the newest imports first.": "Aggiunte di recente mostra sempre prima le importazioni più recenti.",
"Recently Deleted shows no date groups.": "Eliminate di recente non mostra raggruppamenti per data.",
"Previous Shuffle": "Rimescolamento precedente"
}
5 changes: 4 additions & 1 deletion crates/ui-egui/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -2356,5 +2356,8 @@
"Import dropped files without review": "ドロップしたファイルを確認せずに読み込む",
"An import is running": "読み込み中です",
"An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください",
"Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください"
"Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください",
"Recently Added always shows the newest imports first.": "「最近追加した写真」では、常に読み込みが新しい順に表示されます。",
"Recently Deleted shows no date groups.": "「最近削除した写真」では日付でまとめて表示されません。",
"Previous Shuffle": "前のシャッフル"
}
Loading
Loading