GitCorner

Code

ossartcraftlightcraft🌐
5a24289898fd
//! Culling views: **Compare** (the "select" and a "candidate" side by side, with synced zoom and
//! pan) and **Survey** (the selected photos tiled). Rating, flag and label keys act on the active
//! photo only here, and with Auto Advance on they move to the next candidate / photo.

use egui::{Align2, Color32, Rect, Sense, Stroke, pos2, vec2};
use lightcraft_catalog::{Flag, PhotoId};
use serde_json::{Value, json};

use crate::LightcraftApp;
use crate::icons::{Icon, paint};
use crate::render::Slot;
use crate::state::{ViewMode, Zoom};
use crate::theme::Tokens;
use crate::widgets::register;

pub mod survey;

/// Most photos a survey shows.
pub const SURVEY_MAX: usize = 48;

/// Compare or Survey.
pub fn culling(app: &LightcraftApp) -> bool {
    matches!(app.ui.view, ViewMode::Compare | ViewMode::Survey)
}

/// The (select, candidate) pair, repaired or chosen if needed: the active photo against the next
/// selected photo, else against its neighbour in the view.
/// A photo that can be shown or pinned: in the catalog and not in Recently Deleted.
pub fn live(app: &LightcraftApp, id: PhotoId) -> bool {
    app.session.catalog.photo(id).is_some_and(|p| !p.deleted)
}

pub fn compare_pair(app: &mut LightcraftApp) -> Option<(PhotoId, PhotoId)> {
    if let Some((a, b)) = app.ui.compare {
        let (a, b) = (PhotoId(a), PhotoId(b));
        if a != b && live(app, a) && live(app, b) {
            return Some((a, b));
        }
    }
    let vis = app.session.visible_cloned();
    let sel = app.session.active().or(vis.first().copied())?;
    let cand = app.session.selection.ids.iter().copied().find(|x| *x != sel).or_else(|| {
        let i = vis.iter().position(|x| *x == sel)?;
        vis.get(i + 1).or(i.checked_sub(1).and_then(|j| vis.get(j))).copied()
    })?;
    app.ui.compare = Some((sel.0, cand.0));
    Some((sel, cand))
}

/// Enter Compare with the current selection (the active photo becomes the select).
pub fn enter_compare(app: &mut LightcraftApp) -> Result<Value, String> {
    app.ui.compare = None;
    let (a, b) = compare_pair(app).ok_or("Compare needs at least two photos")?;
    app.ui.view = ViewMode::Compare;
    // the candidate is active: rating/flag keys judge it against the select
    select_pair(app, a, b, b);
    Ok(json!({"select": a.0, "candidate": b.0}))
}

fn select_pair(app: &mut LightcraftApp, a: PhotoId, b: PhotoId, active: PhotoId) {
    app.ui.compare = Some((a.0, b.0));
    let _ = app.session.execute("library.select", &json!({"ids": [a.0, b.0], "active": active.0}));
}

/// Move the candidate `d` photos through the view (skipping the select); it becomes active.
pub fn compare_step(app: &mut LightcraftApp, d: isize) -> Result<Value, String> {
    let (sel, cand) = compare_pair(app).ok_or("nothing to compare")?;
    let vis: Vec<PhotoId> = app.session.visible_cloned().into_iter().filter(|x| *x != sel).collect();
    let Some(i) = vis.iter().position(|x| *x == cand).or(if vis.is_empty() { None } else { Some(0) }) else { return Ok(Value::Null) };
    let j = (i as isize + d).clamp(0, vis.len() as isize - 1) as usize;
    select_pair(app, sel, vis[j], vis[j]);
    Ok(json!({"candidate": vis[j].0}))
}

pub fn swap(app: &mut LightcraftApp) -> Result<Value, String> {
    let (a, b) = compare_pair(app).ok_or("nothing to compare")?;
    let active = app.session.active().unwrap_or(b);
    select_pair(app, b, a, active);
    Ok(Value::Null)
}

