GitCorner

Code

ossartcraftphotocraft🌐
856f865cf98d
//! Live canvas preview for the Image › Adjustments dialogs (`adjust_dialog`).
//!
//! While a dialog is open on a pixel layer the canvas shows the committed document with a
//! temporary adjustment layer (the dialog's settings, the selection as its mask) clipped to the
//! target layer. That composite equals what the destructive command will produce (see the tests:
//! within 1/255 for every kind, depth and mode below), but it is drawn by the regular canvas path,
//! so on the GPU canvas a change re-runs the wgpu compositor instead of the command on a CPU
//! proxy (the layer textures stay resident; just the adjustment's uniforms / LUT change):
//! - over the target's area within the selection only (`switch_region`), and of that only what
//!   the view shows; the rest catches up as the view moves (`uncovered`);
//! - zoomed out on a large document, on a copy reduced to about the screen's resolution, built
//!   once per session ([`gpu_proxy`]), unless Preferences › Performance › Low Resolution Previews
//!   is off.
//!
//! OK still runs the real command (one history step); Cancel just drops the preview. The base
//! document (with the preview layer) and the region are built once per dialog session; a change
//! only swaps the layer's adjustment in a shallow copy.
//!
//! An already-clipped, unstyled target becomes a group in the preview document only: its raw
//! raster and the temporary adjustment are children, while its external compositing properties
//! stay on the group. This applies the adjustment before the target blends into its clipping
//! group, as the destructive command does.
//!
//! Cases where an adjustment-layer composite differs from the destructive result, or where it
//! would not be cheap, keep the CPU proxy preview (`canvas::ensure_filter_preview`), see
//! [`unsupported`]:
//! - the target is not a plain pixel layer (smart object, type, shape, group: the command edits
//!   a smart object's filters or refuses);
//! - a clipped target has enabled effects on itself or an enclosing group (their effect shape
//!   maps would rebuild on the UI thread for every settings change);
//! - the target uses Blend If (its "Current Layer" ranges test the layer's adjusted colour);
//! - the target's untouched area is visible (a surface without alpha whose content doesn't cover
//!   the canvas: the command only edits content);
//! - the command targets an alpha channel, the Quick Mask or a single colour channel;
//! - CMYK, Lab and the other non-RGB modes except Grayscale: the command converts each pixel to
//!   RGB, adjusts and converts back (CMYK even changes when the settings are neutral), which a
//!   composite in display RGB can't reproduce;
//! - in Grayscale documents, kinds that make colour from gray (Vibrance, Color Balance, Black &
//!   White, Photo Filter, Channel Mixer, Gradient Map, Selective Color, colorized Hue/Saturation):
//!   the command folds each pixel back to gray, the composite would carry the colour through;
//! - on the GPU canvas, documents the wgpu compositor doesn't cover (it would fall back to a
//!   full CPU composite per change); on the CPU canvas, documents above the proxy size.

use std::sync::Arc;

use craft::imaging::ui::live_preview::{LivePreview, PreviewKey, PreviewLane, PreviewSession, ProxyPlan, settings_hash};
use craft::ui::canvas::PixelRect;
use photocraft_color::ColorMode;
use photocraft_doc::{Adjustment, DocId, Document, Group, Layer, LayerContent, LayerId, LayerMask};
use photocraft_geom::Rect;
use serde_json::Value;

use crate::PhotocraftApp;

/// Id of the temporary preview layer. Fixed so the GPU compositor keeps its mask (the selection)
/// resident from one change to the next. Never reaches a committed document.
pub const PREVIEW_LAYER: LayerId = LayerId(u64::MAX - 77);
/// Id of the raw-raster carrier inside a clipped target's preview group (see [`base_document`]).
/// Fixed like [`PREVIEW_LAYER`] so its GPU textures stay resident across settings changes.
const CARRIER_LAYER: LayerId = LayerId(u64::MAX - 76);

/// The framework's pixel rectangle of a document rectangle; an empty one is the default empty rectangle.
fn pixel_rect(r: &Rect) -> PixelRect {
    if r.is_empty() { PixelRect::default() } else { PixelRect::new(r.x0, r.y0, r.x1, r.y1) }
}

