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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/engine/src/activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,11 @@ impl Activity {
lock(&self.inner.tasks).iter().any(|e| e.parent.is_none() && e.kind == kind)
}

/// The kind of the first top-level task in flight whose kind is one of `kinds`, or `None` ([`crate::sched`]).
pub fn running_kind(&self, kinds: &[&str]) -> Option<&'static str> {
lock(&self.inner.tasks).iter().find(|e| e.parent.is_none() && kinds.contains(&e.kind)).map(|e| e.kind)
}

/// Register a task; it is listed until the returned guard is dropped. `label` is English (the frontend
/// translates it).
pub fn start(&self, kind: &'static str, label: &str, cancel: Cancel) -> TaskGuard {
Expand Down
5 changes: 3 additions & 2 deletions crates/engine/src/cmd/face_recognize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2719,9 +2719,10 @@ mod imp {
const C: &str = "faces.pump";
// how hard the scan may work now, from what the user is doing (the app says); nothing new is started while paused,
// and what is already running finishes
// paused by the user (`faces.pause`): nothing new is started until `faces.resume`
// paused by the user (`faces.pause`): nothing new is started until `faces.resume`; and (rank 3) while an
// export, an import or the photo on screen needs the machine (`crate::sched`)
let (enabled, paused) = switches_cached(s);
let pace = if paused { Pace::Pause } else { Pace::parse(p.get("pace").and_then(Value::as_str)) };
let pace = if paused { Pace::Pause } else { Pace::parse(s.spare_pace(p)) };
let target = target_workers(pace);
// a model that has finished downloading is installed and chosen here, whether or not recognition was on
finish_downloads(s);
Expand Down
126 changes: 124 additions & 2 deletions crates/engine/src/cmd/previews.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,11 @@ fn run_all(state: &PreviewBuild, task: &TaskGuard, lanes: usize, force: bool, ac
if state.background && (wait_for_user_work(activity, &state.cancel, task) || wait_on_screen(&state.cancel)) {
break;
}
// a build that was asked for (an import's, Build Previews) waits while an export runs (the export ranks
// higher, `crate::sched`) and gives the photo on screen a moment
if !state.background && (wait_for_export(activity, &state.cancel, task) || give_way_to_screen(&state.cancel)) {
break;
}
let next = {
let mut q = queue.lock();
match state.next_index(&q) {
Expand Down Expand Up @@ -587,6 +592,49 @@ fn wait_for_user_work(activity: &crate::activity::Activity, cancel: &AtomicBool,
cancel.load(Ordering::Relaxed)
}

/// Wait while an export runs, saying so in the build's row (a build that was asked for: rank 2 below the export,
/// `crate::sched`). `true`: cancelled meanwhile.
fn wait_for_export(activity: &crate::activity::Activity, cancel: &AtomicBool, task: &TaskGuard) -> bool {
let mut paused = false;
while activity.running_kind(&["export"]).is_some() {
if cancel.load(Ordering::Relaxed) {
return true;
}
if !paused {
paused = true;
task.detail("Paused while exporting");
}
#[cfg(not(target_arch = "wasm32"))]
std::thread::sleep(std::time::Duration::from_millis(100));
#[cfg(target_arch = "wasm32")]
break;
}
if paused {
task.detail("");
}
cancel.load(Ordering::Relaxed)
}

/// How long a build that was asked for waits for the photo on screen before its next photo (ms): the loupe's own render
/// goes first, and the build never stalls behind a user who keeps stepping.
#[cfg(not(target_arch = "wasm32"))]
const SCREEN_WAIT_MS: u64 = 600;

/// Wait while the photo on screen is being made, at most [`SCREEN_WAIT_MS`]. `true`: cancelled meanwhile.
fn give_way_to_screen(cancel: &AtomicBool) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
let t0 = web_time::Instant::now();
while crate::prep::foreground_busy() && t0.elapsed() < std::time::Duration::from_millis(SCREEN_WAIT_MS) {
if cancel.load(Ordering::Relaxed) {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(15));
}
}
cancel.load(Ordering::Relaxed)
}

/// The long edge the background preparation builds standard previews at: the library's standard
/// size, or what the loupe asks for on this screen when that is more ([`Session::loupe_edge`]), so
/// the loupe finds what was built.
Expand Down Expand Up @@ -630,7 +678,9 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32");
// `feed`: the caller makes the jobs a few photos a frame ([`feed`]), nearest the user first;
// making all of them here froze the UI for 1.3 s at every build of a 2,597-photo folder (2026-11-10)
let lazy = background && !wait && p.get("feed").and_then(Value::as_bool).unwrap_or(false);
// (an import's build is fed too once the app ticks the preparation: its jobs then carry the photo's path when they
// are made, nearest the user first, not when the import's batch came in)
let lazy = (background || s.prep.ticking()) && !wait && p.get("feed").and_then(Value::as_bool).unwrap_or(false);
let (order, slots): (Vec<u64>, Vec<Slot>) = if lazy {
(ids.iter().map(|id| id.0).collect(), ids.iter().map(|_| Some(None)).collect())
} else {
Expand Down Expand Up @@ -819,12 +869,84 @@ pub fn build_after_import(s: &mut Session, ids: &[lcc_catalog::PhotoId]) {
if ids.is_empty() {
return;
}
// An import commits its photos a batch at a time: while the build of an earlier batch runs, these photos wait and
// the next frame after it builds all that waited ([`build_owed_import`]). Before, every batch after the first
// was dropped ("a preview build is already running"): 16 of 261 photos got their previews.
if s.prep.ticking() && s.preview_build.as_ref().is_some_and(|b| b.running() && !b.background) {
s.prep.owed_import.extend(ids.iter().copied());
return;
}
start_import_build(s, size, ids);
}

/// Start the build of an import's previews (`size` as `library.buildPreviews`), from the photo the user is on.
fn start_import_build(s: &mut Session, size: &str, ids: &[lcc_catalog::PhotoId]) {
let ids: Vec<u64> = ids.iter().map(|id| id.0).collect();
if let Err(e) = build(s, &json!({"size": size, "ids": ids})) {
let mut p = json!({"size": size, "ids": ids, "feed": true});
if let Some(at) = s.active() {
p["from"] = json!(at.0);
}
if let Err(e) = build(s, &p) {
log::warn!("previews at import: {e}");
}
}

/// The photos of an import whose previews wait for the build before them ([`build_after_import`]): built once that
/// build has ended. Cheap; called every frame ([`Session::prep_tick`]).
pub(crate) fn build_owed_import(s: &mut Session) {
if s.prep.owed_import.is_empty() || s.preview_build.as_ref().is_some_and(|b| b.running() && !b.background) {
return;
}
let size = match s.preview_prefs.at_import {
ImportPreviews::Minimal => {
s.prep.owed_import.clear();
return;
}
ImportPreviews::Standard => "standard",
ImportPreviews::Full => "full",
};
let mut seen = std::collections::HashSet::new();
let ids: Vec<lcc_catalog::PhotoId> = std::mem::take(&mut s.prep.owed_import).into_iter().filter(|id| seen.insert(*id)).collect();
start_import_build(s, size, &ids);
}

/// The photos of `ids` whose file moved (Rename Photos, a move, a relink, their undo): the running build's jobs made
/// for them are made again, with the photo's path now. A build queued just before a rename kept the old paths and
/// failed 84 photos with "cannot find the file".
pub(crate) fn refresh_jobs_of(s: &mut Session, ids: &[lcc_catalog::PhotoId]) {
let Some(b) = s.preview_build.clone().filter(|b| b.running()) else { return };
let moved: std::collections::HashSet<u64> = ids.iter().map(|id| id.0).collect();
let stale: Vec<usize> = {
let mut q = b.queue.lock();
b.order
.iter()
.enumerate()
.filter(|(_, id)| moved.contains(*id))
.filter_map(|(i, _)| {
let slot = q.get_mut(i)?;
matches!(slot, Some(Some(_))).then(|| {
*slot = Some(None);
i
})
})
.collect()
};
for i in stale {
let Some(id) = b.order.get(i).copied() else { continue };
let jobs = jobs_for(s, lcc_catalog::PhotoId(id), b.edge);
let mut q = b.queue.lock();
if let Some(slot) = q.get_mut(i).filter(|s| matches!(s, Some(None))) {
if jobs.is_empty() {
*slot = None;
b.skipped.fetch_add(1, Ordering::Relaxed);
b.done.fetch_add(1, Ordering::Relaxed);
} else {
*slot = Some(Some(jobs));
}
}
}
}

/// One photo's smart preview to build or discard: (photo, its file in the smart previews folder,
/// how to load the original at preview size, whether the photo can take a preview-fitted look:
/// vendor raws and DNGs (whose tone can come from their preview); only those proxies go stale when
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/focus_scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,8 @@ fn status(s: &Session) -> Value {
/// `focus.pump {pace?}`: cheap to call every frame.
pub(crate) fn pump(s: &mut Session, p: &Value) -> Result<Value> {
follow_library(s);
let pace = Pace::parse(p.get("pace").and_then(Value::as_str));
// (rank 3: paused while an export, an import or the photo on screen needs the machine, `crate::sched`)
let pace = Pace::parse(s.spare_pace(p));
s.focus_scan.pace = pace;
if !step(s, pace) && !s.focus_scan.auto_checked {
// once per library opening: start by itself when photos are left to look at (a few KB each)
Expand Down
14 changes: 13 additions & 1 deletion crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ pub mod rename;
pub mod render_dng;
pub mod run_presets;
pub mod scene_disk;
pub mod sched;
pub mod segment;
pub mod sensor_maps;
pub mod sidecar;
Expand Down Expand Up @@ -1396,14 +1397,20 @@ impl Session {
// photos whose file was replaced: the faces and ML embeddings made from the old pixels go too (issue #1524)
let mut replaced = Vec::new();
let mut added_photo = false;
// photos whose file moved: a preview build's jobs for them are made again with the new path
let mut moved = Vec::new();
let mut pending = vec![&op];
while let Some(op) = pending.pop() {
match op {
Op::SetContent { id, .. } => {
invalidated.push(*id);
replaced.push(*id);
}
Op::SetFile { id, .. } | Op::Relink { id, .. } | Op::RemovePhoto { id } => invalidated.push(*id),
Op::SetFile { id, .. } | Op::Relink { id, .. } => {
invalidated.push(*id);
moved.push(*id);
}
Op::RemovePhoto { id } => invalidated.push(*id),
// a video's decoded source is its poster frame: a new poster time (or new stream facts) needs a new one
Op::SetVideoPoster { id, .. } | Op::SetVideoMeta { id, .. } => invalidated.push(*id),
Op::AddPhoto { photo } => {
Expand All @@ -1418,6 +1425,9 @@ impl Session {
for id in invalidated {
self.media.forget(id);
}
if !moved.is_empty() {
crate::cmd::previews::refresh_jobs_of(self, &moved);
}
if added_photo {
self.ml.photo_added();
}
Expand Down Expand Up @@ -3203,6 +3213,8 @@ mod tests_reload_sha1;
#[cfg(test)]
mod tests_retouch;
#[cfg(test)]
mod tests_sched;
#[cfg(test)]
mod tests_segment;
#[cfg(test)]
mod tests_select_menu;
Expand Down
16 changes: 14 additions & 2 deletions crates/engine/src/ml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1764,11 +1764,23 @@ impl Session {
submitted
}

/// The pace `ml.pump` last set (tests).
#[cfg(test)]
pub(crate) fn ml_pace_name(&self) -> &'static str {
match Pace::from_u8(self.ml.pace.load(Ordering::Relaxed)) {
Pace::Pause => "pause",
Pace::Light => "light",
Pace::Normal => "normal",
Pace::Full => "full",
}
}

/// `ml.pump {pace?: pause | light | normal | full}`.
pub(crate) fn ml_pump(&mut self, p: &Value) -> crate::Result<Value> {
self.ml_enabled();
// paused by the user (`ml.pause`): the photos being embedded wait, nothing new is queued
let pace = if self.ml.paused { Pace::Pause } else { Pace::parse(p.get("pace").and_then(Value::as_str)) };
// paused by the user (`ml.pause`): the photos being embedded wait, nothing new is queued; and
// (rank 3) while an export, an import or the photo on screen needs the machine (`crate::sched`)
let pace = if self.ml.paused { Pace::Pause } else { Pace::parse(self.spare_pace(p)) };
self.ml.pace.store(pace as u8, Ordering::Relaxed);
let (added, _) = self.drain_ml_results();

Expand Down
17 changes: 17 additions & 0 deletions crates/engine/src/prep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,11 @@ pub struct PrepState {
/// It says "ask again", not what is left: the build that follows skips every photo whose
/// previews are on disk. A view with nothing to build (no marked photo) leaves it as it is.
pub unfinished: bool,
/// An import's photos whose previews wait for the build before them to end
/// ([`crate::cmd::previews::build_after_import`]).
pub(crate) owed_import: Vec<PhotoId>,
/// [`Session::prep_tick`] has run (the app ticks it every frame): a build may then leave making its jobs to it.
ticked: bool,
/// Before when an unfinished build is not taken up again: [`SETTLE_AFTER`] after the view shown
/// last changed (`None`: no change seen yet). The first build of a library with nothing owed
/// doesn't wait for it (the steps in the loupe are its guard).
Expand Down Expand Up @@ -309,6 +314,11 @@ impl std::fmt::Debug for PrepState {
}

impl PrepState {
/// Whether [`Session::prep_tick`] runs (the desktop app): builds fed a frame at a time are fed.
pub fn ticking(&self) -> bool {
self.ticked
}

/// Forget the view state a library that was open before left behind, when a library opens: the
/// view guards (`started_for`, `declined_for`, the view last seen), the settle wait and the
/// step count were earned in that library's views, and a view signature is only its photos'
Expand Down Expand Up @@ -598,6 +608,13 @@ impl Session {
/// updated look, even after 15 min"). In a library the rest is prepared around the photo on screen
/// ([`AROUND`]), not the whole view; a folder being culled is prepared whole.
pub fn prep_tick(&mut self, mode: Mode, at: Option<PhotoId>, backward: bool) {
self.prep.ticked = true;
// an import's photos whose previews waited for the build before them ([`crate::cmd::previews::build_after_import`])
crate::cmd::previews::build_owed_import(self);
// a build that was asked for (an import's) builds from the photo the user is on first, as the preparation does
if let (Some(id), Some(b)) = (at, self.preview_build.as_ref().filter(|b| b.running() && !b.background)) {
b.focus_on(id, backward);
}
self.prep_tick_inner(mode, at, backward);
// the build's render jobs, a few photos a tick, nearest the user first (making all of them
// when it started froze the UI for 1.3 s in a 2,597-photo folder, 2026-11-10)
Expand Down
Loading