/// Show photo `id` on one side of the pair: `side` "select" or "candidate", else the side that is
/// active (the one the Edit panel and the rating keys act on). A photo already on the other side
/// swaps the two. The photo becomes the active one, so what is edited is always on screen.
pub fn set_photo(app: &mut LightcraftApp, id: PhotoId, side: Option<&str>) -> Result<Value, String> {
    if app.session.catalog.photo(id).is_none_or(|p| p.deleted) {
        return Err(format!("no photo {}", id.0));
    }
    let (sel, cand) = compare_pair(app).ok_or("nothing to compare")?;
    let to_select = match side {
        Some("select") => true,
        Some("candidate") => false,
        Some(other) => return Err(format!("unknown side `{other}` (select or candidate)")),
        None => app.session.active() == Some(sel),
    };
    let (a, b) = match (to_select, id == sel, id == cand) {
        (true, _, true) | (false, true, _) => (cand, sel),
        (_, true, _) | (_, _, true) => (sel, cand),
        (true, false, false) => (id, cand),
        (false, false, false) => (sel, id),
    };
    select_pair(app, a, b, id);
    Ok(json!({"select": a.0, "candidate": b.0}))
}

/// A ⌘/Ctrl-click (`range: false`, toggles the photo) or Shift-click (`range: true`, extends
/// from the active photo) on the filmstrip in Compare: the selection changes as it does in the
/// grid, but the two photos shown stay selected and the active one stays active, so the photo the
/// rating keys act on is still on screen (#744). A plain click is [`set_photo`].
pub fn select_with_modifier(app: &mut LightcraftApp, id: PhotoId, range: bool) -> Result<Value, String> {
    if app.session.catalog.photo(id).is_none_or(|p| p.deleted) {
        return Err(format!("no photo {}", id.0));
    }
    let (sel, cand) = compare_pair(app).ok_or("nothing to compare")?;
    let mut next = app.session.selection.clone();
    if range {
        next.extend_to(id, &app.session.visible_cloned());
    } else {
        next.toggle(id);
    }
    for shown in [sel, cand] {
        if !next.contains(shown) {
            next.ids.push(shown);
        }
    }
    let active = app.session.selection.active.filter(|a| next.contains(*a)).unwrap_or(cand);
    let ids: Vec<u64> = next.ids.iter().map(|p| p.0).collect();
    app.session.execute("library.select", &json!({"ids": ids, "active": active.0})).map_err(|e| e.to_string())
}

/// The candidate becomes the select; the next photo becomes the candidate.
pub fn make_select(app: &mut LightcraftApp) -> Result<Value, String> {
    let (_, b) = compare_pair(app).ok_or("nothing to compare")?;
    let vis = app.session.visible_cloned();
    let i = vis.iter().position(|x| *x == b).unwrap_or(0);
    let next = vis.iter().skip(i + 1).chain(vis.iter().take(i).rev()).copied().find(|x| *x != b).ok_or("no next photo")?;
    select_pair(app, b, next, next);
    Ok(json!({"select": b.0, "candidate": next.0}))
}

/// The photos a survey shows: the selection (in view order), or the active photo alone.
pub fn survey_photos(app: &mut LightcraftApp) -> Vec<PhotoId> {
    let vis = app.session.visible_cloned();
    let sel = &app.session.selection;
    let mut v: Vec<PhotoId> = vis.iter().copied().filter(|x| sel.contains(*x)).collect();
    // selected photos hidden in the view (e.g. inside a collapsed stack) come last
    let hidden: Vec<PhotoId> = sel.ids.iter().copied().filter(|x| !v.contains(x) && app.session.catalog.photo(*x).is_some()).collect();
    v.extend(hidden);
    if v.is_empty() {
        v.extend(app.session.active());
    }
    v.truncate(SURVEY_MAX);
    v
}

/// Move the active photo `d` steps within the survey.
pub fn survey_step(app: &mut LightcraftApp, d: isize) -> Result<Value, String> {
    let v = survey_photos(app);
    if v.is_empty() {
        return Ok(Value::Null);
    }
    let i = app.session.selection.active.and_then(|a| v.iter().position(|x| *x == a)).unwrap_or(0);
    let j = (i as isize + d).clamp(0, v.len() as isize - 1) as usize;
    app.session.selection.active = Some(v[j]);
    Ok(json!({"active": v[j].0}))
}

/// After rating/flagging with Auto Advance: next candidate (Compare), next photo in the survey,
/// else the next photo in the view. `was` is the active photo before the rating: a rating that took
/// it out of the view made the photo after it active already, and that is the next one (#2312).
pub fn advance(app: &mut LightcraftApp, was: Option<PhotoId>) {
    let _ = match app.ui.view {
        ViewMode::Compare => compare_step(app, 1),
        ViewMode::Survey => survey_step(app, 1),
        _ if app.session.active() != was => Ok(Value::Null),
        _ => app.session.execute("library.next", &json!({})).map_err(|e| e.to_string()),
    };
}