/// The document rectangle of a framework pixel rectangle.
fn doc_rect(r: PixelRect) -> Rect {
    Rect::new(r.x0, r.y0, r.x1, r.y1)
}

/// The time of the pass the app runs in, in seconds: the unit the live preview's settle time is in. It is the frame
/// time, not the wall clock, so a driver that steps the frame clock steps the settle too.
fn now_s(app: &PhotocraftApp) -> f64 {
    app.ctx().input(|i| i.time)
}

/// Why `target` in `doc` can't preview through the temporary layer path, or None when it can.
pub fn unsupported(doc: &Document, target: LayerId) -> Option<&'static str> {
    if !matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale) {
        return Some("colour mode composites through display RGB");
    }
    let Some(l) = doc.layer(target) else { return Some("no target layer") };
    let LayerContent::Raster(s) = &l.content else { return Some("not a pixel layer") };
    // A clipped target is previewed inside a new group. If the target or a group around it is
    // styled, every slider change invalidates that group's effect shape maps, and rebuilding
    // them is CPU work on the UI thread. The CPU proxy has its own worker, so styled clips keep
    // it; an unrelated styled sibling doesn't affect this target's clip.
    if l.clipped && (photocraft_compose::effects::has_effects(l) || styled_ancestor(doc, target)) {
        return Some("clipped target or enclosing group has layer effects");
    }
    if photocraft_compose::blend_if_active(l, doc.mode) {
        return Some(tl!("Blend If"));
    }
    let shows_default = !s.format().alpha || s.default_pixel().last().is_some_and(|a| *a > 0.0);
    if shows_default && !s.content_bounds().contains_rect(&doc.bounds()) {
        return Some("untouched area is visible");
    }
    None
}

/// Whether a group enclosing `target` has enabled layer effects.
fn styled_ancestor(doc: &Document, target: LayerId) -> bool {
    let Some(path) = doc.path_of(target) else { return false };
    (1..path.len()).any(|n| path.get(..n).and_then(|p| doc.layer_at(p)).is_some_and(photocraft_compose::effects::has_effects))
}

/// Whether `adj` maps gray to gray. Others make colour in a grayscale document, which the command
/// folds back to gray per pixel while the composite carries it to the end.
fn keeps_gray(adj: &Adjustment) -> bool {
    match adj {
        Adjustment::BrightnessContrast { .. }
        | Adjustment::Levels { .. }
        | Adjustment::Curves { .. }
        | Adjustment::Exposure { .. }
        | Adjustment::Posterize { .. }
        | Adjustment::Threshold { .. }
        | Adjustment::Invert => true,
        Adjustment::HueSaturation { colorize, .. } => !colorize,
        _ => false,
    }
}

/// `doc` with a placeholder temporary adjustment layer clipped to `target` (the selection as its
/// mask): built once per dialog session, then [`with_settings`] per change. Errors when the target
/// isn't eligible ([`unsupported`]).
///
/// An already-clipped target becomes a group containing its raw raster and the adjustment, so
/// only its own pixels are adjusted. Its id and external compositing properties stay on the group.
pub fn base_document(doc: &Document, target: LayerId) -> Result<Document, String> {
    if let Some(why) = unsupported(doc, target) {
        return Err(why.into());
    }
    let mut preview = Layer::new(tl!("Adjustment Preview"), LayerContent::Adjustment(Adjustment::Invert));
    preview.id = PREVIEW_LAYER;
    preview.clipped = true;
    if let Some(sel) = &doc.selection {
        preview.mask = Some(LayerMask { surface: sel.clone(), enabled: true, linked: false, density: 1.0, feather: 0.0 });
    }
    let mut out = doc.clone();
    if !out.layer(target).is_some_and(|l| l.clipped) {
        out.insert_above(Some(target), preview);
        return Ok(out);
    }
    let l = out.layer_mut(target).ok_or("no target layer")?;
    let content = std::mem::replace(&mut l.content, LayerContent::Group(Group { children: Vec::new(), expanded: true, artboard: None, frame_stroke: None }));
    let LayerContent::Raster(surface) = content else { return Err("not a pixel layer".into()) };
    let mut carrier = Layer::new(l.name.clone(), LayerContent::Raster(surface));
    carrier.id = CARRIER_LAYER;
    if let LayerContent::Group(g) = &mut l.content {
        g.children = vec![carrier, preview];
    }
    Ok(out)
}

/// A [`base_document`] with the dialog's settings in its preview layer (a shallow copy: pixel
/// tiles are shared). Errors on invalid settings and on kinds the layer can't reproduce here.
pub fn with_settings(base: &Document, kind: &str, params: &Value) -> Result<Document, String> {
    set_adjustment(base, PREVIEW_LAYER, kind, params)
}

fn set_adjustment(base: &Document, layer: LayerId, kind: &str, params: &Value) -> Result<Document, String> {
    let adj = photocraft_engine::adjust_params::from_params(kind, params, None, base.mode).map_err(|e| e.to_string())?;
    if base.mode == ColorMode::Grayscale && !keeps_gray(&adj) {
        return Err("colour result in a grayscale document".into());
    }
    let mut out = base.clone();
    let l = out.layer_mut(layer).ok_or("no preview layer")?;
    l.content = LayerContent::Adjustment(adj);
    Ok(out)
}

/// `doc` with the dialog's adjustment as a temporary layer clipped to `target` (the selection as
/// its mask): [`base_document`] then [`with_settings`].
pub fn preview_document(doc: &Document, target: LayerId, kind: &str, params: &Value) -> Result<Document, String> {
    with_settings(&base_document(doc, target)?, kind, params)
}

/// The canvas area the preview can change: the target's content within the selection, grown by
/// the reach of layer effects (the target's and its groups').
pub fn region(doc: &Document, target: LayerId) -> Rect {
    let Some(s) = doc.layer(target).and_then(Layer::surface) else { return Rect::EMPTY };
    let mut r = s.content_bounds().intersect(&doc.bounds());
    if let Some(sel) = &doc.selection {
        r = r.intersect(&sel.content_bounds());
    }
    if r.is_empty() {
        return r;
    }
    r.inflate(crate::canvas::effect_reach(&doc.layers)).intersect(&doc.bounds())
}

/// Per-dialog preview state on the app.
pub struct AdjustPreview {
    /// The document the session belongs to, for [`retain_documents`].
    doc: DocId,
    /// The document revision the session began at: a switch asked for another revision is not this session's.
    // PLAN: decisions.md drops `revision` from this struct, but `switch_region` and its trial ("another revision" gives None) take the revision as an argument, which only a stored one can be compared with.
    revision: u64,
    /// The dialog lane's keys, session (document, revision, target, channel target), region, covered area and settle time.
    live: LivePreview,
    /// The session's [`base_document`], or None when it previews on the CPU proxy.
    base: Option<Arc<Document>>,
    /// The last key `live` gave: the key of the settings shown, [`PreviewKey::NONE`] before the first.
    keyed: PreviewKey,
    /// Hash of the kind, settings and Preview checkbox (0: no dialog).
    hash: u64,
    /// Whether the layer path handles these settings (false: CPU proxy preview).
    layer_path: bool,
    /// The preview document and its key, or None (proxy path, or the Preview checkbox is off).
    shown: Option<(Arc<Document>, PreviewKey)>,
    /// The dialog's kind and parameters.
    settings: (String, Value),
    /// Reduced-resolution copy for zoomed-out views (see [`gpu_proxy`]).
    proxy: Option<GpuProxy>,
}

/// A [`base_document`] scaled down by `k` for zoomed-out GPU previews, with its own document and
/// layer ids (so its textures live beside the full-size document's), plus the preview built from
/// it for the current settings.
struct GpuProxy {
    k: u32,
    base: Arc<Document>,
    /// (the shown key, preview).
    shown: Option<(PreviewKey, Arc<Document>)>,
    /// The key last composited into the proxy's texture.
    drawn: Option<PreviewKey>,
}

/// The open adjustment dialog: (kind, params, Preview on and not held to compare). None for a Smart Filter edit, which
/// previews through the filter machinery.
fn dialog(app: &PhotocraftApp) -> Option<(String, Value, bool)> {
    let open = crate::adjust_dialog::open_value(app).filter(|open| open.smart_filter.is_none())?;
    let hosted = crate::adjust_dialog::hosted(app, open.id)?;
    let params = hosted.value().params(hosted.edited());
    crate::actions::authorize_panel_preview(app, open.id, &open.command, &params).ok()?;
    Some((open.kind.clone(), params, hosted.is_previewing() && !hosted.is_comparing()))
}