/// In the culling views, point a photo command at the active photo only (not the whole selection).
pub fn target_active(app: &LightcraftApp, params: &mut Value) {
    if culling(app)
        && params.get("ids").is_none()
        && let Some(a) = app.session.active()
    {
        params["ids"] = json!([a.0]);
    }
}

fn area_and_filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui) -> Rect {
    let t = Tokens::get(ui.ctx());
    let full = ui.max_rect();
    let film_h = if app.ui.filmstrip { t.film_h } else { 0.0 };
    let canvas = Rect::from_min_max(full.min, pos2(full.right(), full.bottom() - film_h));
    app.canvas_rect = Some(canvas);
    if app.ui.filmstrip {
        super::detail::filmstrip(app, ui, Rect::from_min_max(pos2(full.left(), canvas.bottom()), full.max));
    }
    canvas
}

/// Ask for the render of a tile (about `want` pixels on its long edge) and for the thumbnail shown meanwhile.
fn request_tile_renders(app: &mut LightcraftApp, id: PhotoId, slot: Slot, want: usize, aspect: f32) {
    let (rw, rh) = if aspect >= 1.0 { (want, (want as f32 / aspect) as usize) } else { ((want as f32 * aspect) as usize, want) };
    if let Some(job) = app.session.render_job(id, rw.max(8), rh.max(8), false, true) {
        app.renderer.request(slot, job, 60);
    }
    request_thumb(app, id);
}

/// Ask for the thumbnail a tile shows until its render is there.
fn request_thumb(app: &mut LightcraftApp, id: PhotoId) {
    if let Some(job) = app.session.thumb_job(id, 256) {
        app.renderer.request(Slot::Thumb(id), job, 30);
    }
}

/// The photo's frame as shown: cropped, rotated and lens-corrected.
fn frame_of(photo: &lightcraft_catalog::Photo) -> lightcraft_pipeline::geometry::Frame {
    lightcraft_pipeline::geometry::Frame::with_lens(
        photo.width.max(1) as usize,
        photo.height.max(1) as usize,
        &photo.develop,
        true,
        photo.embedded_lens.as_ref(),
    )
}