/// Whether Image › Adjustments `kind` on document `idx` would edit a channel (the Channels panel's
/// target or the Quick Mask) or the active layer's mask instead of the layer's pixels.
pub(crate) fn targets_channel(app: &PhotocraftApp, idx: usize, kind: &str, params: &Value) -> bool {
    // The dialog's own target choice, when it has one, decides.
    if let Some(target) = params.get("target") {
        return target.as_str() != Some("pixels");
    }
    let Some(st) = app.session.documents().get(idx) else { return false };
    st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite
        || st.doc.quick_mask.is_some()
        || !app.with_mask_target(&format!("image.adjustments.{kind}"), Value::Null).is_null()
}

/// Whether the layer path can draw `doc` cheaply on this app's canvas.
fn cheap(app: &PhotocraftApp, doc: &Document) -> bool {
    match &app.gpu {
        Some(g) => g.supports(doc),
        None => crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app)) <= 1,
    }
}

/// Bring the cached preview up to date for document `idx` (the active one) and return it.
fn update(app: &mut PhotocraftApp, idx: usize) -> Option<&AdjustPreview> {
    if app.session.active_index() != Some(idx) {
        return None;
    }
    let Some((kind, params, preview)) = dialog(app) else {
        // Keep a closed dialog's session for the canvas's switch back (see `switch_region`) but
        // never show it.
        if let Some(p) = app.adjust_preview.as_mut() {
            (p.hash, p.layer_path, p.shown) = (0, false, None);
        }
        crate::render_path::adjust_preview_ok(app);
        return None;
    };
    let st = app.session.documents().get(idx)?;
    let (doc_id, revision, target) = (st.doc.id, st.revision, st.active_layer?);
    // Commands that target a channel (Channels panel / Quick Mask) or a layer mask keep the proxy
    // preview.
    let channel_target = targets_channel(app, idx, &kind, &params);
    let session = PreviewSession::new(doc_id.0, revision, target.0).and(u64::from(channel_target));
    let h = settings_hash(&[kind.as_bytes(), params.to_string().as_bytes(), &[u8::from(preview)]]);
    if let Some(p) = &app.adjust_preview
        && p.doc == doc_id
        && p.live.session() == Some(session)
        && p.hash == h
    {
        return app.adjust_preview.as_ref();
    }
    if app.adjust_preview.as_ref().is_none_or(|p| p.doc != doc_id || p.live.session() != Some(session)) {
        let doc = st.doc.clone();
        let base = if channel_target { None } else { base_document(&doc, target).ok() };
        // A target the layer path can't preview (or the GPU can't draw) falls to the CPU proxy: say
        // why (#7487), in the preview's own slot. A channel target's proxy is by design, not a
        // fallback.
        let gpu_refuses = app.gpu.as_ref().zip(base.as_ref()).is_some_and(|(g, b)| !g.supports(b));
        match (!channel_target).then(|| unsupported(&doc, target)).flatten().or(gpu_refuses.then_some("the GPU can't draw the result")) {
            Some(why) => crate::render_path::adjust_preview_cpu(app, doc_id.0, why),
            None => crate::render_path::adjust_preview_ok(app),
        }
        let base = base.filter(|b| cheap(app, b)).map(Arc::new);
        let region = if base.is_some() { region(&doc, target) } else { Rect::EMPTY };
        let mut live = LivePreview::new(PreviewLane::Dialog);
        live.begin(session, pixel_rect(&region));
        app.adjust_preview = Some(AdjustPreview {
            doc: doc_id,
            revision,
            live,
            base,
            keyed: PreviewKey::NONE,
            hash: 0,
            layer_path: false,
            shown: None,
            settings: (String::new(), Value::Null),
            proxy: None,
        });
    }
    let now = now_s(app);
    let p = app.adjust_preview.as_mut()?;
    let built = p.base.as_ref().and_then(|b| with_settings(b, &kind, &params).ok());
    let key = p.live.key(h, now);
    p.keyed = key;
    p.layer_path = built.is_some();
    p.shown = built.filter(|_| preview).map(|d| (Arc::new(d), key));
    p.hash = h;
    p.settings = (kind, params);
    app.adjust_preview.as_ref()
}

/// The document the canvas shows for document `idx` while an adjustment dialog previews through
/// the layer path: (document, preview key).
pub fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {
    update(app, idx)?.shown.as_ref().map(|(doc, key)| (doc.clone(), key.raw()))
}

/// Whether the open adjustment dialog previews through the layer path (so the CPU proxy preview
/// must stay off).
pub fn on_layer(app: &mut PhotocraftApp, idx: usize) -> bool {
    update(app, idx).is_some_and(|p| p.layer_path)
}

/// The canvas area to recomposite when document `idx` (at `revision`) switches from the preview
/// key `from` to `to` (raw keys, display transform removed): both must be this dialog's previews
/// or the committed document (0). None means "everything".
pub fn switch_region(app: &PhotocraftApp, doc: DocId, revision: u64, from: u64, to: u64) -> Option<Rect> {
    let p = app.adjust_preview.as_ref().filter(|p| p.doc == doc && p.revision == revision)?;
    let (from, to) = (PreviewKey::from_raw(from), PreviewKey::from_raw(to));
    (p.live.owns(from) && p.live.owns(to) && (!from.is_none() || !to.is_none())).then(|| doc_rect(p.live.region()))
}

/// The key of the preview currently shown, if any.
pub fn shown_key(app: &PhotocraftApp) -> Option<u64> {
    app.adjust_preview.as_ref()?.shown.as_ref().map(|s| s.1.raw())
}

/// The part of a switch's region (from [`switch_region`]) to composite now: to a preview, only
/// what the view shows (`visible`, document pixels), remembering it so [`uncovered`] catches up
/// as the view moves; back to the committed document (key 0), the whole region.
pub fn switch_damage(app: &mut PhotocraftApp, to: u64, region: Rect, visible: Rect) -> Rect {
    let Some(p) = app.adjust_preview.as_mut() else { return region };
    let to = PreviewKey::from_raw(to);
    // The switch's own `from` is not known here and no key is recorded with an area, so the damage is the region
    // either way; going back to the committed document (no key of its own) switches from the key last given.
    let from = if to.is_none() { p.keyed } else { to };
    p.live.switch(from, to, pixel_rect(&visible)).map_or(region, doc_rect)
}

/// Where the main canvas texture (showing preview `key`) is out of date within `visible`: the
/// region's visible part when the view moved past what was composited. Marks it covered.
pub fn uncovered(app: &mut PhotocraftApp, doc: DocId, key: u64, visible: Rect) -> Option<Rect> {
    let p = app.adjust_preview.as_mut().filter(|p| p.doc == doc)?;
    p.live.uncovered(PreviewKey::from_raw(key), pixel_rect(&visible)).map(doc_rect)
}

/// True while the preview's settings changed within the last `ms` milliseconds (secondary views
/// such as the Navigator wait for the settings to settle instead of recompositing every change).
pub fn settling(app: &PhotocraftApp, ms: f64) -> bool {
    app.adjust_preview.as_ref().is_some_and(|p| p.shown.is_some() && p.live.settling(now_s(app), ms / 1000.0))
}

/// Proxy document ids: the document's id with this bit flipped.
const PROXY_DOC_BIT: u64 = 1 << 60;
/// Proxy layer ids: the layer's id with this bit flipped (document layer ids are small counters;
/// [`PREVIEW_LAYER`] has it set).
const PROXY_LAYER_BIT: u64 = 1 << 62;

fn flip_ids(layers: &mut [Layer]) {
    for l in layers {
        l.id = LayerId(l.id.0 ^ PROXY_LAYER_BIT);
        if let Some(ch) = l.children_mut() {
            flip_ids(ch);
        }
    }
}

/// A [`base_document`] scaled down by `k` with its own document and layer ids (so the GPU keeps
/// its textures beside the full-size document's).
pub fn proxy_base(base: &Document, k: u32) -> Document {
    let mut d = photocraft_compose::proxy::proxy_document(base, k);
    d.id = photocraft_doc::DocId(base.id.0 ^ PROXY_DOC_BIT);
    flip_ids(&mut d.layers);
    d
}