/// Draw one photo fitted into `area` (rendered at its display size into `slot`), with its caption
/// strip below. Returns the image rect and the click/drag response.
fn photo_tile(
    app: &mut LightcraftApp,
    ui: &mut egui::Ui,
    id: PhotoId,
    slot: Slot,
    area: Rect,
    label: &str,
    zoom: Zoom,
) -> (Rect, Rect, egui::Response) {
    let t = Tokens::get(ui.ctx());
    let ppp = ui.ctx().pixels_per_point();
    let resp = ui.interact(area, egui::Id::unique(("cull-tile", slot_index(slot), id.0)), Sense::click_and_drag());
    crate::widgets::announce(&resp, app.session.catalog.photo(id).map(|p| p.file_name.clone()).unwrap_or_default());
    let Some(photo) = app.session.catalog.photo(id).cloned() else { return (area, area, resp) };
    let caption_h = 26.0;
    let img_area = Rect::from_min_max(area.min, pos2(area.right(), area.bottom() - caption_h));
    let frame = frame_of(&photo);
    let aspect = frame.aspect() as f32;
    let native = super::detail::output_px(&frame);
    let mut img = super::detail::fit_rect(img_area, aspect, zoom, native, ppp, app.ui.pan);
    if matches!(app.ui.view, ViewMode::Compare | ViewMode::Reference) {
        if super::detail::navigate_gesture(app, ui, &resp, img_area, img, native) {
            img = super::detail::fit_rect(img_area, aspect, app.ui.zoom, native, ppp, app.ui.pan);
            // a pinch changes the zoom every frame: no new windows until it is quiet
            app.compare_hold_until = ui.input(|i| i.time) + crate::region::HOLD_SECS;
            ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(crate::region::HOLD_SECS));
        } else if resp.dragged() {
            super::detail::pan_image(app, img_area, img, resp.drag_delta());
        }
    }
    let texture_side = super::detail::texture_side(ui.ctx());
    let want =
        (img.width().max(img.height()).min(img_area.width().max(img_area.height()) * 4.0) * ppp).min(2560.0_f32.min(texture_side as f32)) as usize;
    // a gliding survey tile asks for its render once it has landed, not one per size it passes on
    // the way, and for its thumbnail (one size) meanwhile; tiles that stay put render as usual
    if app.ui.view == ViewMode::Survey && app.survey_motion.gliding(id, ui.input(|i| i.time)) {
        request_thumb(app, id);
    } else {
        request_tile_renders(app, id, slot, want, aspect);
    }
    // zoomed past what that render holds (1:1 to check focus): the part on screen as a window, as
    // in the loupe. Compare and Reference only; Survey tiles are fit views.
    let pane = match slot {
        Slot::Compare(i) if i < WINDOW_PANES && matches!(app.ui.view, ViewMode::Compare | ViewMode::Reference) => Some(i),
        _ => None,
    };
    let shown_aspect = app.renderer.textures.get(&slot).filter(|x| x.photo == id).map(|t| t.size[0].max(1) as f32 / t.size[1].max(1) as f32);
    let window = pane.and_then(|i| {
        let tile = TileView {
            pane: i,
            id,
            img,
            visible: img_area,
            aspect,
            native_long: native[0].max(native[1]),
            whole_edge: want,
            ppp,
            texture_side,
            now: ui.input(|i| i.time),
        };
        let plain = shown_aspect.is_none_or(|a| crate::region::same_aspect(a, aspect));
        let view = if plain { request_window(app, &tile) } else { None };
        app.compare_windows[i as usize] = view;
        if view.is_none() {
            app.compare_tiles.retain(|(p, _), _| *p != i);
            app.renderer.release(Slot::CompareRegion(i));
        }
        view.map(|_| i)
    });
    let p = ui.painter_at(img_area);
    let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
    let mut display = img;
    if let Some(tex) = app.renderer.textures.get(&slot).filter(|x| x.photo == id) {
        let texture_aspect = tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32;
        display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan);
        p.image(tex.id(), display, uv, Color32::WHITE);
        if let Some(i) = window {
            draw_window(&p, app, i, id, photo.develop.hash64(), img);
        }
    } else if let Some(tex) = app.renderer.textures.get(&Slot::Thumb(id)) {
        let texture_aspect = tex.size[0].max(1) as f32 / tex.size[1].max(1) as f32;
        display = super::detail::fit_rect(img_area, texture_aspect, zoom, native, ppp, app.ui.pan);
        p.image(tex.id(), display, uv, Color32::WHITE);
    } else {
        p.rect_filled(img.intersect(img_area), 0.0, t.skeleton);
    }
    if photo.flag == Flag::Reject {
        p.rect_filled(display, 0.0, Color32::from_black_alpha(110));
    }
    if app.ui.settings.focus_point {
        super::detail::draw_focus_point(&p, display, &photo, &format!("compare:focusPoint:{}", id.0));
    }
    let active = app.session.selection.active == Some(id);
    if active {
        super::grid::selection_ring(&p, &t, display.intersect(img_area.shrink(3.0)), lightcraft_engine::SelectionState::Active);
    }
    // Compare and Reference are where sharpness is judged: as in the loupe, say when what is on
    // screen isn't the render on its way (a thumbnail, the last render after an edit, a magnified
    // frame under its window), or when that render failed
    if matches!(app.ui.view, ViewMode::Compare | ViewMode::Reference) {
        let i = slot_index(slot);
        let r = &app.renderer;
        let mine = |s: Slot| r.textures.get(&s).filter(|t| t.photo == id).map(|t| t.key);
        let waits = |s: Slot| r.is_pending(s) && !r.retrying(s);
        // a slider drag on this photo: Compare has no drafts, so its render can't keep up until the drag ends
        let dragging = app.session.interaction.is_some() && app.session.selection.active == Some(id);
        let coming = (waits(slot) && !dragging) || (window.is_some() && waits(Slot::CompareRegion(i)));
        let keys = [mine(slot), mine(Slot::CompareRegion(i)), None, None];
        let now = ui.input(|i| i.time);
        // (the wait belongs to the photo in the pane: one moved in starts its own)
        let rendering = ui.ctx().data_mut(|d| {
            let (photo, wait) = d.get_temp_mut_or(egui::Id::unique(("compare-rendering", i)), (id, None));
            if *photo != id {
                (*photo, *wait) = (id, None);
            }
            super::detail::rendering_overdue(wait, keys, coming, now)
        });
        let failed = (!rendering && mine(slot).is_none() && (!r.is_pending(slot) || r.retrying(slot))).then(|| r.failure_of(slot, id)).flatten();
        let over = display.intersect(img_area);
        let over = if over.is_positive() { over } else { img_area };
        if let Some(e) = failed {
            super::detail::failed_pill(ui, app, &photo, img_area, over, None, &format!("compare:renderFailed:{i}"), e);
        } else if rendering {
            super::detail::loupe_pill(ui, img_area, over, None, &format!("compare:rendering:{i}"), crate::i18n::tr("Rendering…"), false);
        }
    }
    // caption: label · file name · stars · flag · colour label
    // caption right under the image (at the bottom when zoomed in)
    let cap_top = (display.bottom() + 2.0).min(img_area.bottom());
    let cap = Rect::from_min_max(pos2(img.left().max(area.left()), cap_top), pos2(area.right(), cap_top + caption_h));
    let pt = ui.painter();
    let mut x = cap.left() + 4.0;
    if !label.is_empty() {
        let g = pt.layout_no_wrap(crate::i18n::tr(label).to_string(), t.semibold(12.0), if active { t.text } else { t.text_label });
        pt.galley(pos2(x, cap.center().y - g.size().y / 2.0), g.clone(), t.text);
        x += g.size().x + 10.0;
    }
    let name = photo.copy_name.as_ref().map(|c| format!("{} ({c})", photo.file_name)).unwrap_or(photo.file_name.clone());
    let g = pt.layout_no_wrap(name, t.font(11.5), t.text_dim);
    let name_w = g.size().x;
    if x + name_w + 110.0 < cap.right() {
        pt.galley(pos2(x, cap.center().y - g.size().y / 2.0), g, t.text_dim);
        x += name_w + 10.0;
    }
    for i in 0..5u8 {
        let filled = i < photo.rating;
        let r = Rect::from_min_size(pos2(x + i as f32 * 13.0, cap.center().y - 6.0), vec2(12.0, 12.0));
        if r.right() < cap.right() {
            crate::rating::paint_star(pt, r, filled, if filled { t.star } else { t.icon.gamma_multiply(0.6) });
        }
    }
    x += 5.0 * 13.0 + 4.0;
    let fr = Rect::from_min_size(pos2(x, cap.center().y - 7.0), vec2(14.0, 14.0));
    match photo.flag {
        Flag::Pick if fr.right() < cap.right() => paint(pt, fr, Icon::FlagPickFilled, t.pick),
        Flag::Reject if fr.right() < cap.right() => paint(pt, fr, Icon::FlagReject, t.reject),
        _ => {}
    }
    // the colour label as a dot, so labelling while culling shows on the photo (#2398)
    let lr = Rect::from_min_size(pos2(fr.right() + 6.0, cap.center().y - 5.0), vec2(10.0, 10.0));
    if let Some(l) = photo.label
        && lr.right() < cap.right()
    {
        pt.circle_filled(lr.center(), 5.0, super::grid::label_color(l));
        register(ui, format!("cull:{}:label", id.0), lr);
    }
    register(ui, format!("cull:{}", id.0), display);
    // The frame rect the window was requested in (`img`) and the texture's rect (`display`): they
    // differ when the texture's aspect differs from the frame's. The first is the window's
    // reference, the second is the photo as painted.
    (img, display, resp)
}

/// Panes that get window renders: Compare's Select and Candidate, Reference's two sides.
const WINDOW_PANES: u8 = 2;

/// One pane of Compare or Reference, as [`request_window`] needs it.
struct TileView {
    pane: u8,
    id: PhotoId,
    /// The rect the photo is drawn in (the zoomed frame).
    img: Rect,
    /// The area whose pixels are on screen.
    visible: Rect,
    aspect: f32,
    /// The photo's own long edge as shown.
    native_long: usize,
    /// Long edge of the pane's whole-frame render.
    whole_edge: usize,
    ppp: f32,
    texture_side: usize,
    /// The frame's time (s).
    now: f64,
}

/// Ask for the window of a pane's frame that is on screen, once the view is zoomed past what the
/// pane's whole-frame render holds (issue #323): cut from a frame of at most the photo's own pixels
/// (beyond 100 % the GPU magnifies it) and drawn over the whole-frame render. Remembers it so its
/// texture can be drawn where it belongs. `None`: no window is wanted (or possible): the pane shows
/// its whole-frame render alone, as before windows.
///
/// While a pinch or scroll runs, and while the photo is being edited (a slider drag in Reference
/// view), the window there is stays: a new one per frame would render the photo's own pixels each
/// time. It is drawn magnified or with the old value until the gesture is quiet.
fn request_window(app: &mut LightcraftApp, v: &TileView) -> Option<crate::region::RegionView> {
    let drawn_long = v.img.width().max(v.img.height()) * v.ppp;
    let frame_edge = app.ui.settings.window_frame_edge(drawn_long, v.native_long);
    if frame_edge as f32 <= v.whole_edge as f32 * crate::region::WINDOW_RATIO {
        return None;
    }
    let editing = app.session.interaction.is_some() && app.session.active() == Some(v.id);
    if app.compare_hold_until > v.now || editing {
        return app.compare_windows[v.pane as usize].filter(|w| w.photo == v.id);
    }
    let (fw, fh) =
        if v.aspect >= 1.0 { (frame_edge as f32, frame_edge as f32 / v.aspect) } else { (frame_edge as f32 * v.aspect, frame_edge as f32) };
    let (fw, fh) = (fw.round().max(1.0) as usize, fh.round().max(1.0) as usize);
    // what is on screen, in pixels of the window's frame (the drawn frame, scaled)
    let to_px = v.ppp * frame_edge as f32 / drawn_long.max(1.0);
    let visible = (
        to_px * (v.visible.left() - v.img.left()),
        to_px * (v.visible.top() - v.img.top()),
        to_px * (v.visible.right() - v.img.left()),
        to_px * (v.visible.bottom() - v.img.top()),
    );
    let win = crate::region::window_for(fw, fh, visible, crate::region::max_span(v.texture_side))?;
    // refused: what the window reads (a spot's source, an Auto Mask stroke) is too far for one
    // render; the pane keeps its whole-frame render
    let job = app.session.region_job(v.id, fw, fh, win, true)?;
    // keyed as the renderer keys the texture (a display profile changes the key)
    let job = app.renderer.job_for(Slot::CompareRegion(v.pane), job);
    let look = job.settings.hash64();
    let view = crate::region::RegionView { photo: v.id, before: false, key: job.key, full: (fw, fh), window: win, settings: look };
    // windows of other photos, looks and zooms of this pane can't be drawn any more
    app.compare_tiles.retain(|(p, _), t| *p != v.pane || t.is_current(v.id, (fw, fh), look, false));
    app.compare_tiles.insert((v.pane, job.key), view);
    // after both panes' whole-frame renders (60): those are what a step to the next photo shows first
    app.renderer.request(Slot::CompareRegion(v.pane), job, 58);
    Some(view)
}