/// [`with_settings`] for a [`proxy_base`].
pub fn proxy_with_settings(proxy: &Document, kind: &str, params: &Value) -> Result<Document, String> {
    set_adjustment(proxy, LayerId(PREVIEW_LAYER.0 ^ PROXY_LAYER_BIT), kind, params)
}

/// A frame of the zoomed-out preview: composite `doc` (the proxy preview, its own document id)
/// into its GPU texture over `damage` (None: everything), then draw it scaled by `k`.
pub struct ProxyFrame {
    pub k: u32,
    pub doc: Arc<Document>,
    pub damage: Option<Rect>,
    /// False when the texture already shows this preview.
    pub stale: bool,
    key: PreviewKey,
}

/// The zoomed-out preview for document `idx` at `zoom`, when the dialog previews through the layer
/// and the view is far enough out that a reduced copy shows the same detail as the full-size
/// composite: each change then composites ~1/k² of the pixels. Built once per session and factor.
pub fn gpu_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<ProxyFrame> {
    if !crate::proxy::reduced_previews(app) {
        return None;
    }
    let gpu = app.gpu.clone()?;
    update(app, idx)?;
    let p = app.adjust_preview.as_mut()?;
    p.shown.as_ref()?;
    let base = p.base.clone()?;
    let key = p.shown.as_ref()?.1;
    // `ProxyPlan::factor` is 1 for a document too small for a proxy, which `k < 2` refuses with the near views.
    let k = ProxyPlan::factor(zoom, base.size.area(), true);
    if k < 2 || !photocraft_compose::proxy::proxy_faithful(&base) {
        return None;
    }
    if p.proxy.as_ref().is_none_or(|g| g.k != k) {
        let d = proxy_base(&base, k);
        if !gpu.supports(&d) {
            return None;
        }
        p.proxy = Some(GpuProxy { k, base: Arc::new(d), shown: None, drawn: None });
    }
    let (kind, params) = &p.settings;
    let region = p.live.region();
    let g = p.proxy.as_mut()?;
    if g.shown.as_ref().is_none_or(|(shown, _)| *shown != key) {
        let d = proxy_with_settings(&g.base, kind, params).ok()?;
        g.shown = Some((key, Arc::new(d)));
    }
    let doc = g.shown.as_ref()?.1.clone();
    let scaled = doc_rect(ProxyPlan::scaled(region, k)).intersect(&doc.bounds());
    let damage = g.drawn.map(|_| scaled);
    Some(ProxyFrame { k, doc, damage, stale: g.drawn != Some(key), key })
}

/// Record that `frame` was composited into the proxy's texture.
pub fn proxy_drawn(app: &mut PhotocraftApp, frame: &ProxyFrame) {
    if let Some(g) = app.adjust_preview.as_mut().and_then(|p| p.proxy.as_mut())
        && g.k == frame.k
    {
        g.drawn = Some(frame.key);
    }
}

pub(crate) fn retain_documents(app: &mut PhotocraftApp) {
    // Native reopen can reuse the ID and revision; neither the old base document nor its
    // coverage and upload markers may survive after that document leaves the session.
    if app.adjust_preview.as_ref().is_some_and(|p| !app.session.documents().iter().any(|st| st.doc.id == p.doc)) {
        app.adjust_preview = None;
    }
    if app.live_adjust_preview.as_ref().is_some_and(|p| !app.session.documents().iter().any(|st| st.doc.id == p.doc)) {
        app.live_adjust_preview = None;
    }
}

/// GPU texture keys the preview uses besides the documents' own (keep them alive).
pub fn gpu_keys(app: &PhotocraftApp) -> Option<u64> {
    let p = app.adjust_preview.as_ref().filter(|p| p.hash != 0)?;
    p.proxy.as_ref().map(|g| g.base.id.0)
}

// ---------------------------------------------------------------------------------------------
// The Properties panel's live adjustment-layer preview (`canvas::display_doc`'s `live_adjust`).
//
// Dragging a control there shows the document with that layer's adjustment replaced. Unlike the
// dialog above it needs no temporary layer: the layer is already in the document. What it did
// lack was a damage region, so every parameter value recomposited the whole document — on the
// GPU canvas at 100 % zoom that is the full size, measured at about 7 ms per megapixel, which
// made #5778 a latency regression (#6839). These give that path the same treatment the dialog
// gets: a session-tagged key, the layer's area as the damage, and of that only what the view
// shows, catching up as the view moves.