/// Draw pane `pane`'s window texture over its whole-frame render (`display`), if it shows this
/// photo with its current look (any look of it while it is being edited). A window made at another
/// zoom is drawn at its place in the frame, magnified or shrunk, until the new one arrives.
fn draw_window(p: &egui::Painter, app: &LightcraftApp, pane: u8, id: PhotoId, look: u64, display: Rect) {
    let Some(tex) = app.renderer.textures.get(&Slot::CompareRegion(pane)).filter(|t| t.photo == id) else { return };
    let editing = app.session.interaction.is_some() && app.session.active() == Some(id);
    let Some(tile) = app.compare_tiles.get(&(pane, tex.key)).filter(|t| t.photo == id && (editing || t.settings == look)) else {
        return;
    };
    let (fw, fh) = (tile.full.0.max(1) as f32, tile.full.1.max(1) as f32);
    let at = display.min + vec2(tile.window.x as f32 / fw * display.width(), tile.window.y as f32 / fh * display.height());
    let dst = Rect::from_min_size(at, vec2(tile.window.w as f32 / fw * display.width(), tile.window.h as f32 / fh * display.height()));
    p.image(tex.id(), dst, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}

/// Per frame, before the central view is shown: Compare and Reference keep two photos' originals
/// decoded (their windows are cut from both); other views keep one and free the panes' windows.
/// The Detail view's photo keeps its original even over the memory budget (a zoomed 64 MP raw);
/// other views free the Detail view's windows (while one is shown the GPU copy of its original stays).
pub fn prepare(app: &mut LightcraftApp) {
    let shown = if app.ui.view == ViewMode::Detail { app.session.active() } else { None };
    app.session.media.set_on_screen(shown);
    if app.ui.view != ViewMode::Detail {
        app.region_view = None;
        app.region_before_view = None;
        app.region_tiles.clear();
        app.renderer.release(Slot::Region);
        app.renderer.release(Slot::RegionBefore);
    }
    // Reference with no live pin draws no panes: release them as other views do.
    let reference_shown = app.ui.reference.is_some_and(|r| live(app, PhotoId(r)));
    if app.ui.view == ViewMode::Compare || (app.ui.view == ViewMode::Reference && reference_shown) {
        app.session.media.set_full_capacity(WINDOW_PANES as usize);
        return;
    }
    if app.ui.view == ViewMode::Reference {
        // the reference (pane 0) and the active photo beside it (pane 1)
        app.renderer.release(Slot::Compare(0));
        app.renderer.release(Slot::Compare(1));
    }
    app.session.media.set_full_capacity(1);
    for i in 0..WINDOW_PANES {
        if app.compare_windows[i as usize].take().is_some() || app.renderer.textures.contains_key(&Slot::CompareRegion(i)) {
            app.renderer.release(Slot::CompareRegion(i));
        }
    }
    app.compare_tiles.clear();
}

fn slot_index(s: Slot) -> u8 {
    match s {
        Slot::Compare(i) => i,
        _ => 255,
    }
}

pub fn show_compare(app: &mut LightcraftApp, ui: &mut egui::Ui) {
    let canvas = area_and_filmstrip(app, ui);
    let Some((sel, cand)) = compare_pair(app) else {
        super::empty_message(ui, canvas, "Nothing to compare", "Select two photos, then choose View → Compare (Shift+C)");
        return;
    };
    let area = canvas.shrink(18.0);
    let half = (area.width() - 16.0) / 2.0;
    let panes = [
        (sel, Rect::from_min_size(area.min, vec2(half, area.height())), "Select", 0u8),
        (cand, Rect::from_min_size(pos2(area.right() - half, area.top()), vec2(half, area.height())), "Candidate", 1u8),
    ];
    let zoom = app.ui.zoom;
    for (id, r, label, i) in panes {
        let (img, _, resp) = photo_tile(app, ui, id, Slot::Compare(i), r, label, zoom);
        if i == 1 {
            app.image_rect = Some(img);
        }
        if resp.clicked() {
            select_pair(app, sel, cand, id);
        }
        if resp.double_clicked() {
            app.ui.zoom = if app.ui.zoom == Zoom::Fit { Zoom::Percent(100.0) } else { Zoom::Fit };
        }
        crate::widgets::context_menu(&resp, |ui| {
            if ui.button(crate::i18n::tr("Swap")).clicked() {
                let _ = swap(app);
            }
            if ui.button(crate::i18n::tr("Make Candidate the Select")).clicked() {
                let _ = make_select(app);
            }
            ui.separator();
            super::grid::context_menu(app, ui, id);
        });
    }
    let mid = area.center().x;
    ui.painter().line_segment([pos2(mid, area.top()), pos2(mid, area.bottom())], Stroke::new(1.0, Tokens::get(ui.ctx()).divider));
}

pub fn show_survey(app: &mut LightcraftApp, ui: &mut egui::Ui) {
    let t = Tokens::get(ui.ctx());
    let canvas = area_and_filmstrip(app, ui);
    let photos = survey_photos(app);
    if photos.is_empty() {
        super::empty_message(ui, canvas, "Nothing to survey", "Select photos, then choose View → Survey (N)");
        return;
    }
    let area = canvas.shrink(14.0);
    let aspects: Vec<f32> = photos.iter().map(|id| app.session.catalog.photo(*id).map_or(1.5, |p| frame_of(p).aspect() as f32)).collect();
    let cells = survey::cells(&aspects, area);
    let now = ui.input(|i| i.time);
    let placed = app.survey_motion.place(&photos, &cells, area, ui.ctx().cumulative_frame_nr(), now);
    let (slots, freed) = app.survey_motion.assign_slots(&photos);
    for s in freed {
        app.renderer.release(Slot::Compare(s));
    }
    if app.survey_motion.moving(now) {
        ui.ctx().request_repaint();
    }
    for ((id, cell), slot) in photos.iter().zip(placed).zip(slots) {
        // (Survey tiles are fit views with no windows: what counts is the photo as painted)
        let (_, img, resp) = photo_tile(app, ui, *id, Slot::Compare(slot), cell.shrink(survey::GAP), "", Zoom::Fit);
        if app.session.selection.active == Some(*id) {
            app.image_rect = Some(img);
        }
        // ⌘/Ctrl-click removes the photo from the survey (deselects it), as the × does
        if resp.clicked() && ui.input(|i| i.modifiers.command) {
            if photos.len() > 1 {
                let _ = app.run("library.select", json!({"ids": [id.0], "mode": "toggle"}));
            }
        } else if resp.clicked() {
            app.session.selection.active = Some(*id);
        }
        if resp.double_clicked() {
            let _ = app.run("library.select", json!({"ids": [id.0]}));
            app.ui.view = ViewMode::Detail;
        }
        // remove from the survey (deselect) on hover; the × stays while the pointer is on it, where
        // the tile has lost its hover to the × (tied to `hovered()`, it vanished before a click landed)
        if resp.contains_pointer() && photos.len() > 1 {
            let xr = Rect::from_min_size(pos2(img.right() - 26.0, img.top() + 6.0), vec2(20.0, 20.0));
            let xresp = ui.interact(xr, egui::Id::unique(("survey-x", id.0)), Sense::click()).on_hover_text(crate::i18n::tr("Remove from survey"));
            crate::widgets::announce(&xresp, crate::i18n::tr("Remove from survey"));
            ui.painter().circle_filled(xr.center(), 10.0, Color32::from_black_alpha(if xresp.hovered() { 230 } else { 160 }));
            paint(ui.painter(), xr.shrink(4.0), Icon::Close, t.text);
            if xresp.clicked() {
                let _ = app.run("library.select", json!({"ids": [id.0], "mode": "toggle"}));
            }
        }
        crate::widgets::context_menu(&resp, |ui| super::grid::context_menu(app, ui, *id));
    }
    let n = photos.len();
    let msg = if app.session.selection.ids.len() > SURVEY_MAX {
        crate::i18n::tr_format!("Showing {n} of {}", app.session.selection.ids.len(), n = n)
    } else {
        String::new()
    };
    if !msg.is_empty() {
        ui.painter().text(pos2(canvas.right() - 16.0, canvas.top() + 10.0), Align2::RIGHT_TOP, msg, t.font(12.0), t.text_dim);
    }
}

/// Reference view: the reference photo (left, fixed) beside the active photo (right) — the one
/// the Edit panel works on, so a look can be matched by eye.
pub fn show_reference(app: &mut LightcraftApp, ui: &mut egui::Ui) {
    let canvas = area_and_filmstrip(app, ui);
    let reference = app.ui.reference.map(PhotoId).filter(|r| live(app, *r));
    let (Some(r), Some(active)) = (reference, app.session.active()) else {
        super::empty_message(ui, canvas, "No reference photo", "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)");
        return;
    };
    let area = canvas.shrink(18.0);
    let half = (area.width() - 16.0) / 2.0;
    let zoom = app.ui.zoom;
    let left = Rect::from_min_size(area.min, vec2(half, area.height()));
    let right = Rect::from_min_size(pos2(area.right() - half, area.top()), vec2(half, area.height()));
    let (_, _, lresp) = photo_tile(app, ui, r, Slot::Compare(0), left, "Reference", zoom);
    let (img, _, _) = photo_tile(app, ui, active, Slot::Compare(1), right, "Active", zoom);
    app.image_rect = Some(img);
    crate::widgets::context_menu(&lresp, |ui| {
        if ui.button(crate::i18n::tr("Clear Reference")).clicked() {
            app.ui.reference = None;
            app.ui.view = ViewMode::Detail;
        }
    });
    let mid = area.center().x;
    ui.painter().line_segment([pos2(mid, area.top()), pos2(mid, area.bottom())], Stroke::new(1.0, Tokens::get(ui.ctx()).divider));
}