/// One Properties-panel drag: which layer of which document revision (the session of its own
/// lane, so its keys are never mistaken for the dialog's), the area its adjustment can change, and
/// what the canvas has composited of it so far.
pub struct LiveAdjust {
    /// The document the session belongs to, for [`retain_documents`].
    doc: DocId,
    /// The document revision the session began at (see [`AdjustPreview`]).
    revision: u64,
    live: LivePreview,
    /// The last key `live` gave.
    keyed: PreviewKey,
}

/// The area an adjustment layer can change: the whole document.
///
/// It is deliberately not narrowed by the layer's mask. A mask's coverage can live entirely in
/// its surface's *default pixel* with no tiles written — [`LayerMask::reveal_all`], which is what
/// `layer.newAdjustmentLayer` gives every adjustment layer — and such a mask reports an empty
/// `content_bounds()`. Intersecting with that emptied the region, so the damage was empty and the
/// compositor drew nothing at all for the whole drag. A mask only bounds the effect when it hides
/// outside its content (default pixel 0); that narrowing is worth little here, since the damage is
/// clipped to the view anyway ([`live_switch_damage`]), and is not worth the risk of showing stale
/// pixels. Too large only costs pixels; too small freezes the preview.
fn live_region(doc: &Document, layer: LayerId) -> Rect {
    if doc.layer(layer).is_none() {
        return Rect::EMPTY;
    }
    doc.bounds()
}

/// The preview key for `params` on `layer` of `doc` at `revision`, starting a session (and
/// measuring its region) when the document, revision or layer changes.
pub fn live_key(app: &mut PhotocraftApp, doc: &Document, revision: u64, layer: LayerId, params: &Value) -> u64 {
    let session = PreviewSession::new(doc.id.0, revision, layer.0);
    let now = now_s(app);
    let p = app.live_adjust_preview.get_or_insert_with(|| LiveAdjust {
        doc: doc.id,
        revision,
        live: LivePreview::new(PreviewLane::Properties),
        keyed: PreviewKey::NONE,
    });
    (p.doc, p.revision) = (doc.id, revision);
    // The region is measured once per session.
    if p.live.session() != Some(session) {
        p.live.begin(session, pixel_rect(&live_region(doc, layer)));
    }
    p.keyed = p.live.key(settings_hash(&[params.to_string().as_bytes()]), now);
    p.keyed.raw()
}

/// The canvas area to recomposite when document `doc` (at `revision`) switches between two of
/// this drag's previews, or between one and the committed document (0).
pub fn live_switch_region(app: &PhotocraftApp, doc: DocId, revision: u64, from: u64, to: u64) -> Option<Rect> {
    let p = app.live_adjust_preview.as_ref().filter(|p| p.doc == doc && p.revision == revision)?;
    let (from, to) = (PreviewKey::from_raw(from), PreviewKey::from_raw(to));
    (p.live.owns(from) && p.live.owns(to) && (!from.is_none() || !to.is_none())).then(|| doc_rect(p.live.region()))
}

/// The part of a switch's region to composite now: to a preview, only what the view shows,
/// remembered so [`live_uncovered`] catches up as the view moves; back to the committed
/// document (key 0), the whole region.
pub fn live_switch_damage(app: &mut PhotocraftApp, to: u64, region: Rect, visible: Rect) -> Rect {
    let Some(p) = app.live_adjust_preview.as_mut() else { return region };
    let to = PreviewKey::from_raw(to);
    // Going back to the committed document switches from the key last given (no key of it is shown).
    let from = if to.is_none() { p.keyed } else { to };
    p.live.switch(from, to, pixel_rect(&visible)).map_or(region, doc_rect)
}

/// Where the main canvas texture (showing preview `key`) is out of date within `visible`: the
/// region's visible part when the view moved past what was composited. Marks it covered.
pub fn live_uncovered(app: &mut PhotocraftApp, doc: DocId, key: u64, visible: Rect) -> Option<Rect> {
    let p = app.live_adjust_preview.as_mut().filter(|p| p.doc == doc)?;
    p.live.uncovered(PreviewKey::from_raw(key), pixel_rect(&visible)).map(doc_rect)
}

#[cfg(test)]
mod tests;