Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

137 KB
Raw Blame
//! GPU document canvas: an `egui_wgpu` paint callback that draws one document view with a custom
//! WGSL shader.
//!
//! The document's composite lives on the GPU as one or more mipmapped textures (premultiplied
//! alpha, sRGB-encoded values, matching how the CPU path and egui blend): `Rgba8Unorm` for 8-bit
//! documents, `Rgba16Float` for 16- and 32-bit documents when the adapter can render to and
//! filter it (so smooth gradients don't band and 32-bit values above 1.0 survive for the 32-bit
//! preview), within [`F16_BUDGET_PX`]; larger high-bit documents fall back to `Rgba8Unorm`.
//! Uploads are either full (new document, size change, re-render) or a damage rect (brush
//! strokes); after an upload only the affected region of each mip level is regenerated by a
//! render-pass blit chain. Documents larger than the device's maximum texture size are split
//! into tiles.
//!
//! Per frame the shader draws, in *device pixels*:
//! - a soft analytic drop shadow around the document on the pasteboard (erf-blurred box),
//! - a transparency checkerboard (8 pt squares, grays 255/204, the same size at every zoom)
//!   under the document, anchored to the document's top-left corner so it moves with the image,
//! - the document itself, sampled trilinearly when zoomed out, bilinearly between 1× and 2×, and
//!   with an anti-aliased "sharp nearest" filter at integer scales and ≥ 2×,
//! - a one-device-pixel pixel grid above 500% zoom, over pixels with content only.
//!
//! GPU resources live in the renderer's `callback_resources` type map; the per-frame callback only
//! carries plain view parameters, so it is `Send + Sync` on every target (including wasm).
//!
//! The document pixels still come from the CPU compositor (`photocraft-compose`) for now; the wgpu
//! compositor (M5) will render straight into these tiles.

use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::atomic::Ordering;

use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, RenderState, ScreenDescriptor};
use eframe::wgpu;

pub use photocraft_gpu::{DeviceHealth, Fault};

/// Default tile side; documents up to this size (and the device limit) use a single texture.
pub const DEFAULT_TILE: u32 = 8192;
/// Mip levels no larger than this on either side are redrawn whole on every edit rather than
/// just their damage (see [`mip_damage`], #6418). Every corrupted level measured was at most
/// 64 px; this leaves a factor of two.
const WHOLE_MIP_SIDE: u32 = 128;
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
/// Canvas texture format of high-bit documents (see [`GpuCanvas::format_for`]).
const FORMAT_HIGH: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
/// Largest high-bit document (in pixels) given an `Rgba16Float` canvas texture: 100 MP is
/// 800 MB at level 0, about 1.07 GB with mips (twice the `Rgba8Unorm` cost). Bigger 16/32-bit
/// documents (a 14000² one would need 2.1 GB) use `Rgba8Unorm`, so they stay on the GPU like
/// 8-bit ones. `PHOTOCRAFT_CANVAS_F16=0` turns the float canvas off, `=1` ignores this budget.
pub const F16_BUDGET_PX: u64 = 100_000_000;
const VIEW_UNIFORM_SIZE: u64 = 128;
const VIEW_FLOATS: usize = 32;
const TILE_UNIFORM_SIZE: u64 = 16;

/// Whether this view can use the GPU canvas. Flip and non-square pixel aspect correction are
/// still CPU blits (the shader's filtering assumes square pixels); rotation is a shader uniform.
pub fn gpu_view_ok(flip: bool, _rotation: f32, aspect: f32) -> bool {
    !flip && (aspect - 1.0).abs() < 1e-6
}

/// Parameters for drawing one document view. Positions are in egui points.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ViewParams {
    /// Document key used with [`GpuCanvas::upload_full`].
    pub doc: u64,
    /// Document size in pixels.
    pub doc_size: [u32; 2],
    /// Screen points per document pixel.
    pub zoom: f32,
    /// Document point shown at the centre of the canvas rect.
    pub center: [f32; 2],
    /// Camera rotation in radians, clockwise in Y-down screen space. Rotate around [`Self::center`]
    /// before sampling. Flip stays on the CPU path.
    pub rotation: f32,
    /// Draw the drop shadow on the pasteboard.
    pub shadow: bool,
    /// Draw the pixel grid at high zoom.
    pub pixel_grid: bool,
    /// Distinguishes views painted in the same frame (main canvas, extra windows).
    pub view_key: u64,
    /// Display transform: 0 none, 1 the document's display LUT (document → monitor profile,
    /// Proof Colors), 2 LUT plus the gamut warning, 3 matrix/shaper (see [`GpuCanvas::set_display_lut`]).
    pub display: u8,
    /// The display the view is on (its LUT is per document and display, #569; 0 = unknown).
    pub output: u32,
    /// View › 32-bit Preview Options (exposure in stops, gamma), applied to the texture values
    /// before the display LUT; `None` when off. The display LUT must then leave it out
    /// (`ColorState::gpu_canvas_lut`).
    pub hdr: Option<[f32; 2]>,
    /// Where this draw puts the document, in document pixels from its own place: `[0, 0]` for the
    /// document, a whole number of widths and heights for a View › Pattern Preview copy (#1067).
    /// A copy samples the same texture, so nothing is composited again.
    pub offset: [f32; 2],
}

/// When high-bit documents get an `Rgba16Float` canvas texture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HighPolicy {
    /// The adapter can't render to or filter `Rgba16Float`, or `PHOTOCRAFT_CANVAS_F16=0`.
    Off,
    /// Up to [`F16_BUDGET_PX`].
    Budget,
    /// Always (`PHOTOCRAFT_CANVAS_F16=1`).
    Always,
}

/// Uploads documents to the GPU and paints them. Cheap to clone.
///
/// Once the device is lost or reports an uncaptured error (see [`GpuCanvas::fault`]), every
/// method is a no-op or an `Err`, so nothing reaches the GPU again; the app then switches to the
/// CPU canvas (#243).
#[derive(Clone)]
pub struct GpuCanvas {
    rs: RenderState,
    tile: u32,
    high: HighPolicy,
    health: photocraft_gpu::DeviceHealth,
    /// [`video_memory`] of the adapter, detected once.
    vram: Option<u64>,
    /// [`canvas_budget`], shared with the paint callback's resources: [`GpuCanvas::format_for`]
    /// reads it while the renderer is locked.
    canvas_budget: std::sync::Arc<std::sync::atomic::AtomicU64>,
}

/// Whether `regenerate_mips` builds each level in a scratch texture and copies it back: on
/// Intel adapters under DX12 only, where some drivers corrupt reduced previews when a pass
/// samples one mip level and renders into another of the same texture (#892, Intel UHD 620).
/// Everywhere else it renders straight into the level: on an NVIDIA DX12 adapter the scratch
/// textures, created per level on every refresh, cost about 1 ms of CPU time per brush dab
/// (#4515). `PHOTOCRAFT_SEPARATE_MIPS` (`setting`) forces it on (`1`) or off (`0`).
pub fn separate_mip_targets(backend: wgpu::Backend, vendor: u32, setting: Option<&str>) -> bool {
    const INTEL: u32 = 0x8086;
    match setting.map(str::trim) {
        Some("1") => true,
        Some("0") => false,
        _ => backend == wgpu::Backend::Dx12 && vendor == INTEL,
    }
}

/// Can `adapter` use `Rgba16Float` as a sampled, filtered, render-target and copy texture?
/// (Core WebGPU guarantees it; WebGL2 needs `EXT_color_buffer_float`, and some drivers lack it.)
pub fn supports_f16_canvas(adapter: &wgpu::Adapter) -> bool {
    let f = adapter.get_texture_format_features(FORMAT_HIGH);
    let usages = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC;
    f.allowed_usages.contains(usages) && f.flags.contains(wgpu::TextureFormatFeatureFlags::FILTERABLE)
}

impl GpuCanvas {
    /// Create pipelines and register resources with the egui renderer.
    pub fn new(rs: &RenderState) -> Self {
        Self::with_tile(rs, None)
    }

    /// Like [`GpuCanvas::new`] with a preferred texture tile side (`PHOTOCRAFT_GPU_TILE` wins).
    pub fn with_tile(rs: &RenderState, tile: Option<u32>) -> Self {
        let max = rs.device.limits().max_texture_dimension_2d;
        let env_tile = std::env::var("PHOTOCRAFT_GPU_TILE").ok().and_then(|v| v.parse::<u32>().ok());
        let tile = env_tile.or(tile).unwrap_or(DEFAULT_TILE).clamp(64, max);
        let high = match std::env::var("PHOTOCRAFT_CANVAS_F16").ok().as_deref() {
            _ if !supports_f16_canvas(&rs.adapter) => HighPolicy::Off,
            Some("0") => HighPolicy::Off,
            Some("1") => HighPolicy::Always,
            _ => HighPolicy::Budget,
        };
        // Device loss and uncaptured errors mark this flag instead of panicking (#243).
        let health = photocraft_gpu::DeviceHealth::watch(&rs.device);
        let mut res = Resources::new(&rs.device, &rs.queue, rs.target_format, high != HighPolicy::Off);
        res.health = health.clone();
        let info = rs.adapter.get_info();
        res.separate_mip_targets = separate_mip_targets(info.backend, info.vendor, std::env::var("PHOTOCRAFT_SEPARATE_MIPS").ok().as_deref());
        let vram = video_memory(&info);
        res.canvas_budget.store(canvas_budget(physical_memory(), vram), Ordering::Relaxed);
        let budget = res.canvas_budget.clone();
        rs.renderer.write().callback_resources.insert(res);
        log::info!(
            "gpu canvas: target {:?}, max texture {max}, tile {tile}, 16F canvas {high:?}, video memory {}",
            rs.target_format,
            vram.map_or_else(|| "unknown".to_owned(), |b| format!("{} MB", b >> 20))
        );
        Self { rs: rs.clone(), tile, high, health, vram, canvas_budget: budget }
    }

    /// The device's health flag (shared with the wgpu compositor and the paint callback).
    pub fn health(&self) -> &photocraft_gpu::DeviceHealth {
        &self.health
    }

    /// Why the GPU can't be used any more (`None` while it can).
    pub fn fault(&self) -> Option<photocraft_gpu::Fault> {
        self.health.fault()
    }

    /// Free every GPU resource the canvas holds (compositor pages, document textures, LUTs) after
    /// a fault; the paint callback draws nothing from then on.
    pub fn release(&self) {
        let mut r = self.rs.renderer.write();
        if let Some(res) = r.callback_resources.get_mut::<Resources>() {
            res.compositor = None;
            res.compositor_failed = Some(photocraft_gpu::Unsupported(self.fault().map_or_else(|| "GPU canvas released".into(), |f| f.to_string())));
            res.docs.clear();
            res.luts.clear();
            res.display_lut_signatures.clear();
            res.views.clear();
        }
    }

    /// The adapter this canvas renders with.
    pub fn adapter_info(&self) -> wgpu::AdapterInfo {
        self.rs.adapter.get_info()
    }

    /// The adapter's own memory where it has one and the platform reports it (see
    /// [`video_memory`]); it caps [`memory_budget`] and [`canvas_budget`].
    pub fn video_memory(&self) -> Option<u64> {
        self.vram
    }

    /// The canvas texture format for a document of `depth` and `size`: `Rgba16Float` for 16/32-bit
    /// documents when the adapter supports it and the document fits [`F16_BUDGET_PX`], else
    /// `Rgba8Unorm`.
    /// The device's largest 2D texture side (egui textures can use it too).
    pub fn max_texture_side(&self) -> usize {
        self.rs.device.limits().max_texture_dimension_2d as usize
    }

    pub fn format_for(&self, depth: photocraft_doc::SampleType, size: [u32; 2]) -> wgpu::TextureFormat {
        let px = size[0] as u64 * size[1] as u64;
        let high = match self.high {
            HighPolicy::Off => false,
            // Within the canvas budget too: a 16-bit canvas a small card can't hold as floats
            // stays on the GPU as `Rgba8Unorm` rather than falling back to the CPU canvas.
            HighPolicy::Budget => {
                px <= F16_BUDGET_PX && canvas_texture_bytes(size, self.tile, texel_bytes(FORMAT_HIGH)) <= self.canvas_budget.load(Ordering::Relaxed)
            }
            HighPolicy::Always => true,
        };
        if high && depth != photocraft_doc::SampleType::U8 { FORMAT_HIGH } else { FORMAT }
    }

    /// Format and GPU bytes (all tiles, all mip levels) of document `key`'s canvas texture.
    pub fn texture_info(&self, key: u64) -> Option<(wgpu::TextureFormat, u64)> {
        let r = self.rs.renderer.read();
        let d = r.callback_resources.get::<Resources>()?.docs.get(&key)?;
        let bpp = texel_bytes(d.format);
        let bytes = d
            .tiles
            .iter()
            .map(|t| (0..t.levels.len() as u32).map(|l| ((t.rect[2] >> l).max(1) as u64) * ((t.rect[3] >> l).max(1) as u64) * bpp).sum::<u64>())
            .sum();
        Some((d.format, bytes))
    }

    /// Set the GPU memory the wgpu compositor may hold for layer pages and caches (see
    /// [`memory_budget`]); pages beyond it are evicted least recently used first.
    pub fn set_memory_budget(&self, bytes: u64) {
        let mut r = self.rs.renderer.write();
        if let Some(res) = r.callback_resources.get_mut::<Resources>() {
            res.compositor_budget = Some(bytes);
        }
    }

    /// The compositor's memory budget (`None` until [`GpuCanvas::set_memory_budget`]).
    pub fn memory_budget(&self) -> Option<u64> {
        let r = self.rs.renderer.read();
        r.callback_resources.get::<Resources>()?.compositor_budget
    }

    /// Set the GPU bytes one document's display texture set may take (see [`canvas_budget`]).
    pub fn set_canvas_budget(&self, bytes: u64) {
        self.canvas_budget.store(bytes, Ordering::Relaxed);
    }

    /// Whether `doc`'s display textures fit [`canvas_budget`]; when they don't, nothing is
    /// created for it and it is drawn on the CPU canvas.
    pub fn fits_canvas(&self, doc: &photocraft_doc::Document) -> bool {
        let size = [doc.size.width, doc.size.height];
        let bytes = canvas_texture_bytes(size, self.tile, texel_bytes(self.format_for(doc.depth, size)));
        let r = self.rs.renderer.read();
        r.callback_resources.get::<Resources>().is_some_and(|res| bytes <= res.canvas_budget.load(Ordering::Relaxed))
    }

    /// Cap lower-stack composite reuse; zero disables it for profiling the uncached path.
    pub fn set_composite_cache_budget(&self, bytes: u64) {
        let mut r = self.rs.renderer.write();
        if let Some(res) = r.callback_resources.get_mut::<Resources>() {
            res.compositor_cache_budget = Some(bytes);
            if let Some(comp) = &mut res.compositor {
                comp.set_composite_cache_budget(bytes);
            }
        }
    }

    /// The document area the view shows: full refreshes composite it last, so its layer pages
    /// are the ones still resident for the edits that follow.
    pub fn set_focus(&self, focus: Option<photocraft_geom::Rect>) {
        let mut r = self.rs.renderer.write();
        if let Some(res) = r.callback_resources.get_mut::<Resources>() {
            res.compositor_focus = focus;
        }
    }

    /// Take any GPU measurement that has landed since the last call, without compositing
    /// anything. [`Compositor::render`] carries measurements out in its stats, but a refresh is
    /// the only thing that collects them, so the last refresh before the app goes idle would
    /// never be reported. The frame loop calls this so it is.
    pub fn take_gpu_timing(&self) -> Option<photocraft_gpu::GpuTiming> {
        let mut r = self.rs.renderer.write();
        r.callback_resources.get_mut::<Resources>()?.compositor.as_mut()?.take_gpu_timing()
    }

    /// GPU bytes the wgpu compositor holds: resident layer pages and caches (effect maps and
    /// lower-stack chunks). Keep the scorecard's memory measurements inclusive of reuse.
    pub fn compositor_bytes(&self) -> Option<(u64, usize)> {
        let r = self.rs.renderer.read();
        let c = r.callback_resources.get::<Resources>()?.compositor.as_ref()?;
        Some((c.resident_bytes(), c.fx_cache_bytes().saturating_add(usize::try_from(c.composite_cache_bytes()).unwrap_or(usize::MAX))))
    }

    /// Whether `doc`'s layers fit the budget as it now stands, measured without a refresh (a GPU
    /// Memory change shows in the status bar at once). `None` before the compositor exists.
    pub fn measure_fit(&self, doc: &photocraft_doc::Document) -> Option<LayerFit> {
        let mut r = self.rs.renderer.write();
        let res = r.callback_resources.get_mut::<Resources>()?;
        let budget = res.compositor_budget;
        let comp = res.compositor.as_mut()?;
        if let Some(b) = budget {
            comp.set_memory_budget(b);
        }
        let needed = comp.working_set(doc, doc.bounds());
        let fit = LayerFit { doc: doc.id.0, needed, budget: comp.fit_layers(needed, true) };
        res.layer_fit = Some(fit);
        Some(fit)
    }

    /// Whether the layers of the last full (or large) refresh fit the GPU memory budget, and by
    /// how much (`None` before the first one).
    pub fn layer_fit(&self) -> Option<LayerFit> {
        let r = self.rs.renderer.read();
        r.callback_resources.get::<Resources>()?.layer_fit
    }

    /// Set the checkerboard and gamut warning colours.
    pub fn set_style(&self, style: CanvasStyle) {
        let mut r = self.rs.renderer.write();
        if let Some(res) = r.callback_resources.get_mut::<Resources>() {
            res.style = style;
        }
    }

    /// Whether document `doc` has been uploaded with this size.
    pub fn has(&self, doc: u64, size: [u32; 2]) -> bool {
        let r = self.rs.renderer.read();
        r.callback_resources.get::<Resources>().and_then(|res| res.docs.get(&doc)).is_some_and(|d| d.size == size)
    }

    /// Whether [`GpuCanvas::composite`] would draw `doc` with the wgpu compositor (rather than
    /// fall back to the CPU compositor).
    pub fn supports(&self, doc: &photocraft_doc::Document) -> bool {
        if std::env::var_os("PHOTOCRAFT_CPU_COMPOSE").is_some() || doc.size.width == 0 || doc.size.height == 0 {
            return false;
        }
        let r = self.rs.renderer.read();
        let Some(res) = r.callback_resources.get::<Resources>() else { return false };
        if res.compositor_failed.is_some() {
            return false;
        }
        match &res.compositor {
            Some(c) => c.supports(doc).is_ok(),
            // Layers larger than the texture limit are stored in pages, so any size qualifies.
            None => photocraft_gpu::plan(doc).is_ok(),
        }
    }

    /// Replace the whole document image with an `Rgba8Unorm` texture. `rgba` is premultiplied
    /// RGBA8, `size[0] * size[1] * 4` bytes (anything else is ignored).
    pub fn upload_full(&self, doc: u64, size: [u32; 2], rgba: &[u8]) {
        self.upload_full_as(doc, size, FORMAT, rgba);
    }

    /// Replace the whole document image with a `format` texture of premultiplied `texels`.
    fn upload_full_as(&self, doc: u64, size: [u32; 2], format: wgpu::TextureFormat, texels: &[u8]) {
        if size[0] == 0 || size[1] == 0 || texels.len() as u64 != size[0] as u64 * size[1] as u64 * texel_bytes(format) || !self.health.is_ok() {
            return;
        }
        let (device, queue) = (&self.rs.device, &self.rs.queue);
        let mut renderer = self.rs.renderer.write();
        let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return };
        if res.docs.get(&doc).is_none_or(|d| d.size != size || d.format != format) {
            let Some(tex) = DocTextures::new(device, res, size, self.tile, format) else {
                res.docs.remove(&doc);
                return;
            };
            res.docs.insert(doc, tex);
        }
        let Some(d) = res.docs.get(&doc) else { return };
        d.write(queue, [0, 0], size, size[0], texels);
        d.regenerate_mips(device, queue, res, [0, 0, size[0], size[1]]);
    }

    /// Replace a rectangle `origin..origin+size` of an uploaded document with premultiplied texels
    /// in its texture format (`size[0] * size[1]` texels: RGBA8 or RGBA16F). Returns false if the
    /// document isn't uploaded, the rectangle doesn't fit or the buffer has the wrong size.
    pub fn upload_rect(&self, doc: u64, origin: [u32; 2], size: [u32; 2], texels: &[u8]) -> bool {
        if !self.health.is_ok() {
            return false;
        }
        let (device, queue) = (&self.rs.device, &self.rs.queue);
        let mut renderer = self.rs.renderer.write();
        let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return false };
        let Some(d) = res.docs.get(&doc) else { return false };
        if texels.len() as u64 != size[0] as u64 * size[1] as u64 * texel_bytes(d.format)
            || origin[0].saturating_add(size[0]) > d.size[0]
            || origin[1].saturating_add(size[1]) > d.size[1]
        {
            return false;
        }
        if size[0] == 0 || size[1] == 0 {
            return true;
        }
        d.write(queue, origin, size, size[0], texels);
        d.regenerate_mips(device, queue, res, [origin[0], origin[1], origin[0] + size[0], origin[1] + size[1]]);
        true
    }

    /// The texture format of uploaded document `doc`.
    fn format_of(&self, doc: u64) -> Option<wgpu::TextureFormat> {
        let r = self.rs.renderer.read();
        r.callback_resources.get::<Resources>().and_then(|res| res.docs.get(&doc)).map(|d| d.format)
    }

    /// Upload a CPU composite covering the whole document (a preview of a document of `depth`:
    /// see [`GpuCanvas::format_for`]).
    pub fn upload_buffer_full(&self, doc: u64, buf: &photocraft_compose::Buffer, depth: photocraft_doc::SampleType) {
        let size = [buf.rect.width(), buf.rect.height()];
        let format = self.format_for(depth, size);
        self.upload_full_as(doc, size, format, &texels(format, &buf.px));
    }

    /// Upload a CPU composite of a sub-rectangle (in document pixels, `buf.rect`).
    pub fn upload_buffer_rect(&self, doc: u64, buf: &photocraft_compose::Buffer) -> bool {
        let r = buf.rect;
        let Some(format) = self.format_of(doc) else { return false };
        if r.x0 < 0 || r.y0 < 0 {
            return false;
        }
        self.upload_rect(doc, [r.x0 as u32, r.y0 as u32], [r.width(), r.height()], &texels(format, &buf.px))
    }

    /// Composite `region` of `doc` with the wgpu compositor straight into its display texture
    /// (no CPU pixels, no upload of the composite). `encode_srgb` stores the sRGB encoding of the
    /// composite (linear documents, see `photocraft_engine::display_color`). Returns `Err` when the
    /// document uses features the GPU compositor doesn't cover yet; the caller then falls back to
    /// the CPU compositor.
    pub fn composite(
        &self,
        doc: &photocraft_doc::Document,
        region: photocraft_geom::Rect,
        encode_srgb: bool,
    ) -> Result<photocraft_gpu::Stats, photocraft_gpu::Unsupported> {
        let (device, queue) = (&self.rs.device, &self.rs.queue);
        let size = [doc.size.width, doc.size.height];
        if size[0] == 0 || size[1] == 0 {
            return Err(photocraft_gpu::Unsupported("empty document".into()));
        }
        if std::env::var_os("PHOTOCRAFT_CPU_COMPOSE").is_some() {
            return Err(photocraft_gpu::Unsupported("disabled by PHOTOCRAFT_CPU_COMPOSE".into()));
        }
        if let Some(f) = self.fault() {
            return Err(photocraft_gpu::Unsupported(f.to_string()));
        }
        let mut renderer = self.rs.renderer.write();
        let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return Err(photocraft_gpu::Unsupported("no GPU canvas".into())) };
        // A driver that couldn't build the pipelines once won't later: stay on the CPU compositor.
        if let Some(e) = &res.compositor_failed {
            return Err(e.clone());
        }
        let mut comp = match res.compositor.take() {
            Some(c) => c,
            None => match photocraft_gpu::Compositor::try_new_with_format(device, photocraft_gpu::Compositor::preferred_acc_format(&self.rs.adapter)) {
                Ok(c) => c,
                Err(e) => {
                    log::warn!("{e}; using the CPU compositor");
                    res.compositor_failed = Some(e.clone());
                    return Err(e);
                }
            },
        };
        comp.set_health(self.health.clone());
        // Measured, not waited for: the timestamps come back a frame or two later.
        comp.measure_gpu_time(device, queue);
        if let Some(b) = res.compositor_budget {
            comp.set_memory_budget(b);
        }
        if let Some(b) = res.compositor_cache_budget {
            comp.set_composite_cache_budget(b);
        }
        comp.set_focus(res.compositor_focus);
        let key = doc.id.0;
        let format = self.format_for(doc.depth, size);
        let fresh = res.docs.get(&key).is_none_or(|d| d.size != size || d.format != format);
        let region = if fresh { doc.bounds() } else { region.intersect(&doc.bounds()) };
        // Checked before allocating a new canvas texture only: `render` plans (and refuses) itself.
        if fresh && let Err(e) = comp.supports(doc) {
            res.compositor = Some(comp);
            return Err(e);
        }
        // A full refresh whose layer pages don't fit the memory budget would re-upload the
        // evicted ones every time (no faster than the CPU, and more memory): the banded CPU
        // compositor does it (in the background on desktop). So does a large damage rect, such
        // as hiding a big layer (#4024); small edits in the view stay on the GPU.
        let large = region.width() as u64 * region.height() as u64 >= DEFER_PX;
        if region == doc.bounds() || large {
            let needed = comp.working_set(doc, region);
            let fit = LayerFit { doc: doc.id.0, needed, budget: comp.fit_layers(needed, region == doc.bounds()) };
            res.layer_fit = Some(fit);
            if !fit.fits() {
                res.compositor = Some(comp);
                return Err(photocraft_gpu::Unsupported(OVER_BUDGET.into()));
            }
        }
        if fresh {
            let Some(tex) = DocTextures::new(device, res, size, self.tile, format) else {
                res.docs.remove(&key);
                res.compositor = Some(comp);
                return Err(photocraft_gpu::Unsupported(OVER_CANVAS_BUDGET.into()));
            };
            res.docs.insert(key, tex);
        }
        let (Some(pipe), Some(d)) = (res.encode_pipeline(format), res.docs.get(&key)) else {
            res.compositor = Some(comp);
            return Err(photocraft_gpu::Unsupported(format!("no {format:?} canvas texture or pipeline")));
        };
        let bgl = &res.encode_bgl;
        // A float canvas keeps values above 1.0 (32-bit documents, for the 32-bit preview).
        let keep_hdr = i32::from(format == FORMAT_HIGH);
        // Last-resort guard: a wgpu panic (e.g. polling a device lost mid-refresh) marks the
        // device lost instead of taking the app and its documents down.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            comp.render(device, queue, doc, region, |enc, out| {
                for t in &d.tiles {
                    let [tx, ty, tw, th] = t.rect.map(|v| v as i32);
                    let r = out.rect.intersect(&photocraft_geom::Rect::from_xywh(tx, ty, tw as u32, th as u32));
                    if r.is_empty() {
                        continue;
                    }
                    let offset = [out.rect.x0 - tx, out.rect.y0 - ty, i32::from(encode_srgb), keep_hdr];
                    let ubuf = init_buffer(device, "pc_encode", &offset.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>(), wgpu::BufferUsages::UNIFORM);
                    let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                        label: Some("pc_encode"),
                        layout: bgl,
                        entries: &[
                            wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(out.view) },
                            wgpu::BindGroupEntry { binding: 1, resource: ubuf.as_entire_binding() },
                        ],
                    });
                    let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("pc_encode"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: &t.levels[0],
                            resolve_target: None,
                            depth_slice: None,
                            ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store },
                        })],
                        depth_stencil_attachment: None,
                        timestamp_writes: None,
                        occlusion_query_set: None,
                        multiview_mask: None,
                    });
                    pass.set_pipeline(pipe);
                    pass.set_bind_group(0, &bg, &[]);
                    pass.set_scissor_rect((r.x0 - tx) as u32, (r.y0 - ty) as u32, r.width(), r.height());
                    pass.draw(0..3, 0..1);
                }
            })
        }));
        let Ok(result) = result else {
            self.health.mark(photocraft_gpu::Fault::Lost("the GPU compositor stopped (internal error)".into()));
            res.docs.remove(&key);
            return Err(photocraft_gpu::Unsupported("GPU device lost".into()));
        };
        // Lost during the refresh: its output can't be trusted.
        let result = match self.fault() {
            Some(f) => Err(photocraft_gpu::Unsupported(f.to_string())),
            None => result,
        };
        if result.is_ok() {
            d.regenerate_mips(device, queue, res, [region.x0 as u32, region.y0 as u32, region.x1 as u32, region.y1 as u32]);
            if std::env::var_os("PHOTOCRAFT_GPU_SYNC").is_some() {
                // Benchmarking: wait for the GPU so callers can time the whole refresh.
                #[cfg(not(target_arch = "wasm32"))]
                self.health.wait(device, None);
            }
        } else if fresh {
            res.docs.remove(&key);
        }
        res.compositor = Some(comp);
        result
    }

    /// Bring document `key`'s display texture up to date with `doc`: only `damage` when given (a
    /// brush stroke on an already uploaded document), else everything. The wgpu compositor renders
    /// straight into the texture when it supports the document; otherwise the CPU compositor does.
    /// `display` is the canvas colour transform: the GPU path stores the sRGB encoding when it
    /// asks for it, and every CPU band or rect goes through its `texture_buffer`.
    pub fn refresh(
        &self,
        key: u64,
        doc: &photocraft_doc::Document,
        damage: Option<photocraft_geom::Rect>,
        display: Option<&photocraft_engine::display_color::CanvasDisplay>,
    ) -> Refresh {
        self.refresh_with(key, doc, damage, display, false)
    }

    /// [`GpuCanvas::refresh`], except that with `defer`, a refresh of at least [`DEFER_PX`] the
    /// CPU compositor would draw is left to the caller (`background_redraw`): the texture is made
    /// ready (keeping what it shows when it already fits) and the kind is [`REFRESH_DEFERRED`].
    pub fn refresh_with(
        &self,
        key: u64,
        doc: &photocraft_doc::Document,
        damage: Option<photocraft_geom::Rect>,
        display: Option<&photocraft_engine::display_color::CanvasDisplay>,
        defer: bool,
    ) -> Refresh {
        if let Some(f) = self.fault() {
            // Nothing reaches the GPU any more; the app switches to the CPU canvas.
            return Refresh { kind: "lost", fallback: Some(f.to_string()), ..Default::default() };
        }
        if !self.fits_canvas(doc) {
            // Neither compositor can fill textures that are never created: the CPU canvas draws
            // it. A set left from before the canvas grew is stale, so it goes too.
            if let Some(res) = self.rs.renderer.write().callback_resources.get_mut::<Resources>() {
                res.docs.remove(&key);
            }
            return Refresh { kind: REFRESH_OVER_BUDGET, fallback: Some(OVER_CANVAS_BUDGET.into()), ..Default::default() };
        }
        let bounds = doc.bounds();
        let size = [doc.size.width, doc.size.height];
        let format = self.format_for(doc.depth, size);
        let damage = damage.filter(|_| self.has(key, size) && self.format_of(key) == Some(format)).map(|r| r.intersect(&bounds));
        let t0 = now_ms();
        let mut out = Refresh::default();
        if damage.is_some_and(|r| r.is_empty()) {
            // Nothing changed on the canvas (selecting a layer, say): don't even plan.
            out.kind = "rect";
            return out;
        }
        let region = damage.unwrap_or(bounds);
        let encode_srgb = display.is_some_and(|d| d.encode_srgb);
        let gpu = if key == doc.id.0 { self.composite(doc, region, encode_srgb) } else { Err(photocraft_gpu::Unsupported("preview texture".into())) };
        match gpu {
            Ok(stats) => {
                out.kind = if damage.is_some() { "gpu-rect" } else { "gpu-full" };
                out.px = region.width() as u64 * region.height() as u64;
                // Encoding and submitting only: the GPU is still running this work.
                out.composite_ms = now_ms() - t0;
                out.uploads = stats.tiles_uploaded as u64;
                out.gpu = stats.gpu_time;
                return out;
            }
            Err(e) => out.fallback = Some(e.0),
        }
        let px = region.width() as u64 * region.height() as u64;
        if defer && px >= DEFER_PX && self.prepare_texture(key, doc).is_some() {
            out.kind = REFRESH_DEFERRED;
            out.px = px;
            return out;
        }
        if let Some(r) = damage {
            if r.is_empty() {
                out.kind = "rect";
                return out;
            }
            let buf = photocraft_compose::render(doc, r);
            let t1 = now_ms();
            if self.upload_buffer_rect(key, &texture_buffer(display, &buf)) {
                out.kind = "rect";
                out.px = r.width() as u64 * r.height() as u64;
                out.composite_ms = t1 - t0;
                out.upload_ms = now_ms() - t1;
                return out;
            }
        }
        self.upload_composite(key, doc, display);
        out.kind = "full";
        out.px = bounds.width() as u64 * bounds.height() as u64;
        out.composite_ms = now_ms() - t0;
        out
    }

    /// Composite the whole of `doc` with the CPU compositor into document `key`'s texture, band by
    /// band (each band converted and uploaded before the next is rendered), so a huge document
    /// never needs a full-size float composite or texture-format copy in memory.
    pub fn upload_composite(&self, key: u64, doc: &photocraft_doc::Document, display: Option<&photocraft_engine::display_color::CanvasDisplay>) {
        let size = [doc.size.width, doc.size.height];
        let Some(format) = self.prepare_texture(key, doc) else { return };
        let (device, queue) = (&self.rs.device, &self.rs.queue);
        let mut rgba = Vec::new();
        let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> {
            if !self.health.is_ok() {
                return Err(());
            }
            texels_into(format, &texture_buffer(display, &band).px, &mut rgba);
            let renderer = self.rs.renderer.read();
            let d = renderer.callback_resources.get::<Resources>().and_then(|r| r.docs.get(&key)).ok_or(())?;
            d.write(queue, [0, band.rect.y0 as u32], [size[0], band.rect.height()], size[0], &rgba);
            drop(renderer);
            // Flush the staged band so its staging memory is reclaimed while the next renders.
            queue.submit(std::iter::empty::<wgpu::CommandBuffer>());
            self.health.poll(device);
            Ok(())
        });
        if !self.health.is_ok() {
            return;
        }
        let mut renderer = self.rs.renderer.write();
        if let Some(res) = renderer.callback_resources.get_mut::<Resources>()
            && let Some(d) = res.docs.get(&key)
        {
            d.regenerate_mips(device, queue, res, [0, 0, size[0], size[1]]);
        }
    }

    /// Make sure document `key` has a display texture of `doc`'s size and format, keeping the one
    /// it has when that fits. Returns its format, or `None` when it can't be created.
    pub fn prepare_texture(&self, key: u64, doc: &photocraft_doc::Document) -> Option<wgpu::TextureFormat> {
        let size = [doc.size.width, doc.size.height];
        if size[0] == 0 || size[1] == 0 || !self.health.is_ok() {
            return None;
        }
        let format = self.format_for(doc.depth, size);
        let mut renderer = self.rs.renderer.write();
        let res = renderer.callback_resources.get_mut::<Resources>()?;
        if res.docs.get(&key).is_none_or(|d| d.size != size || d.format != format) {
            let Some(tex) = DocTextures::new(&self.rs.device, res, size, self.tile, format) else {
                res.docs.remove(&key);
                return None;
            };
            res.docs.insert(key, tex);
        }
        Some(format)
    }

    /// Free textures, display LUTs and their signatures for documents not in `live`.
    pub fn retain(&self, live: &[u64]) {
        let mut renderer = self.rs.renderer.write();
        let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return };
        if res.docs.keys().any(|k| !live.contains(k)) {
            res.docs.retain(|k, _| live.contains(k));
        }
        // Everything the compositor holds for documents that aren't open, also when their
        // texture entry was dropped earlier (over budget, a failed render), which used to leave
        // their pages and effect maps resident after closing (#4529).
        if let Some(c) = res.compositor.as_mut() {
            c.retain_docs(|d| live.contains(&d.0));
        }
        // LUTs and identity-transform signatures can outlive document textures. Prune both,
        // or a preserved-ID reopen can skip rebuilding a missing LUT.
        res.luts.retain(|k, _| live.contains(&k.0));
        res.display_lut_signatures.retain(|k, _| live.contains(&k.0));
    }

    pub(crate) fn display_lut_signature(&self, doc: u64, output: u32) -> Option<(u64, u8)> {
        let renderer = self.rs.renderer.read();
        renderer.callback_resources.get::<Resources>()?.display_lut_signatures.get(&(doc, output)).copied()
    }

    /// Whether document `doc` has a display LUT for display `output` (tests).
    #[cfg(test)]
    pub(crate) fn has_display_lut(&self, doc: u64, output: u32) -> bool {
        let renderer = self.rs.renderer.read();
        renderer.callback_resources.get::<Resources>().is_some_and(|r| r.luts.contains_key(&(doc, output)))
    }

    pub(crate) fn cache_display_lut_signature(&self, doc: u64, output: u32, signature: u64, mode: u8) {
        let mut renderer = self.rs.renderer.write();
        if let Some(res) = renderer.callback_resources.get_mut::<Resources>() {
            res.display_lut_signatures.insert((doc, output), (signature, mode));
        }
    }

    /// Set (or clear with `None`) the display LUT of document `doc` on display `output`:
    /// `size`³ RGBA8 texels, red fastest. RGB is the display colour for each lattice input;
    /// alpha 255 marks out-of-gamut colours for the gamut warning.
    pub fn set_display_lut(&self, doc: u64, output: u32, size: u32, rgba: Option<&[u8]>) {
        if !self.health.is_ok() {
            return;
        }
        let (device, queue) = (&self.rs.device, &self.rs.queue);
        let mut renderer = self.rs.renderer.write();
        let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return };
        res.display_lut_signatures.remove(&(doc, output));
        match rgba {
            None => {
                res.luts.remove(&(doc, output));
            }
            Some(bytes) => {
                if size < 2 || bytes.len() as u64 != (size as u64).pow(3) * 4 {
                    log::warn!("set_display_lut: {} bytes for a {size}³ LUT; ignored", bytes.len());
                    return;
                }
                let bg = lut_bind_group(device, queue, &res.lut_bgl, size, bytes, None);
                res.luts.insert((doc, output), bg);
            }
        }
    }

    /// Set a separately sampled curve/matrix/curve display transform. CMS validates this
    /// representation and provides bounded tables; no profile interpretation lives in the UI.
    pub fn set_display_matrix_shaper(&self, doc: u64, output: u32, shaper: &photocraft_cms::GpuMatrixShaper) {
        if !self.health.is_ok() {
            return;
        }
        let mut renderer = self.rs.renderer.write();
        let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return };
        let bg = lut_bind_group(&self.rs.device, &self.rs.queue, &res.lut_bgl, 2, &identity_lut_bytes(), Some(shaper));
        res.display_lut_signatures.remove(&(doc, output));
        res.luts.insert((doc, output), bg);
    }

    /// Read back level 0 of document `key`'s canvas texture: its format, size and the stored
    /// (premultiplied) texels as `f32` RGBA, row-major. Waits for the GPU; for tests, benchmarks
    /// and debugging.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn read_texels(&self, key: u64) -> Option<(wgpu::TextureFormat, [u32; 2], Vec<[f32; 4]>)> {
        if !self.health.is_ok() {
            return None;
        }
        let (device, queue) = (&self.rs.device, &self.rs.queue);
        let renderer = self.rs.renderer.read();
        let d = renderer.callback_resources.get::<Resources>()?.docs.get(&key)?;
        let bpp = texel_bytes(d.format);
        let (w, h) = (d.size[0] as usize, d.size[1] as usize);
        let mut out = vec![[0.0f32; 4]; w.checked_mul(h)?];
        for t in &d.tiles {
            let [tx, ty, tw, th] = t.rect;
            let row = (tw as u64 * bpp).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64);
            let buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("pc_canvas_readback"),
                size: row * th as u64,
                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
                mapped_at_creation: false,
            });
            let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_canvas_readback") });
            enc.copy_texture_to_buffer(
                t.texture.as_image_copy(),
                wgpu::TexelCopyBufferInfo {
                    buffer: &buf,
                    layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row as u32), rows_per_image: Some(th) },
                },
                wgpu::Extent3d { width: tw, height: th, depth_or_array_layers: 1 },
            );
            queue.submit([enc.finish()]);
            let slice = buf.slice(..);
            slice.map_async(wgpu::MapMode::Read, |_| {});
            if !self.health.wait(device, None) {
                return None;
            }
            let data = slice.get_mapped_range().ok()?;
            for y in 0..th as usize {
                let src = data.get(y * row as usize..)?;
                for x in 0..tw as usize {
                    let o = out.get_mut((ty as usize + y) * w + tx as usize + x)?;
                    *o = texel_to_f32(d.format, src.get(x * bpp as usize..(x + 1) * bpp as usize)?);
                }
            }
        }
        Some((d.format, d.size, out))
    }

    /// Add the paint callback drawing `params` into `rect` (clipped by the painter's clip rect).
    pub fn paint(painter: &egui::Painter, rect: egui::Rect, params: ViewParams) {
        painter.add(egui_wgpu::Callback::new_paint_callback(rect, CanvasCallback { rect, params }));
    }
}

/// A CPU composite as the canvas texture stores it (`display`'s encoding; as is without one).
fn texture_buffer<'a>(
    display: Option<&photocraft_engine::display_color::CanvasDisplay>,
    buf: &'a photocraft_compose::Buffer,
) -> std::borrow::Cow<'a, photocraft_compose::Buffer> {
    match display {
        Some(d) => d.texture_buffer(buf),
        None => std::borrow::Cow::Borrowed(buf),
    }
}

/// A CPU composite `buf` as texels of a `format` canvas texture, in `display`'s encoding: what
/// [`GpuCanvas::upload_rect`] takes. Runs anywhere (a redraw's worker converts its own pieces).
pub fn display_texels(
    format: wgpu::TextureFormat,
    display: Option<&photocraft_engine::display_color::CanvasDisplay>,
    buf: &photocraft_compose::Buffer,
) -> Vec<u8> {
    texels(format, &texture_buffer(display, buf).px)
}

/// What a [`GpuCanvas::refresh`] did.
#[derive(Clone, Debug, Default)]
pub struct Refresh {
    /// "gpu-rect", "gpu-full" (wgpu compositor), "rect" or "full" (CPU compositor); "lost" or
    /// [`REFRESH_OVER_BUDGET`] when nothing was drawn and the caller should use the CPU canvas.
    pub kind: &'static str,
    /// Pixels refreshed.
    pub px: u64,
    pub composite_ms: f64,
    pub upload_ms: f64,
    /// Layer tiles the wgpu compositor uploaded.
    pub uploads: u64,
    /// How long the GPU spent executing a recent wgpu composite, once its timestamps came back
    /// (a frame or two after that refresh, so usually an earlier one than this). It carries its
    /// own pixel count and is never this refresh's unless they match. `None` when the device has
    /// no timestamp queries, on the CPU compositor, and on wasm: no number at all is reported
    /// rather than `composite_ms`, which measures encoding and submitting, not executing. It
    /// leaves out layer-tile uploads (`uploads` above counts them), so a first refresh of a
    /// document under-reports by more than the few per cent of a warm one.
    pub gpu: Option<photocraft_gpu::GpuTiming>,
    /// Why the wgpu compositor wasn't used.
    pub fallback: Option<String>,
}

/// How the app creates its wgpu device: egui's defaults clamped to the adapter's supported limits,
/// with the adapter's own texture and buffer sizes rather than egui's 8192 px cap, so large
/// documents stay on the GPU compositor.
pub fn wgpu_setup() -> egui_wgpu::WgpuSetup {
    let mut setup = egui_wgpu::WgpuSetup::without_display_handle();
    use_adapter_limits(&mut setup);
    setup
}

/// Make `setup` request the adapter's own texture and buffer size limits instead of egui's
/// default 8192 px cap (which sent every document wider or taller than 8192 px to the CPU
/// compositor). Other limits use egui's defaults (WebGL2's on GL), clamped to adapter support;
/// features stay egui's default.
pub fn use_adapter_limits(setup: &mut egui_wgpu::WgpuSetup) {
    use_adapter_limits_with(setup, |_| {});
}

/// [`use_adapter_limits`], calling `on_adapter` with the chosen adapter just before the device
/// is requested (the desktop app records it in its crash-safe startup marker).
pub fn use_adapter_limits_with(setup: &mut egui_wgpu::WgpuSetup, on_adapter: impl Fn(&wgpu::Adapter) + Send + Sync + 'static) {
    if let egui_wgpu::WgpuSetup::CreateNew(create) = setup {
        create.device_descriptor = std::sync::Arc::new(move |adapter| {
            on_adapter(adapter);
            device_descriptor(adapter)
        });
    }
}

/// How the app asks for its device: egui's defaults, the adapter's texture and buffer size
/// limits ([`device_limits`]), and timestamp queries where the adapter has them, so the canvas
/// can report how long the GPU actually spends compositing ([`photocraft_gpu::GpuTimer`]).
/// A bench or test that builds its own device should use this rather than [`device_limits`]
/// alone, or it measures a device the app never creates. (`bevel_bench`, `fx_bench` and
/// `interactive_bench` still call [`device_limits`] directly and so report no GPU time.)
pub fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
    wgpu::DeviceDescriptor {
        label: Some("photocraft wgpu device"),
        required_limits: device_limits(adapter),
        required_features: timing_features(adapter),
        ..Default::default()
    }
}

/// The timestamp-query features when the adapter supports all of them, else none: asking for a
/// feature an adapter lacks fails device creation, and a canvas without GPU timing is far better
/// than no canvas.
///
/// `PHOTOCRAFT_NO_GPU_TIMING` suppresses the request as well as the timer
/// ([`photocraft_gpu::Compositor::measure_gpu_time`]), so the variable also rescues a driver
/// that advertises the features and then fails or misbehaves on device creation — not only one
/// whose timestamps come back wrong.
pub fn timing_features(adapter: &wgpu::Adapter) -> wgpu::Features {
    let want = photocraft_gpu::timing::FEATURES;
    if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() {
        return wgpu::Features::empty();
    }
    if adapter.features().contains(want) { want } else { wgpu::Features::empty() }
}

/// egui's base limits (WebGL2's on GL), clamped to adapter support, with its maximum texture and buffer sizes.
pub fn device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits {
    device_limits_for(adapter.get_info().backend, adapter.limits())
}

fn device_limits_for(backend: wgpu::Backend, supported: wgpu::Limits) -> wgpu::Limits {
    let base = if backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() };
    let base = base.or_worse_values_from(&supported);
    wgpu::Limits { max_texture_dimension_2d: supported.max_texture_dimension_2d, max_buffer_size: supported.max_buffer_size, ..base }
}

/// Milliseconds since first call (monotonic). Always 0 on wasm, where `std::time` is unavailable.
pub fn now_ms() -> f64 {
    #[cfg(not(target_arch = "wasm32"))]
    {
        static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
        START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0
    }
    #[cfg(target_arch = "wasm32")]
    0.0
}

/// UI-thread timings (CPU side), exponentially smoothed.
#[derive(Clone, Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Perf {
    /// Average CPU time building the UI per frame (ms).
    pub ui_ms: f64,
    /// Worst UI frame of the last ~second (ms).
    pub ui_max_ms: f64,
    /// Last canvas refresh, CPU side (ms): the CPU composite on the CPU path, and on the GPU
    /// path the cost of *encoding and submitting* the composite — not of running it, which is
    /// `gpu_ms`.
    pub composite_ms: f64,
    /// Last canvas refresh: conversion + upload (ms).
    pub upload_ms: f64,
    /// Last canvas refresh kind: "full", "rect" or "none".
    pub last_refresh: &'static str,
    /// Pixels in the last refresh.
    pub last_refresh_px: u64,
    /// Whether the GPU canvas path is active.
    pub gpu: bool,
    /// Layer tiles uploaded by the last GPU composite.
    pub gpu_uploads: u64,
    /// How long the GPU spent executing a recent composite (ms), from timestamp queries read
    /// back after the fact. `None` on the CPU compositor, on a device without timestamp queries
    /// and on wasm — there is then no honest number to report, and `composite_ms` is not one.
    /// Excludes layer-tile uploads and end-of-batch work (see `photocraft_gpu::timing`), so it
    /// is a few per cent under the GPU's full share of a warm refresh and further under a cold
    /// one.
    pub gpu_ms: Option<f64>,
    /// Pixels of the refresh `gpu_ms` measured, which is a frame or two behind
    /// `last_refresh_px` and may be a different size.
    pub gpu_ms_px: u64,
    /// Why the last refresh fell back to the CPU compositor (None = GPU composited).
    pub gpu_fallback: Option<String>,
    /// Adapter, backend, driver and fallback state (Help › System Info).
    pub gpu_info: GpuInfo,
    /// GPU memory the compositor may hold for layer pages and effect maps (MB; see
    /// [`memory_budget`]).
    pub gpu_budget_mb: u64,
    /// The Memory Usage allowance and the GPU Memory preference (bytes) `gpu_budget_mb` was
    /// computed from.
    #[serde(skip)]
    pub gpu_budget_allowance: (u64, u64),
    /// The layer pages the last full refresh needed against the part of the budget they may
    /// hold; when they don't fit, edits that redraw the whole document do it on the CPU.
    pub gpu_layer_fit: Option<LayerFit>,
    /// Last command run through the app and its duration (ms).
    pub last_command: String,
    pub command_ms: f64,
    /// Most recent cost of occasional UI work (outline tracing, thumbnails, …), in ms.
    pub spans: std::collections::BTreeMap<&'static str, f64>,
    #[serde(skip)]
    max_decay: f64,
    /// Composite and upload time of this frame's canvas refreshes, in ms (the stroke trace).
    #[serde(skip)]
    pub(crate) frame_refresh_ms: f64,
}

/// What the app renders with and why (Help › System Info, Preferences › Performance, the `perf`
/// control-channel output).
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GpuInfo {
    /// Adapter name ("" before the window opens).
    pub adapter: String,
    /// wgpu backend of the window's device ("vulkan", "dx12", "metal", "gl", …).
    pub backend: String,
    /// Device type ("discreteGpu", "integratedGpu", "cpu", …).
    pub device_type: String,
    /// Driver name and version as the driver reports them.
    pub driver: String,
    /// The adapter's own memory in MB ([`video_memory`]): discrete GPUs where the platform
    /// reports it. It caps the GPU memory budgets.
    pub video_memory_mb: Option<u64>,
    /// `performance.gpuBackend` at launch.
    pub preference: String,
    /// Every graphics adapter the window could have used, by name (Preferences › Performance ›
    /// Graphics Adapter lists them). Empty in hosts that don't set it.
    pub adapters: Vec<String>,
    /// The backend startup chose ("auto", "dx12", "cpu", …, or "env" for `WGPU_BACKEND`).
    pub selected: String,
    /// Why startup didn't use the preference as is (previous start crashed, `--safe-gpu`,
    /// `WGPU_BACKEND`, Intel on Windows).
    pub fallback: Option<String>,
    /// "gpu" (wgpu canvas and compositor) or "cpu" (CPU compositor, egui textures).
    pub canvas: String,
    /// Why the GPU canvas was dropped during this session (device lost or a GPU error).
    pub lost: Option<String>,
    /// Present mode and frame latency ("fifo, latency 2"; launch overrides marked, see the
    /// app's `presentation`). Empty in hosts that don't set it.
    pub present: String,
}

impl GpuInfo {
    /// Record the adapters the instance found, without duplicates (one GPU shows up once per backend).
    pub fn set_available(&mut self, adapters: &[wgpu::Adapter]) {
        self.adapters.clear();
        for a in adapters {
            let name = a.get_info().name;
            if !name.is_empty() && !self.adapters.contains(&name) {
                self.adapters.push(name);
            }
        }
    }

    /// Fill the adapter fields from `info`.
    pub fn set_adapter(&mut self, info: &wgpu::AdapterInfo) {
        self.adapter = info.name.clone();
        self.backend = backend_name(info.backend).to_string();
        self.device_type = match info.device_type {
            wgpu::DeviceType::DiscreteGpu => "discreteGpu",
            wgpu::DeviceType::IntegratedGpu => "integratedGpu",
            wgpu::DeviceType::VirtualGpu => "virtualGpu",
            wgpu::DeviceType::Cpu => "cpu",
            wgpu::DeviceType::Other => "other",
        }
        .to_string();
        self.driver = [info.driver.as_str(), info.driver_info.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::<Vec<_>>().join(" ");
        self.video_memory_mb = video_memory(info).map(|b| b >> 20);
    }

    /// Human-readable lines for Help › System Info.
    pub fn lines(&self) -> Vec<String> {
        let or = |s: &str, d: &str| if s.is_empty() || (s == "auto" && d == "auto") { tl!(d).to_string() } else { s.to_string() };
        let mut v = vec![
            {
                let template = "Graphics adapter: {adapter}";
                crate::i18n::fmt(tl!(template), &[("adapter", &or(&self.adapter, "unknown"))])
            },
            {
                let template = "Backend: {backend} ({type})";
                crate::i18n::fmt(tl!(template), &[("backend", &or(&self.backend, "unknown")), ("type", &or(&self.device_type, "unknown type"))])
            },
            {
                let template = "Driver: {driver}";
                crate::i18n::fmt(tl!(template), &[("driver", &or(&self.driver, "unknown"))])
            },
        ];
        // The card's own memory caps the GPU budgets, so it explains a huge canvas falling back
        // to the CPU. Only discrete cards report one (integrated GPUs share system memory).
        if let Some(mb) = self.video_memory_mb {
            let template = "Graphics memory: {size}";
            v.push(crate::i18n::fmt(tl!(template), &[("size", &crate::chrome_ui::fmt_bytes(mb.saturating_mul(1 << 20)))]));
        }
        v.extend([
            {
                let template = "GPU backend preference: {backend}";
                crate::i18n::fmt(tl!(template), &[("backend", &or(&self.preference, "auto"))])
            },
            {
                let template = "Selected at launch: {backend}";
                crate::i18n::fmt(tl!(template), &[("backend", &or(&self.selected, "auto"))])
            },
            {
                let template = "Image compositor: {processor}";
                crate::i18n::fmt(tl!(template), &[("processor", if self.canvas == "gpu" { "GPU" } else { "CPU" })])
            },
            {
                let template = "Window renderer: {renderer}";
                let renderer = if self.device_type == "cpu" {
                    "Software adapter"
                } else if self.adapter.is_empty() {
                    "Unknown"
                } else {
                    "Graphics adapter"
                };
                crate::i18n::fmt(tl!(template), &[("renderer", tl!(renderer))])
            },
        ]);
        if let Some(f) = &self.fallback {
            v.push({
                let template = "Fallback: {reason}";
                crate::i18n::fmt(tl!(template), &[("reason", f)])
            });
        }
        if let Some(l) = &self.lost {
            v.push({
                let template = "This session: {reason}";
                crate::i18n::fmt(tl!(template), &[("reason", l)])
            });
        }
        v
    }
}

/// The preference name of a wgpu backend.
pub fn backend_name(b: wgpu::Backend) -> &'static str {
    match b {
        wgpu::Backend::Vulkan => "vulkan",
        wgpu::Backend::Dx12 => "dx12",
        wgpu::Backend::Metal => "metal",
        wgpu::Backend::Gl => "gl",
        wgpu::Backend::BrowserWebGpu => "webgpu",
        wgpu::Backend::Noop => "noop",
    }
}

impl Perf {
    pub fn record(&mut self, kind: &'static str, px: u64, composite_ms: f64, upload_ms: f64) {
        self.frame_refresh_ms += composite_ms + upload_ms;
        self.last_refresh = kind;
        self.last_refresh_px = px;
        self.composite_ms = composite_ms;
        self.upload_ms = upload_ms;
        if !kind.starts_with("gpu") {
            self.gpu_uploads = 0;
            // The CPU compositor did this one: there is no GPU time, and the last GPU
            // refresh's would be read as this refresh's.
            self.gpu_ms = None;
            self.gpu_ms_px = 0;
        } else {
            self.gpu_fallback = None;
        }
    }

    /// Record a canvas refresh and any GPU measurement that came back with it.
    pub fn record_refresh(&mut self, r: &Refresh) {
        self.record(r.kind, r.px, r.composite_ms, r.upload_ms);
        if let Some(t) = r.gpu {
            self.record_gpu(t);
        }
    }

    /// Record a GPU composite measurement that came back (see [`photocraft_gpu::GpuTiming`]).
    pub fn record_gpu(&mut self, t: photocraft_gpu::GpuTiming) {
        self.gpu_ms = Some(t.ms);
        self.gpu_ms_px = t.px;
    }
    pub fn span(&mut self, name: &'static str, ms: f64) {
        self.spans.insert(name, (ms * 100.0).round() / 100.0);
    }
    pub fn frame(&mut self, ms: f64) {
        self.ui_ms = if self.ui_ms == 0.0 { ms } else { self.ui_ms * 0.9 + ms * 0.1 };
        self.max_decay += 1.0;
        if ms > self.ui_max_ms || self.max_decay > 60.0 {
            self.ui_max_ms = ms;
            self.max_decay = 0.0;
        }
    }
}

/// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA8, split across threads on native.
pub fn premultiply_rgba8(px: &[[f32; 4]]) -> Vec<u8> {
    let mut out = Vec::new();
    texels_into(FORMAT, px, &mut out);
    out
}

/// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA16F (little-endian), split across
/// threads on native. Colour values above 1.0 are kept (32-bit documents); negatives and NaN
/// become 0.
pub fn premultiply_rgba16f(px: &[[f32; 4]]) -> Vec<u8> {
    let mut out = Vec::new();
    texels_into(FORMAT_HIGH, px, &mut out);
    out
}

/// Bytes per texel of a canvas texture format.
fn texel_bytes(format: wgpu::TextureFormat) -> u64 {
    if format == FORMAT_HIGH { 8 } else { 4 }
}

/// Straight-alpha f32 RGBA → premultiplied texels of `format`.
fn texels(format: wgpu::TextureFormat, px: &[[f32; 4]]) -> Vec<u8> {
    let mut out = Vec::new();
    texels_into(format, px, &mut out);
    out
}

/// [`texels`] into `out` (resized; reusing it across bands saves page-faulting a fresh buffer).
fn texels_into(format: wgpu::TextureFormat, px: &[[f32; 4]], out: &mut Vec<u8>) {
    fn rgba8(src: &[[f32; 4]], dst: &mut [u8]) {
        for (o, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) {
            let a = p[3].clamp(0.0, 1.0);
            o[0] = (p[0].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8;
            o[1] = (p[1].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8;
            o[2] = (p[2].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8;
            o[3] = (a * 255.0 + 0.5) as u8;
        }
    }
    fn rgba16f(src: &[[f32; 4]], dst: &mut [u8]) {
        for (o, p) in dst.as_chunks_mut::<8>().0.iter_mut().zip(src) {
            let a = if p[3].is_nan() { 0.0 } else { p[3].clamp(0.0, 1.0) };
            let [r, g, b, a] = [p[0].max(0.0) * a, p[1].max(0.0) * a, p[2].max(0.0) * a, a].map(|v| f32_to_f16(v).to_le_bytes());
            *o = [r[0], r[1], g[0], g[1], b[0], b[1], a[0], a[1]];
        }
    }
    let bpp = texel_bytes(format) as usize;
    let convert = if format == FORMAT_HIGH { rgba16f } else { rgba8 };
    out.clear();
    out.resize(px.len() * bpp, 0);
    #[cfg(not(target_arch = "wasm32"))]
    if px.len() > 1 << 18 {
        let threads = std::thread::available_parallelism().map_or(4, |n| n.get()).min(16);
        let chunk = px.len().div_ceil(threads);
        std::thread::scope(|s| {
            for (src, dst) in px.chunks(chunk).zip(out.chunks_mut(chunk * bpp)) {
                s.spawn(move || convert(src, dst));
            }
        });
        return;
    }
    convert(px, out);
}

/// IEEE 754 binary32 → binary16, round to nearest even; overflow saturates to the largest
/// finite half (65504) so HDR values never become infinite, NaN becomes 0. Branch-light: the
/// rounding is done with integer adds on the f32 bits (and an f32 add for subnormals).
fn f32_to_f16(v: f32) -> u16 {
    // 2^-14: the smallest normal half; below it the result is subnormal (or zero).
    const MIN_NORMAL: u32 = 113 << 23;
    // 2^16: halves overflow from here (65520 and up round to infinity; saturate instead).
    const OVERFLOW: u32 = 143 << 23;
    // Adding 0.5 (as f32) shifts a subnormal half's bits to the bottom of the mantissa.
    const DENORM_MAGIC: u32 = 126 << 23;
    let bits = v.to_bits();
    let sign = ((bits >> 16) & 0x8000) as u16;
    let a = bits & 0x7fff_ffff;
    if a > 0x7f80_0000 {
        return 0;
    }
    let h = if a >= OVERFLOW {
        0x7bff
    } else if a < MIN_NORMAL {
        (f32::from_bits(a) + f32::from_bits(DENORM_MAGIC)).to_bits().wrapping_sub(DENORM_MAGIC) as u16
    } else {
        // Rebias the exponent and round the 13 dropped mantissa bits to nearest even.
        let odd = (a >> 13) & 1;
        (((a.wrapping_add(0xc800_0fff).wrapping_add(odd)) >> 13).min(0x7bff)) as u16
    };
    sign | h
}

/// IEEE 754 binary16 → binary32.
#[cfg(not(target_arch = "wasm32"))]
fn f16_to_f32(h: u16) -> f32 {
    let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 };
    let exp = i32::from((h >> 10) & 0x1f);
    let man = f32::from(h & 0x3ff);
    sign * match exp {
        0 => man * 2f32.powi(-24),
        0x1f => {
            if man == 0.0 {
                f32::INFINITY
            } else {
                f32::NAN
            }
        }
        e => (1.0 + man / 1024.0) * 2f32.powi(e - 15),
    }
}

/// One stored texel of `format` as f32 RGBA.
#[cfg(not(target_arch = "wasm32"))]
fn texel_to_f32(format: wgpu::TextureFormat, b: &[u8]) -> [f32; 4] {
    let mut o = [0.0f32; 4];
    for (i, v) in o.iter_mut().enumerate() {
        *v = if format == FORMAT_HIGH {
            f16_to_f32(u16::from_le_bytes([b.get(i * 2).copied().unwrap_or(0), b.get(i * 2 + 1).copied().unwrap_or(0)]))
        } else {
            f32::from(b.get(i).copied().unwrap_or(0)) / 255.0
        };
    }
    o
}

// ---------------------------------------------------------------------------------------------
// GPU resources

/// The GPU memory a refresh's layer pages need against what they may hold (bytes).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LayerFit {
    /// The document refreshed.
    pub doc: u64,
    pub needed: u64,
    pub budget: u64,
}

impl LayerFit {
    pub fn fits(&self) -> bool {
        self.needed <= self.budget
    }
}

/// Floor of the compositor's memory budget: enough for a viewport's pages of a dozen layers.
pub const MIN_GPU_BUDGET: u64 = 512 << 20;

/// Why a full refresh whose layer pages don't fit [`memory_budget`] (or GPU memory) goes to the
/// CPU compositor.
pub const OVER_BUDGET: &str = photocraft_gpu::OVER_BUDGET;

/// GPU memory the wgpu compositor may hold for layer pages and effect maps.
///
/// `fixed` (Preferences › Performance › GPU Memory, bytes) sets it when it isn't 0, within
/// [`vram_share`] of a discrete GPU's own memory (`vram`, from [`video_memory`]). Otherwise it is
/// Memory Usage (`allowance`) within a quarter of physical memory (`ram`; 16 GB assumed when
/// unknown) and the VRAM share. The document's pixels and History (`pixels`) come off Memory Usage
/// unless the card's own memory is known: a discrete card doesn't hold them, while integrated and
/// software adapters (and a card whose memory can't be read) share the system's. Never below
/// [`MIN_GPU_BUDGET`]. Layers beyond it redraw full refreshes on the CPU ([`OVER_BUDGET`]).
pub fn memory_budget(allowance: u64, pixels: u64, ram: Option<u64>, vram: Option<u64>, fixed: u64) -> u64 {
    let card = vram.map_or(u64::MAX, vram_share);
    if fixed > 0 {
        return fixed.min(card).max(MIN_GPU_BUDGET);
    }
    let ram = ram.unwrap_or(16 << 30);
    let charged = if vram.is_some() { 0 } else { pixels };
    allowance.saturating_sub(charged).min(ram / 4).min(card).max(MIN_GPU_BUDGET)
}

/// The share of a discrete GPU's memory each of [`memory_budget`] and [`canvas_budget`] may
/// plan for: three eighths, so the two together leave a quarter of the card to the window's
/// swapchain, egui and other applications instead of over-committing it and letting the driver
/// page (#4536).
pub fn vram_share(vram: u64) -> u64 {
    vram / 8 * 3
}

/// Why a document whose display textures don't fit [`canvas_budget`] is drawn on the CPU canvas.
pub const OVER_CANVAS_BUDGET: &str = "the canvas exceeds the GPU texture budget; drawing it on the CPU canvas";

/// [`Refresh::kind`] when the document's display textures don't fit [`canvas_budget`]: nothing
/// was created, and the caller draws the CPU canvas instead.
pub const REFRESH_OVER_BUDGET: &str = "over-budget";

/// [`Refresh::kind`] of a CPU refresh left to the caller ([`GpuCanvas::refresh_with`]).
pub const REFRESH_DEFERRED: &str = "deferred";

/// The smallest CPU refresh (pixels) [`GpuCanvas::refresh_with`] defers: below it, the
/// synchronous composite takes a fraction of a second even with many layers.
pub const DEFER_PX: u64 = 1 << 22;

/// GPU bytes one document's display texture set (every tile and mip level) may take: a quarter
/// of physical memory (`ram`; 16 GB assumed when unknown) and at most [`vram_share`] of a
/// discrete GPU's own memory (`vram`), at least [`MIN_GPU_BUDGET`]. The set covers the whole
/// canvas at full resolution, so its size follows the declared canvas, not the layer pixels; a
/// larger canvas is drawn on the (reduced) CPU canvas instead (#2934).
pub fn canvas_budget(ram: Option<u64>, vram: Option<u64>) -> u64 {
    (ram.unwrap_or(16 << 30) / 4).min(vram.map_or(u64::MAX, vram_share)).max(MIN_GPU_BUDGET)
}

/// GPU bytes of a display texture set for a `size` canvas in `tile`-sided tiles of `bpp` bytes
/// per texel, with every mip level (what [`GpuCanvas::texture_info`] reports once it exists).
/// Closed form over the (at most four) distinct tile shapes, so any size is cheap to price.
pub fn canvas_texture_bytes(size: [u32; 2], tile: u32, bpp: u64) -> u64 {
    let tile = tile.max(1);
    // (how many tiles, their side) along one axis: whole tiles, then the remainder.
    let spans = |n: u32| [(n / tile, tile), (u32::from(!n.is_multiple_of(tile)), n % tile)];
    let mut total = 0u64;
    for (nx, w) in spans(size[0]) {
        for (ny, h) in spans(size[1]) {
            if nx == 0 || ny == 0 {
                continue;
            }
            let one = (0..mip_count(w, h)).map(|l| u64::from((w >> l).max(1)) * u64::from((h >> l).max(1)) * bpp).fold(0, u64::saturating_add);
            total = total.saturating_add(one.saturating_mul(u64::from(nx) * u64::from(ny)));
        }
    }
    total
}

/// Physical memory of this machine in bytes, if known. `PHOTOCRAFT_RAM_MB` overrides it (to
/// simulate a smaller machine).
pub fn physical_memory() -> Option<u64> {
    static RAM: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
    *RAM.get_or_init(|| {
        if let Some(mb) = std::env::var("PHOTOCRAFT_RAM_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()) {
            return mb.checked_mul(1 << 20);
        }
        detect_physical_memory()
    })
}

#[cfg(target_os = "macos")]
fn detect_physical_memory() -> Option<u64> {
    let out = std::process::Command::new("/usr/sbin/sysctl").args(["-n", "hw.memsize"]).output().ok()?;
    String::from_utf8(out.stdout).ok()?.trim().parse().ok()
}

#[cfg(target_os = "linux")]
fn detect_physical_memory() -> Option<u64> {
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
    let kb: u64 = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
    kb.checked_mul(1024)
}

#[cfg(target_os = "freebsd")]
fn detect_physical_memory() -> Option<u64> {
    let out = std::process::Command::new("/sbin/sysctl").args(["-n", "hw.physmem"]).output().ok()?;
    String::from_utf8(out.stdout).ok()?.trim().parse().ok()
}

#[cfg(windows)]
fn detect_physical_memory() -> Option<u64> {
    winsafe::GlobalMemoryStatusEx().map(|m| m.ullTotalPhys).ok().filter(|b| *b > 0)
}

#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "freebsd", windows)))]
fn detect_physical_memory() -> Option<u64> {
    None
}

/// The memory of `adapter` itself, in bytes, when it is a discrete GPU and the platform reports
/// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size on Linux. `None` for
/// integrated and software adapters, whose textures live in system memory (the RAM-based
/// budgets already cover them), and where nothing reports it. `PHOTOCRAFT_VRAM_MB` overrides it
/// for any adapter, simulating a discrete card of that size: on an integrated GPU the budget then
/// stops charging the document's pixels too, as for a real card (a development switch).
pub fn video_memory(adapter: &wgpu::AdapterInfo) -> Option<u64> {
    if let Some(mb) = std::env::var("PHOTOCRAFT_VRAM_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()) {
        return mb.checked_mul(1 << 20).filter(|b| *b > 0);
    }
    if adapter.device_type != wgpu::DeviceType::DiscreteGpu {
        return None;
    }
    // Detected once per adapter, as `physical_memory` is: on Windows each detection builds a
    // DXGI factory, and startup asks three times. Keyed by the adapter, since a GPU retry can
    // pick another one.
    /// (vendor, device) ids and the memory found for them.
    type Seen = Vec<((u32, u32), Option<u64>)>;
    static SEEN: std::sync::Mutex<Seen> = std::sync::Mutex::new(Vec::new());
    let key = (adapter.vendor, adapter.device);
    let mut seen = SEEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
    if let Some((_, bytes)) = seen.iter().find(|(k, _)| *k == key) {
        return *bytes;
    }
    let bytes = detect_video_memory(key.0, key.1).filter(|b| *b > 0);
    seen.push((key, bytes));
    bytes
}

#[cfg(windows)]
fn detect_video_memory(vendor: u32, device: u32) -> Option<u64> {
    use winsafe::prelude::*;
    let factory = winsafe::CreateDXGIFactory1().ok()?;
    factory
        .EnumAdapters1()
        .filter_map(|a| a.ok()?.GetDesc1().ok())
        .find(|d| d.VendorId == vendor && d.DeviceId == device)
        .and_then(|d| u64::try_from(d.DedicatedVideoMemory).ok())
}

#[cfg(target_os = "linux")]
fn detect_video_memory(vendor: u32, device: u32) -> Option<u64> {
    drm_video_memory(std::path::Path::new("/sys/class/drm"), vendor, device)
}

/// amdgpu's VRAM size (`<card>/device/mem_info_vram_total`, bytes) of the card under `drm` (the
/// sysfs `/sys/class/drm` folder) whose PCI `vendor` and `device` ids (hex files beside it) match.
#[cfg(any(target_os = "linux", test))]
fn drm_video_memory(drm: &std::path::Path, vendor: u32, device: u32) -> Option<u64> {
    let hex = |p: std::path::PathBuf| u32::from_str_radix(std::fs::read_to_string(p).ok()?.trim().trim_start_matches("0x"), 16).ok();
    std::fs::read_dir(drm).ok()?.flatten().find_map(|card| {
        let dev = card.path().join("device");
        if hex(dev.join("vendor"))? != vendor || hex(dev.join("device"))? != device {
            return None;
        }
        std::fs::read_to_string(dev.join("mem_info_vram_total")).ok()?.trim().parse().ok()
    })
}

#[cfg(not(any(target_os = "linux", windows)))]
fn detect_video_memory(_vendor: u32, _device: u32) -> Option<u64> {
    None
}

struct Resources {
    view_bgl: wgpu::BindGroupLayout,
    tile_bgl: wgpu::BindGroupLayout,
    shadow_pipeline: wgpu::RenderPipeline,
    tile_pipeline: wgpu::RenderPipeline,
    sampler: wgpu::Sampler,
    mip_bgl: wgpu::BindGroupLayout,
    mip_pipeline: wgpu::RenderPipeline,
    /// `mip_pipeline` and `encode_pipeline` for `Rgba16Float` tiles (when the adapter supports them).
    mip_pipeline_high: Option<wgpu::RenderPipeline>,
    encode_pipeline_high: Option<wgpu::RenderPipeline>,
    mip_sampler: wgpu::Sampler,
    docs: HashMap<u64, DocTextures>,
    views: HashMap<u64, ViewGpu>,
    out_linear: bool,
    /// Build each mip level in a scratch texture and copy it back instead of rendering into
    /// the level directly (see [`separate_mip_targets`]).
    separate_mip_targets: bool,
    /// The wgpu layer compositor (created on first use).
    compositor: Option<photocraft_gpu::Compositor>,
    /// Why the wgpu compositor couldn't be created (then the CPU compositor is used).
    compositor_failed: Option<photocraft_gpu::Unsupported>,
    /// The device's health: the paint callback issues no GPU work once it's lost.
    health: photocraft_gpu::DeviceHealth,
    /// GPU memory the compositor may hold (`None`: its default), and the document area the
    /// view shows; applied before every composite.
    compositor_budget: Option<u64>,
    /// The layer pages the last full (or large) refresh needed and the budget they had to fit
    /// (bytes): when they don't fit, full refreshes go to the CPU ([`OVER_BUDGET`]).
    layer_fit: Option<LayerFit>,
    compositor_cache_budget: Option<u64>,
    compositor_focus: Option<photocraft_geom::Rect>,
    /// GPU bytes one document's display texture set may take (see [`canvas_budget`]).
    canvas_budget: std::sync::Arc<std::sync::atomic::AtomicU64>,
    encode_bgl: wgpu::BindGroupLayout,
    encode_pipeline: wgpu::RenderPipeline,
    lut_bgl: wgpu::BindGroupLayout,
    /// Display LUTs per (document, display) (monitor profile, Proof Colors / Gamut Warning);
    /// `identity_lut` otherwise.
    luts: HashMap<(u64, u32), wgpu::BindGroup>,
    /// Signatures belong to their renderer resources, including identity transforms (mode 0).
    display_lut_signatures: HashMap<(u64, u32), (u64, u8)>,
    identity_lut: wgpu::BindGroup,
    /// Transparency checkerboard and gamut warning colours (Preferences › Transparency & Gamut).
    style: CanvasStyle,
}

/// Canvas colours from Preferences › Transparency & Gamut.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CanvasStyle {
    /// Checker square side in points (0 = no checkerboard: transparency shows white).
    pub checker_square: f32,
    pub checker_light: [f32; 3],
    pub checker_dark: [f32; 3],
    pub gamut_color: [f32; 3],
    /// Gamut warning opacity 0..1.
    pub gamut_opacity: f32,
}

impl Default for CanvasStyle {
    fn default() -> Self {
        Self { checker_square: 8.0, checker_light: [1.0; 3], checker_dark: [0.8; 3], gamut_color: [0.5; 3], gamut_opacity: 1.0 }
    }
}

/// A display transform: either the existing 3D LUT or separate full-float shapers and
/// matrix. Pack curves into short rows to stay within WebGL2's texture-size limits.
fn lut_bind_group(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    bgl: &wgpu::BindGroupLayout,
    size: u32,
    bytes: &[u8],
    shaper: Option<&photocraft_cms::GpuMatrixShaper>,
) -> wgpu::BindGroup {
    let extent = wgpu::Extent3d { width: size, height: size, depth_or_array_layers: size };
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("pc_display_lut"),
        size: extent,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D3,
        format: FORMAT,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
        bytes,
        wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size * 4), rows_per_image: Some(size) },
        extent,
    );
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    let (width, height, curves, matrix) = if let Some(s) = shaper {
        let width = 1024usize;
        let count = s.input_table().len() + s.output_table().len();
        let height = count.div_ceil(width);
        let mut curves = Vec::with_capacity(width * height * 16);
        for value in s.input_table().iter().chain(s.output_table()).flatten() {
            curves.extend_from_slice(&value.to_le_bytes());
        }
        curves.resize(width * height * 16, 0);
        (width as u32, height as u32, curves, s.matrix_rows())
    } else {
        (1, 1, vec![0; 16], [[0.0; 4]; 3])
    };
    let extent = wgpu::Extent3d { width, height, depth_or_array_layers: 1 };
    let curves_texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("pc_display_shapers"),
        size: extent,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        // textureLoad + explicit interpolation needs no optional float-filtering feature.
        format: wgpu::TextureFormat::Rgba32Float,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo { texture: &curves_texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
        &curves,
        wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width * 16), rows_per_image: Some(height) },
        extent,
    );
    let curves_view = curves_texture.create_view(&wgpu::TextureViewDescriptor::default());
    let matrix_bytes: Vec<u8> = matrix.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
    let matrix_buffer = init_buffer(device, "pc_display_matrix", &matrix_bytes, wgpu::BufferUsages::UNIFORM);
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("pc_display_lut"),
        layout: bgl,
        entries: &[
            wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) },
            wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&curves_view) },
            wgpu::BindGroupEntry { binding: 2, resource: matrix_buffer.as_entire_binding() },
        ],
    })
}

/// The 2³ identity LUT (unused unless a document has none and `display` is set).
fn identity_lut_bytes() -> Vec<u8> {
    (0..8).flat_map(|i| [if i & 1 != 0 { 255 } else { 0 }, if i & 2 != 0 { 255 } else { 0 }, if i & 4 != 0 { 255 } else { 0 }, 0]).collect()
}

struct ViewGpu {
    buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    frame_data: [f32; VIEW_FLOATS],
}

struct DocTextures {
    size: [u32; 2],
    format: wgpu::TextureFormat,
    tiles: Vec<Tile>,
}

struct Tile {
    /// Document-pixel rect: x, y, w, h.
    rect: [u32; 4],
    texture: wgpu::Texture,
    levels: Vec<wgpu::TextureView>,
    bind_group: wgpu::BindGroup,
    _uniform: wgpu::Buffer,
}

fn uniform_entry(binding: u32, size: u64, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: vis,
        ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: NonZeroU64::new(size) },
        count: None,
    }
}
fn texture_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Texture {
            multisampled: false,
            sample_type: wgpu::TextureSampleType::Float { filterable: true },
            view_dimension: wgpu::TextureViewDimension::D2,
        },
        count: None,
    }
}
fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
        count: None,
    }
}

fn f32_bytes(v: &[f32]) -> Vec<u8> {
    v.iter().flat_map(|f| f.to_ne_bytes()).collect()
}

fn pipeline(
    device: &wgpu::Device,
    label: &str,
    layout: &wgpu::PipelineLayout,
    module: &wgpu::ShaderModule,
    (vs, fs): (&str, &str),
    format: wgpu::TextureFormat,
    blend: Option<wgpu::BlendState>,
) -> wgpu::RenderPipeline {
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some(label),
        layout: Some(layout),
        vertex: wgpu::VertexState { module, entry_point: Some(vs), buffers: &[], compilation_options: Default::default() },
        primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
        depth_stencil: None,
        multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false },
        fragment: Some(wgpu::FragmentState {
            module,
            entry_point: Some(fs),
            targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })],
            compilation_options: Default::default(),
        }),
        multiview_mask: None,
        cache: None,
    })
}

impl Resources {
    fn new(device: &wgpu::Device, queue: &wgpu::Queue, target: wgpu::TextureFormat, high: bool) -> Self {
        let module =
            device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_canvas"), source: wgpu::ShaderSource::Wgsl(CANVAS_WGSL.into()) });
        let vis = wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT;
        let view_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("pc_canvas_view"),
            entries: &[uniform_entry(0, VIEW_UNIFORM_SIZE, vis), sampler_entry(1)],
        });
        let tile_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("pc_canvas_tile"),
            entries: &[texture_entry(0), uniform_entry(1, TILE_UNIFORM_SIZE, vis)],
        });
        let lut_entry = wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                multisampled: false,
                sample_type: wgpu::TextureSampleType::Float { filterable: true },
                view_dimension: wgpu::TextureViewDimension::D3,
            },
            count: None,
        };
        let curves_entry = wgpu::BindGroupLayoutEntry {
            binding: 1,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                multisampled: false,
                sample_type: wgpu::TextureSampleType::Float { filterable: false },
                view_dimension: wgpu::TextureViewDimension::D2,
            },
            count: None,
        };
        let lut_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("pc_display_lut"),
            entries: &[lut_entry, curves_entry, uniform_entry(2, 48, wgpu::ShaderStages::FRAGMENT)],
        });
        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("pc_canvas"),
            bind_group_layouts: &[Some(&view_bgl), Some(&tile_bgl), Some(&lut_bgl)],
            immediate_size: 0,
        });
        let shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("pc_canvas_shadow"),
            bind_group_layouts: &[Some(&view_bgl)],
            immediate_size: 0,
        });
        // Premultiplied "over", with egui's alpha rule (keeps a transparent window's alpha sane).
        let blend = wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::OneMinusDstAlpha,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
        };
        let shadow_pipeline = pipeline(device, "pc_canvas_shadow", &shadow_layout, &module, ("vs_shadow", "fs_shadow"), target, Some(blend));
        let tile_pipeline = pipeline(device, "pc_canvas_tile", &layout, &module, ("vs_tile", "fs_tile"), target, Some(blend));
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("pc_canvas_trilinear"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Linear,
            ..Default::default()
        });

        let mip_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_mip"), source: wgpu::ShaderSource::Wgsl(MIP_WGSL.into()) });
        let mip_bgl =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_mip"), entries: &[texture_entry(0), sampler_entry(1)] });
        let mip_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_mip"), bind_group_layouts: &[Some(&mip_bgl)], immediate_size: 0 });
        let mip_pipeline = pipeline(device, "pc_mip", &mip_layout, &mip_module, ("vs", "fs"), FORMAT, None);
        let mip_pipeline_high = high.then(|| pipeline(device, "pc_mip_16f", &mip_layout, &mip_module, ("vs", "fs"), FORMAT_HIGH, None));
        let mip_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("pc_mip"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });
        // Compositor output (straight RGBA32F chunk) -> premultiplied RGBA8 display tile.
        let encode_module =
            device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_encode"), source: wgpu::ShaderSource::Wgsl(ENCODE_WGSL.into()) });
        let unfilterable = wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                multisampled: false,
                sample_type: wgpu::TextureSampleType::Float { filterable: false },
                view_dimension: wgpu::TextureViewDimension::D2,
            },
            count: None,
        };
        let encode_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("pc_encode"),
            entries: &[unfilterable, uniform_entry(1, 16, wgpu::ShaderStages::FRAGMENT)],
        });
        let encode_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("pc_encode"),
            bind_group_layouts: &[Some(&encode_bgl)],
            immediate_size: 0,
        });
        let encode_pipeline = pipeline(device, "pc_encode", &encode_layout, &encode_module, ("vs", "fs"), FORMAT, None);
        let encode_pipeline_high = high.then(|| pipeline(device, "pc_encode_16f", &encode_layout, &encode_module, ("vs", "fs"), FORMAT_HIGH, None));
        let identity_lut = lut_bind_group(device, queue, &lut_bgl, 2, &identity_lut_bytes(), None);
        Self {
            lut_bgl,
            luts: HashMap::new(),
            display_lut_signatures: HashMap::new(),
            identity_lut,
            style: CanvasStyle::default(),
            view_bgl,
            tile_bgl,
            shadow_pipeline,
            tile_pipeline,
            sampler,
            mip_bgl,
            mip_pipeline,
            mip_pipeline_high,
            encode_pipeline_high,
            mip_sampler,
            docs: HashMap::new(),
            views: HashMap::new(),
            out_linear: target.is_srgb(),
            separate_mip_targets: false,
            compositor: None,
            compositor_failed: None,
            health: photocraft_gpu::DeviceHealth::new(),
            compositor_budget: None,
            layer_fit: None,
            compositor_cache_budget: None,
            compositor_focus: None,
            canvas_budget: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(canvas_budget(physical_memory(), None))),
            encode_bgl,
            encode_pipeline,
        }
    }

    /// The pipeline encoding compositor output into a `format` tile.
    fn encode_pipeline(&self, format: wgpu::TextureFormat) -> Option<&wgpu::RenderPipeline> {
        if format == FORMAT_HIGH { self.encode_pipeline_high.as_ref() } else { Some(&self.encode_pipeline) }
    }

    /// The mip-chain pipeline for `format` tiles.
    fn mip_pipeline(&self, format: wgpu::TextureFormat) -> Option<&wgpu::RenderPipeline> {
        if format == FORMAT_HIGH { self.mip_pipeline_high.as_ref() } else { Some(&self.mip_pipeline) }
    }
}

fn mip_count(w: u32, h: u32) -> u32 {
    32 - w.max(h).max(1).leading_zeros()
}

/// The rect (x0, y0, x1, y1) of a `lw`×`lh` mip level to redraw when `prev` changed in the level
/// above: that damage halved and padded by one texel for odd-size rounding, or the whole level
/// when it is at most [`WHOLE_MIP_SIDE`] on either side. On AMD's Vulkan driver a pass that draws
/// only part of a level of 64 px or less corrupts texels outside its scissor, at the level's
/// top-left (#6418: RX 6900 XT, driver 26.8.1; DX12 on the same card is fine). Such a level costs
/// next to nothing to redraw, so this holds for every adapter; the levels after it are smaller
/// still, so the rest of the chain is redrawn whole too.
fn mip_damage([x0, y0, x1, y1]: [u32; 4], lw: u32, lh: u32) -> [u32; 4] {
    if lw.max(lh) <= WHOLE_MIP_SIDE {
        return [0, 0, lw, lh];
    }
    [(x0 / 2).saturating_sub(1), (y0 / 2).saturating_sub(1), (x1.div_ceil(2) + 1).min(lw), (y1.div_ceil(2) + 1).min(lh)]
}

/// A buffer holding `contents`, like `DeviceExt::create_buffer_init` but without its panic when
/// the device was lost (an invalid buffer has no mapped range): the buffer is then just invalid.
fn init_buffer(device: &wgpu::Device, label: &str, contents: &[u8], usage: wgpu::BufferUsages) -> wgpu::Buffer {
    let size = (contents.len() as u64).next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT).max(wgpu::COPY_BUFFER_ALIGNMENT);
    let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: true });
    if let Ok(mut view) = buffer.slice(..).get_mapped_range_mut()
        && view.len() >= contents.len()
    {
        view.slice(..contents.len()).copy_from_slice(contents);
    }
    buffer.unmap();
    buffer
}

impl DocTextures {
    /// The texture set for a `size` canvas, or `None` (nothing created) when it doesn't fit
    /// the canvas budget or the GPU's memory. A set the GPU can't hold (a 3 GP canvas is 16 GB
    /// of textures, #4017) lowers the budget below it, so that canvas and larger ones are drawn
    /// on the CPU canvas instead of the out-of-memory error disabling the GPU for the session.
    fn new(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Option<Self> {
        let bytes = canvas_texture_bytes(size, tile, texel_bytes(format));
        if bytes > res.canvas_budget.load(Ordering::Relaxed) {
            return None;
        }
        let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
        let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
        let set = Self::create(device, res, size, tile, format);
        // Native wgpu reports these synchronously; where they arrive later (WebGPU) none is seen.
        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
        let mut error = None;
        for pop in [memory.pop(), validation.pop()] {
            if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) {
                error.get_or_insert(e);
            }
        }
        if let Some(e) = error {
            log::warn!("{} MB of canvas textures failed ({e}); larger canvases are drawn on the CPU", bytes >> 20);
            res.canvas_budget.fetch_min(bytes.saturating_sub(1), Ordering::Relaxed);
            return None;
        }
        Some(set)
    }

    fn create(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Self {
        let mut tiles = Vec::new();
        for ty in (0..size[1]).step_by(tile as usize) {
            for tx in (0..size[0]).step_by(tile as usize) {
                let (w, h) = (tile.min(size[0] - tx), tile.min(size[1] - ty));
                let levels_n = mip_count(w, h);
                let texture = device.create_texture(&wgpu::TextureDescriptor {
                    label: Some("pc_canvas_tile"),
                    size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
                    mip_level_count: levels_n,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format,
                    usage: wgpu::TextureUsages::TEXTURE_BINDING
                        | wgpu::TextureUsages::COPY_DST
                        | wgpu::TextureUsages::COPY_SRC
                        | wgpu::TextureUsages::RENDER_ATTACHMENT,
                    view_formats: &[],
                });
                let levels = (0..levels_n)
                    .map(|l| texture.create_view(&wgpu::TextureViewDescriptor { base_mip_level: l, mip_level_count: Some(1), ..Default::default() }))
                    .collect();
                let full = texture.create_view(&wgpu::TextureViewDescriptor::default());
                let uniform = init_buffer(device, "pc_canvas_tile", &f32_bytes(&[tx as f32, ty as f32, w as f32, h as f32]), wgpu::BufferUsages::UNIFORM);
                let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("pc_canvas_tile"),
                    layout: &res.tile_bgl,
                    entries: &[
                        wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&full) },
                        wgpu::BindGroupEntry { binding: 1, resource: uniform.as_entire_binding() },
                    ],
                });
                tiles.push(Tile { rect: [tx, ty, w, h], texture, levels, bind_group, _uniform: uniform });
            }
        }
        Self { size, format, tiles }
    }

    /// Write `size` pixels at document `origin` from `texels` (in the texture format, row stride
    /// `stride` pixels) into every overlapping tile's level 0.
    fn write(&self, queue: &wgpu::Queue, origin: [u32; 2], size: [u32; 2], stride: u32, texels: &[u8]) {
        let bpp = texel_bytes(self.format);
        let (x0, y0, x1, y1) = (origin[0], origin[1], origin[0] + size[0], origin[1] + size[1]);
        for t in &self.tiles {
            let [tx, ty, tw, th] = t.rect;
            let (ix0, iy0, ix1, iy1) = (x0.max(tx), y0.max(ty), x1.min(tx + tw), y1.min(ty + th));
            if ix0 >= ix1 || iy0 >= iy1 {
                continue;
            }
            let offset = ((iy0 - y0) as u64 * stride as u64 + (ix0 - x0) as u64) * bpp;
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &t.texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d { x: ix0 - tx, y: iy0 - ty, z: 0 },
                    aspect: wgpu::TextureAspect::All,
                },
                texels,
                wgpu::TexelCopyBufferLayout { offset, bytes_per_row: Some(stride * bpp as u32), rows_per_image: Some(iy1 - iy0) },
                wgpu::Extent3d { width: ix1 - ix0, height: iy1 - iy0, depth_or_array_layers: 1 },
            );
        }
    }

    /// Rebuild the mip chain inside document rect `r` (x0, y0, x1, y1) with 2×2 box filtering.
    fn regenerate_mips(&self, device: &wgpu::Device, queue: &wgpu::Queue, res: &Resources, r: [u32; 4]) {
        let Some(mip_pipeline) = res.mip_pipeline(self.format) else { return };
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_mips") });
        for t in &self.tiles {
            let [tx, ty, tw, th] = t.rect;
            let (mut x0, mut y0, mut x1, mut y1) = (r[0].max(tx), r[1].max(ty), r[2].min(tx + tw), r[3].min(ty + th));
            if x0 >= x1 || y0 >= y1 {
                continue;
            }
            (x0, y0, x1, y1) = (x0 - tx, y0 - ty, x1 - tx, y1 - ty);
            for level in 1..t.levels.len() {
                let (lw, lh) = ((tw >> level).max(1), (th >> level).max(1));
                [x0, y0, x1, y1] = mip_damage([x0, y0, x1, y1], lw, lh);
                let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("pc_mip"),
                    layout: &res.mip_bgl,
                    entries: &[
                        wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&t.levels[level - 1]) },
                        wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&res.mip_sampler) },
                    ],
                });
                // Keep the sampled source and render attachment in separate resources on Intel
                // DX12 adapters ([`separate_mip_targets`]): some of their drivers corrupt reduced
                // previews when both are mip levels of the same texture, even though the
                // subresources do not overlap. Elsewhere render straight into the level, which
                // spares a scratch texture and a copy per level on every edit.
                let scratch = res.separate_mip_targets.then(|| {
                    let scratch = device.create_texture(&wgpu::TextureDescriptor {
                        label: Some("pc_mip_scratch"),
                        size: wgpu::Extent3d { width: lw, height: lh, depth_or_array_layers: 1 },
                        mip_level_count: 1,
                        sample_count: 1,
                        dimension: wgpu::TextureDimension::D2,
                        format: self.format,
                        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
                        view_formats: &[],
                    });
                    let view = scratch.create_view(&Default::default());
                    (scratch, view)
                });
                let (target, load) = match &scratch {
                    Some((_, view)) => (view, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)),
                    None => (&t.levels[level], wgpu::LoadOp::Load),
                };
                let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("pc_mip"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: target,
                        resolve_target: None,
                        depth_slice: None,
                        ops: wgpu::Operations { load, store: wgpu::StoreOp::Store },
                    })],
                    depth_stencil_attachment: None,
                    timestamp_writes: None,
                    occlusion_query_set: None,
                    multiview_mask: None,
                });
                pass.set_pipeline(mip_pipeline);
                pass.set_bind_group(0, &bg, &[]);
                pass.set_scissor_rect(x0, y0, x1 - x0, y1 - y0);
                pass.draw(0..3, 0..1);
                drop(pass);
                if let Some((scratch, _)) = &scratch {
                    let origin = wgpu::Origin3d { x: x0, y: y0, z: 0 };
                    encoder.copy_texture_to_texture(
                        wgpu::TexelCopyTextureInfo { texture: scratch, mip_level: 0, origin, aspect: wgpu::TextureAspect::All },
                        wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: level as u32, origin, aspect: wgpu::TextureAspect::All },
                        wgpu::Extent3d { width: x1 - x0, height: y1 - y0, depth_or_array_layers: 1 },
                    );
                }
            }
        }
        queue.submit([encoder.finish()]);
    }
}

// ---------------------------------------------------------------------------------------------
// Per-frame callback

struct CanvasCallback {
    rect: egui::Rect,
    params: ViewParams,
}

/// Sampling mode: 0 trilinear, 1 bilinear, 2 anti-aliased nearest.
fn filter_mode(scale: f32) -> (f32, f32) {
    if scale < 0.999 {
        (0.0, (-scale.log2()).max(0.0))
    } else if (scale - scale.round()).abs() < 1e-3 || scale >= 2.0 {
        (2.0, 0.0)
    } else {
        (1.0, 0.0)
    }
}

fn map_doc_px(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, x: f32, y: f32) -> [f32; 2] {
    let dx = x - center[0];
    let dy = y - center[1];
    let rx = dx * cos - dy * sin;
    let ry = dx * sin + dy * cos;
    [origin[0] + center[0] * scale + rx * scale, origin[1] + center[1] * scale + ry * scale]
}

fn tile_screen_aabb(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, tile: [f32; 4]) -> (f32, f32, f32, f32) {
    let [tx, ty, tw, th] = tile;
    if sin.abs() < 1e-8 && (cos - 1.0).abs() < 1e-8 {
        let x0 = origin[0] + tx * scale;
        let y0 = origin[1] + ty * scale;
        return (x0, y0, x0 + tw * scale, y0 + th * scale);
    }
    let pts = [
        map_doc_px(origin, scale, center, cos, sin, tx, ty),
        map_doc_px(origin, scale, center, cos, sin, tx + tw, ty),
        map_doc_px(origin, scale, center, cos, sin, tx + tw, ty + th),
        map_doc_px(origin, scale, center, cos, sin, tx, ty + th),
    ];
    let mut x0 = pts[0][0];
    let mut y0 = pts[0][1];
    let mut x1 = x0;
    let mut y1 = y0;
    for p in pts {
        x0 = x0.min(p[0]);
        y0 = y0.min(p[1]);
        x1 = x1.max(p[0]);
        y1 = y1.max(p[1]);
    }
    (x0, y0, x1, y1)
}

impl CanvasCallback {
    /// Screen-pixel origin of document (0, 0) (snapped to whole pixels) and device px per doc px.
    fn placement(&self, ppp: f32) -> ([f32; 2], f32) {
        let p = &self.params;
        let scale = p.zoom * ppp;
        let c = self.rect.center();
        let ox = (c.x * ppp - p.center[0] * scale).round();
        let oy = (c.y * ppp - p.center[1] * scale).round();
        ([ox, oy], scale)
    }

    fn uniforms(&self, screen: [u32; 2], ppp: f32, out_linear: bool, style: &CanvasStyle) -> [f32; VIEW_FLOATS] {
        let p = &self.params;
        let (origin, scale) = self.placement(ppp);
        let (mode, lod) = filter_mode(scale);
        // The pixel grid shows above 500% (the constants are shared with the CPU path,
        // pixel_grid.rs). `p.zoom` is screen points per document pixel; the shared threshold is
        // in device pixels, so scale by the display's pixels per point.
        let grid = if p.pixel_grid && crate::pixel_grid::shows_at(p.zoom * ppp) { crate::pixel_grid::STRENGTH } else { 0.0 };
        let square = if style.checker_square > 0.0 { (style.checker_square * ppp).round().max(1.0) } else { 0.0 };
        let (l, d, g) = (style.checker_light, style.checker_dark, style.gamut_color);
        // 32-bit preview: linear-light gain 2^exposure (0 = off) and 1 / gamma.
        let (gain, inv_gamma) = match p.hdr {
            Some([e, gm]) if e.is_finite() && gm.is_finite() && gm > 0.0 => (2f32.powf(e.clamp(-20.0, 20.0)), 1.0 / gm.max(0.01)),
            _ => (0.0, 1.0),
        };
        [
            screen[0] as f32,
            screen[1] as f32,
            scale,
            ppp,
            origin[0],
            origin[1],
            p.doc_size[0] as f32,
            p.doc_size[1] as f32,
            mode,
            lod,
            grid,
            square,
            if p.offset[0].is_finite() { p.offset[0] } else { 0.0 },
            if p.offset[1].is_finite() { p.offset[1] } else { 0.0 },
            p.display as f32,
            if out_linear { 1.0 } else { 0.0 },
            l[0],
            l[1],
            l[2],
            style.gamut_opacity,
            d[0],
            d[1],
            d[2],
            gain,
            g[0],
            g[1],
            g[2],
            inv_gamma,
            {
                let r = if p.rotation.is_finite() { p.rotation } else { 0.0 };
                if r.abs() < 1e-8 { 1.0 } else { r.cos() }
            },
            {
                let r = if p.rotation.is_finite() { p.rotation } else { 0.0 };
                if r.abs() < 1e-8 { 0.0 } else { r.sin() }
            },
            p.center[0],
            p.center[1],
        ]
    }
}

impl CallbackTrait for CanvasCallback {
    fn prepare(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        screen: &ScreenDescriptor,
        _encoder: &mut wgpu::CommandEncoder,
        resources: &mut CallbackResources,
    ) -> Vec<wgpu::CommandBuffer> {
        let Some(res) = resources.get_mut::<Resources>() else { return Vec::new() };
        if !res.health.is_ok() {
            return Vec::new();
        }
        let data = self.uniforms(screen.size_in_pixels, screen.pixels_per_point, res.out_linear, &res.style);
        let (bgl, sampler) = (&res.view_bgl, &res.sampler);
        let v = res.views.entry(self.params.view_key).or_insert_with(|| {
            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("pc_canvas_view"),
                size: VIEW_UNIFORM_SIZE,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("pc_canvas_view"),
                layout: bgl,
                entries: &[
                    wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() },
                    wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) },
                ],
            });
            ViewGpu { buffer, bind_group, frame_data: [f32::NAN; VIEW_FLOATS] }
        });
        if v.frame_data != data {
            queue.write_buffer(&v.buffer, 0, &f32_bytes(&data));
            v.frame_data = data;
        }
        Vec::new()
    }

    fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, resources: &CallbackResources) {
        let Some(res) = resources.get::<Resources>() else { return };
        if !res.health.is_ok() {
            return;
        }
        let Some(view) = res.views.get(&self.params.view_key) else { return };
        let [sw, sh] = info.screen_size_px;
        let clip = info.clip_rect_in_pixels();
        if clip.width_px <= 0 || clip.height_px <= 0 || sw == 0 || sh == 0 {
            return;
        }
        // Work in whole-screen pixel coordinates; the scissor does the clipping.
        pass.set_viewport(0.0, 0.0, sw as f32, sh as f32, 0.0, 1.0);
        pass.set_scissor_rect(clip.left_px.max(0) as u32, clip.top_px.max(0) as u32, clip.width_px as u32, clip.height_px as u32);
        pass.set_bind_group(0, &view.bind_group, &[]);
        if self.params.shadow {
            pass.set_pipeline(&res.shadow_pipeline);
            pass.draw(0..6, 0..1);
        }
        let Some(doc) = res.docs.get(&self.params.doc) else { return };
        if doc.size != self.params.doc_size {
            return;
        }
        let (origin, scale) = self.placement(info.pixels_per_point);
        let (cx0, cy0) = (clip.left_px as f32, clip.top_px as f32);
        let (cx1, cy1) = (cx0 + clip.width_px as f32, cy0 + clip.height_px as f32);
        let rot = if self.params.rotation.is_finite() { self.params.rotation } else { 0.0 };
        let (cos, sin) = if rot.abs() < 1e-8 { (1.0, 0.0) } else { (rot.cos(), rot.sin()) };
        let cen = self.params.center;
        let [ox, oy] = self.params.offset.map(|v| if v.is_finite() { v } else { 0.0 });
        pass.set_pipeline(&res.tile_pipeline);
        pass.set_bind_group(2, res.luts.get(&(self.params.doc, self.params.output)).unwrap_or(&res.identity_lut), &[]);
        for t in &doc.tiles {
            let [tx, ty, tw, th] = t.rect.map(|v| v as f32);
            let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, cen, cos, sin, [tx + ox, ty + oy, tw, th]);
            if x1 < cx0 || y1 < cy0 || x0 > cx1 || y0 > cy1 {
                continue;
            }
            pass.set_bind_group(1, &t.bind_group, &[]);
            pass.draw(0..6, 0..1);
        }
    }
}

const CANVAS_WGSL: &str = r#"
struct View {
    a: vec4<f32>, // screen_w, screen_h, scale (device px per doc px), pixels_per_point
    b: vec4<f32>, // doc origin x, y (device px), doc w, h (doc px)
    c: vec4<f32>, // filter mode, lod, grid alpha, checker square (device px)
    d: vec4<f32>, // pattern preview offset x, y (doc px), display (0 none, 1 LUT, 2 LUT + gamut, 3 matrix/shaper), output linear
    e: vec4<f32>, // checker light rgb, gamut warning opacity
    f: vec4<f32>, // checker dark rgb, 32-bit preview gain (2^exposure; 0 = off)
    g: vec4<f32>, // gamut warning rgb, 32-bit preview 1 / gamma
    h: vec4<f32>, // cos, sin, center_doc_x, center_doc_y
};
struct Tile { r: vec4<f32> }; // x, y, w, h in doc px

@group(0) @binding(0) var<uniform> view: View;
@group(0) @binding(1) var samp: sampler;
@group(1) @binding(0) var tex: texture_2d<f32>;
@group(1) @binding(1) var<uniform> tile: Tile;
@group(2) @binding(0) var lut: texture_3d<f32>;
@group(2) @binding(1) var display_curves: texture_2d<f32>;
struct DisplayMatrix { r: vec4<f32>, g: vec4<f32>, b: vec4<f32> };
@group(2) @binding(2) var<uniform> display_matrix: DisplayMatrix;

fn curve_entry(index: u32) -> vec3<f32> {
    let width = textureDimensions(display_curves).x;
    return textureLoad(display_curves, vec2<i32>(i32(index % width), i32(index / width)), 0).rgb;
}

fn display_curve(c: vec3<f32>, offset: u32, intervals: f32) -> vec3<f32> {
    let p = clamp(c, vec3(0.0), vec3(1.0)) * intervals;
    let lo = vec3<u32>(floor(p));
    let hi = min(lo + vec3(1u), vec3(u32(intervals)));
    let f = fract(p);
    return vec3(
        mix(curve_entry(offset + lo.r).r, curve_entry(offset + hi.r).r, f.r),
        mix(curve_entry(offset + lo.g).g, curve_entry(offset + hi.g).g, f.g),
        mix(curve_entry(offset + lo.b).b, curve_entry(offset + hi.b).b, f.b)
    );
}

fn matrix_display(c: vec3<f32>) -> vec3<f32> {
    // Layout matches cms::GpuMatrixShaper: 4097 input entries, then 4096 inverse-curve
    // entries indexed by the fourth root. This preserves near-black precision without
    // interpolating across clipped corners of a coarse RGB cube.
    let v = vec4(display_curve(c, 0u, 4096.0), 1.0);
    let linear = vec3(dot(display_matrix.r, v), dot(display_matrix.g, v), dot(display_matrix.b, v));
    let u = sqrt(sqrt(clamp(linear, vec3(0.0), vec3(1.0))));
    return display_curve(u, 4097u, 4095.0);
}

struct VOut { @builtin(position) pos: vec4<f32> };

fn corner(i: u32) -> vec2<f32> {
    var c = array<vec2<f32>, 6>(vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0));
    return c[i];
}

fn px_to_clip(p: vec2<f32>) -> vec4<f32> {
    let n = p / view.a.xy * 2.0 - 1.0;
    return vec4(n.x, -n.y, 0.0, 1.0);
}

fn screen_center() -> vec2<f32> {
    return view.b.xy + view.h.zw * view.a.z;
}

fn doc_to_px(d: vec2<f32>) -> vec2<f32> {
    let cs = view.h.xy;
    let q = d - view.h.zw;
    let r = vec2(q.x * cs.x - q.y * cs.y, q.x * cs.y + q.y * cs.x);
    return screen_center() + r * view.a.z;
}

fn px_to_doc(p: vec2<f32>) -> vec2<f32> {
    let cs = view.h.xy;
    let q = (p - screen_center()) / view.a.z;
    return vec2(q.x * cs.x + q.y * cs.y, -q.x * cs.y + q.y * cs.x) + view.h.zw;
}

fn doc_min() -> vec2<f32> { return view.b.xy; }
fn doc_max() -> vec2<f32> { return view.b.xy + view.b.zw * view.a.z; }

fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
    let lo = c / 12.92;
    let hi = pow((c + 0.055) / 1.055, vec3(2.4));
    return select(hi, lo, c <= vec3(0.04045));
}

fn linear_to_srgb(c: vec3<f32>) -> vec3<f32> {
    let hi = 1.055 * pow(max(c, vec3(1e-12)), vec3(1.0 / 2.4)) - 0.055;
    return select(hi, c * 12.92, c <= vec3(0.0031308));
}

// --- drop shadow ---------------------------------------------------------------------------

fn erf2(x: vec2<f32>) -> vec2<f32> {
    let s = sign(x);
    let a = abs(x);
    var t = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
    t = t * t;
    return s - s / (t * t);
}

// Coverage of the box [lo, hi] blurred by a Gaussian of std-dev `sigma`, at point p.
fn box_blur(p: vec2<f32>, lo: vec2<f32>, hi: vec2<f32>, sigma: f32) -> f32 {
    let k = 0.70710678 / sigma;
    let q = (erf2((p - lo) * k) - erf2((p - hi) * k)) * 0.5;
    return q.x * q.y;
}

@vertex
fn vs_shadow(@builtin(vertex_index) vi: u32) -> VOut {
    let pad = 64.0 * view.a.w;
    let c0 = doc_to_px(vec2(0.0, 0.0));
    let c1 = doc_to_px(vec2(view.b.z, 0.0));
    let c2 = doc_to_px(vec2(view.b.z, view.b.w));
    let c3 = doc_to_px(vec2(0.0, view.b.w));
    let lo = min(min(c0, c1), min(c2, c3)) - vec2(pad);
    let hi = max(max(c0, c1), max(c2, c3)) + vec2(pad);
    let p = mix(lo, hi, corner(vi));
    return VOut(px_to_clip(p));
}

@fragment
fn fs_shadow(in: VOut) -> @location(0) vec4<f32> {
    let p = in.pos.xy;
    let d = px_to_doc(p);
    if (all(d >= vec2(0.0)) && all(d < view.b.zw)) {
        discard;
    }
    let p_align = view.b.xy + d * view.a.z;
    let lo = doc_min();
    let hi = doc_max();
    let u = view.a.w;
    let ambient = box_blur(p_align - vec2(0.0, 7.0 * u), lo, hi, 16.0 * u) * 0.40;
    let contact = box_blur(p_align - vec2(0.0, 0.75 * u), lo, hi, 1.25 * u) * 0.30;
    let a = 1.0 - (1.0 - ambient) * (1.0 - contact);
    return vec4(0.0, 0.0, 0.0, a);
}

// --- document tiles ------------------------------------------------------------------------

@vertex
fn vs_tile(@builtin(vertex_index) vi: u32) -> VOut {
    // A View › Pattern Preview copy sits a whole number of document sizes away (view.d.xy).
    let p = doc_to_px(view.d.xy + tile.r.xy + tile.r.zw * corner(vi));
    return VOut(px_to_clip(p));
}

// Cells are screen-sized (view.c.w device px) but anchored to the document's top-left corner, so
// the pattern moves with the image as it is panned or zoomed. `d` is in document pixels (each
// Pattern Preview copy has the same cells).
fn checker(d: vec2<f32>) -> vec3<f32> {
    if (view.c.w <= 0.0) {
        return vec3(1.0);
    }
    let c = floor(d * view.a.z / view.c.w);
    let odd = fract((c.x + c.y) * 0.5) > 0.25;
    return select(view.e.xyz, view.f.xyz, odd);
}

@fragment
fn fs_tile(in: VOut) -> @location(0) vec4<f32> {
    let p = in.pos.xy;
    let scale = view.a.z;
    let d = px_to_doc(p) - view.d.xy;      // document pixel coordinates (within this copy)
    let size = tile.r.zw;
    let t = d - tile.r.xy;                 // texel coordinates within this tile
    let mode = view.c.x;
    var col: vec4<f32>;
    if (mode < 0.5) {
        // Zoomed out: trilinear through the mip chain.
        col = textureSampleLevel(tex, samp, t / size, view.c.y);
    } else if (mode < 1.5) {
        col = textureSampleLevel(tex, samp, t / size, 0.0);
    } else {
        // Crisp texels with a one-device-pixel anti-aliased edge ("sharp bilinear").
        let tt = t - 0.5;
        let i = floor(tt);
        let f = clamp((tt - i - 0.5) * scale + 0.5, vec2(0.0), vec2(1.0));
        col = textureSampleLevel(tex, samp, (i + 0.5 + f) / size, 0.0);
    }
    if (view.f.w > 0.0 && col.a > 0.0) {
        // View › 32-bit Preview Options: exposure and gamma in linear light on the sRGB-encoded
        // texture value, before the display LUT. A float canvas keeps values above 1.0, so they
        // are brought into range by the exposure instead of clipped.
        let lin = srgb_to_linear(max(col.rgb / col.a, vec3(0.0))) * view.f.w;
        let v = linear_to_srgb(min(pow(max(lin, vec3(1e-12)), vec3(view.g.w)), vec3(1.0)));
        col = vec4(v * col.a, col.a);
    }
    if (view.d.z > 0.5 && col.a > 0.0) {
        // Colour management, Proof Colors, Gamut Warning: the document's display LUT (alpha flags
        // out-of-gamut colours).
        let c = clamp(col.rgb / col.a, vec3(0.0), vec3(1.0));
        var shown: vec3<f32>;
        if (view.d.z > 2.5) {
            shown = matrix_display(c);
        } else {
            let n = f32(textureDimensions(lut).x);
            let l = textureSampleLevel(lut, samp, (c * (n - 1.0) + 0.5) / n, 0.0);
            shown = select(l.rgb, mix(l.rgb, view.g.xyz, view.e.w), view.d.z > 1.5 && l.a > 0.5);
        }
        col = vec4(shown * col.a, col.a);
    }
    var rgb = col.rgb + checker(d) * (1.0 - col.a);
    // The pixel grid is drawn over pixels with content, not over empty checker.
    let grid = view.c.z * col.a;
    if (grid > 0.0) {
        let e = fract(d) * scale;
        if (e.x < 1.0 || e.y < 1.0) {
            // White over dark pixels, a weaker black over light ones, cross-faded by luma so a
            // mid-tone image never flips line colour from one cell to the next (pixel_grid.rs
            // `light_share`: same band, same numbers).
            let t = smoothstep(0.35, 0.75, dot(rgb, vec3(0.299, 0.587, 0.114)));
            let white = grid * (1.0 - t);
            let black = grid * 0.64 * t;
            rgb = rgb * (1.0 - white - black) + vec3(white);
        }
    }
    if (view.d.w > 0.5) {
        rgb = srgb_to_linear(rgb);
    }
    return vec4(rgb, 1.0);
}
"#;

const ENCODE_WGSL: &str = r#"
@group(0) @binding(0) var acc: texture_2d<f32>;
@group(0) @binding(1) var<uniform> offset: vec4<i32>; // x, y, encode sRGB, keep values above 1.0

@vertex
fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
    let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u));
    return vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);
}

fn srgb_encode(c: vec3<f32>) -> vec3<f32> {
    return select(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3(0.0031308));
}

@fragment
fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
    let c = textureLoad(acc, vec2<i32>(floor(pos.xy)) - offset.xy, 0);
    let a = clamp(c.a, 0.0, 1.0);
    var rgb = max(c.rgb, vec3(0.0));
    if (offset.w == 0) {
        rgb = min(rgb, vec3(1.0));
    }
    if (offset.z != 0) {
        // Linear composite: store its sRGB encoding (8-bit precision where it matters).
        rgb = srgb_encode(rgb);
    }
    return vec4(rgb * a, a);
}
"#;

const MIP_WGSL: &str = r#"
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;

struct V { @builtin(position) pos: vec4<f32>, @location(0) uv: vec2<f32> };

@vertex
fn vs(@builtin(vertex_index) vi: u32) -> V {
    let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u));
    return V(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0), uv);
}

@fragment
fn fs(in: V) -> @location(0) vec4<f32> {
    // A bilinear tap at the destination texel centre averages the 2×2 source block.
    return textureSampleLevel(src, samp, in.uv, 0.0);
}
"#;

#[cfg(test)]
#[path = "gpu_canvas_mip_tests.rs"]
mod mip_tests;

#[cfg(test)]
mod tests {
    use super::*;

    /// A GPU measurement arrives a frame or two after its refresh, so most GPU refreshes carry
    /// none; the last one reported must stand until a newer one lands. A CPU refresh is
    /// different: there is no GPU time at all then, and keeping the old number would show it as
    /// this refresh's. Runs anywhere — the GPU timing tests need hardware and CI has none.
    #[test]
    fn a_gpu_measurement_stands_until_replaced_and_a_cpu_refresh_clears_it() {
        let timing = |ms, px| photocraft_gpu::GpuTiming { ms, px, spans: 1 };
        let refresh = |kind, gpu| Refresh { kind, gpu, ..Default::default() };
        let mut perf = Perf::default();
        assert_eq!(perf.gpu_ms, None, "nothing is reported before a measurement");

        perf.record_refresh(&refresh("gpu-full", Some(timing(83.9, 24_000_000))));
        assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000));

        // The common case: a GPU refresh whose own measurement has not come back yet.
        perf.record_refresh(&refresh("gpu-rect", None));
        assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000), "the last measurement stands");

        perf.record_refresh(&refresh("gpu-rect", Some(timing(11.2, 1_098_640))));
        assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(11.2), 1_098_640), "a newer measurement replaces it");

        // The CPU compositor did this one: the GPU number belongs to no refresh on screen.
        perf.record_refresh(&refresh("full", None));
        assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (None, 0), "a CPU refresh clears it rather than showing a stale one");

        // And it comes back on the next GPU refresh that carries one.
        perf.record_refresh(&refresh("gpu-full", Some(timing(42.0, 6_000_000))));
        assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(42.0), 6_000_000));
    }

    #[test]
    fn device_limits_support_v3d_shader_variable_limit() {
        let supported = wgpu::Limits { max_texture_dimension_2d: 7680, max_inter_stage_shader_variables: 15, ..wgpu::Limits::default() };
        let requested = device_limits_for(wgpu::Backend::Vulkan, supported.clone());
        assert_eq!(requested.max_inter_stage_shader_variables, 15);
        assert!(requested.check_limits(&supported));
        assert_eq!(requested.max_texture_dimension_2d, 7680);
        assert_eq!(requested.max_buffer_size, supported.max_buffer_size);
    }

    #[test]
    fn device_limits_support_weaker_gl_adapters() {
        let supported = wgpu::Limits {
            max_texture_dimension_2d: 1024,
            max_texture_dimension_3d: 128,
            max_bind_groups: 2,
            max_buffer_size: 128 << 20,
            ..wgpu::Limits::downlevel_webgl2_defaults()
        };
        let requested = device_limits_for(wgpu::Backend::Gl, supported.clone());
        assert!(requested.check_limits(&supported));
        assert_eq!(requested, supported);
    }

    #[test]
    fn device_limits_preserve_backend_defaults_on_capable_adapters() {
        let supported = wgpu::Limits {
            max_texture_dimension_2d: 16_384,
            max_buffer_size: 1 << 30,
            max_bind_groups: 8,
            max_inter_stage_shader_variables: 32,
            min_uniform_buffer_offset_alignment: 64,
            min_storage_buffer_offset_alignment: 64,
            ..wgpu::Limits::default()
        };
        for (backend, base) in [
            (wgpu::Backend::Vulkan, wgpu::Limits::default()),
            (wgpu::Backend::Dx12, wgpu::Limits::default()),
            (wgpu::Backend::Metal, wgpu::Limits::default()),
            (wgpu::Backend::Gl, wgpu::Limits::downlevel_webgl2_defaults()),
        ] {
            let requested = device_limits_for(backend, supported.clone());
            assert!(requested.check_limits(&supported));
            assert_eq!(requested, wgpu::Limits { max_texture_dimension_2d: 16_384, max_buffer_size: 1 << 30, ..base }, "{backend:?}");
        }
    }

    #[test]
    fn device_limits_support_larger_minimum_alignments() {
        let supported = wgpu::Limits { min_uniform_buffer_offset_alignment: 512, min_storage_buffer_offset_alignment: 1024, ..wgpu::Limits::default() };
        for backend in [wgpu::Backend::Vulkan, wgpu::Backend::Gl] {
            let requested = device_limits_for(backend, supported.clone());
            assert!(requested.check_limits(&supported));
            assert_eq!(requested.min_uniform_buffer_offset_alignment, 512);
            assert_eq!(requested.min_storage_buffer_offset_alignment, 1024);
        }
    }

    /// The scratch-texture workaround is for Intel's DX12 drivers (#892); other DX12 adapters
    /// render straight into the level like every other backend (#4515).
    #[test]
    fn separate_mip_targets_only_for_intel_on_dx12() {
        use wgpu::Backend::{Dx12, Metal, Vulkan};
        let (intel, nvidia, amd) = (0x8086, 0x10de, 0x1002);
        assert!(separate_mip_targets(Dx12, intel, None));
        assert!(!separate_mip_targets(Dx12, nvidia, None));
        assert!(!separate_mip_targets(Dx12, amd, None));
        assert!(!separate_mip_targets(Vulkan, intel, None));
        assert!(!separate_mip_targets(Metal, 0, None));
        // PHOTOCRAFT_SEPARATE_MIPS forces either way; anything else leaves the default.
        assert!(separate_mip_targets(Dx12, nvidia, Some("1")));
        assert!(!separate_mip_targets(Dx12, intel, Some(" 0 ")));
        assert!(separate_mip_targets(Dx12, intel, Some("yes")));
    }

    /// #6418: levels of at most WHOLE_MIP_SIDE are redrawn whole; larger ones keep the damage.
    #[test]
    fn small_mip_levels_are_redrawn_whole() {
        // A 3 × 3 dab at (800, 500) of a 1791 × 1083 tile, at mip 1 (895 × 541): halved and padded.
        assert_eq!(mip_damage([800, 500, 803, 503], 895, 541), [399, 249, 403, 253]);
        // At most 128 px on either side: the whole level, wherever the damage is.
        assert_eq!(mip_damage([100, 60, 102, 63], 111, 67), [0, 0, 111, 67]);
        assert_eq!(mip_damage([0, 0, 1, 1], 128, 2), [0, 0, 128, 2]);
        assert_eq!(mip_damage([0, 0, 1, 1], 129, 2), [0, 0, 2, 2]);
    }

    #[test]
    fn gpu_budget_follows_memory_usage_and_ram() {
        const G: u64 = 1 << 30;
        // Card memory unknown (integrated, software, or unreadable): what Memory Usage leaves
        // after the document, within a quarter of RAM.
        assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G), None, 0), 5 * G);
        assert_eq!(memory_budget(8 * G, 3 * G, Some(16 * G), None, 0), 4 * G);
        assert_eq!(memory_budget(64 * G, 3 * G, Some(16 * G), None, 0), 4 * G);
        // Never below the floor, even with nothing left; 16 GB assumed when RAM is unknown.
        assert_eq!(memory_budget(8 * G, 10 * G, Some(48 * G), None, 0), MIN_GPU_BUDGET);
        assert_eq!(memory_budget(64 * G, 0, None, None, 0), 4 * G);
        // A card's own memory, known, doesn't hold the document's pixels: 10 GB of layers no
        // longer squeeze the budget, which stays within 3/8 of the card (#4536).
        assert_eq!(memory_budget(8 * G, 10 * G, Some(32 * G), Some(32 * G), 0), 8 * G);
        assert_eq!(memory_budget(8 * G, 10 * G, Some(32 * G), Some(16 * G), 0), 6 * G);
        assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), Some(32 * G), 0), 4 * G);
        // GPU Memory set: that much, within the card's share, above the floor.
        assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), None, 12 * G), 12 * G);
        assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), Some(16 * G), 12 * G), 6 * G);
        assert_eq!(memory_budget(8 * G, 0, None, Some(32 * G), 1 << 20), MIN_GPU_BUDGET);
        assert!(physical_memory().is_none_or(|b| b >= 256 << 20));
    }

    /// An 8 GB card in a 64 GB machine: both budgets used to plan for 16 GB, twice the card (#4536).
    #[test]
    fn gpu_budgets_fit_a_discrete_gpus_own_memory() {
        const G: u64 = 1 << 30;
        let (ram, vram) = (Some(64 * G), Some(8 * G));
        assert_eq!(memory_budget(64 * G, 3 * G, ram, vram, 0), 3 * G);
        assert_eq!(canvas_budget(ram, vram), 3 * G);
        assert!(memory_budget(64 * G, 0, ram, vram, 0) + canvas_budget(ram, vram) <= 6 * G, "a quarter of the card stays free");
        // A card larger than a quarter of RAM caps nothing (its own memory isn't charged for the
        // document's 3 GB); a tiny one keeps the floor.
        assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G), Some(24 * G), 0), 8 * G);
        assert_eq!(canvas_budget(Some(16 * G), Some(24 * G)), 4 * G);
        assert_eq!(memory_budget(64 * G, 0, ram, Some(G), 0), MIN_GPU_BUDGET);
        assert_eq!(canvas_budget(ram, Some(G)), MIN_GPU_BUDGET);
    }

    /// DXGI reports each adapter's dedicated memory, found by the vendor and device ids wgpu gives.
    #[cfg(windows)]
    #[test]
    fn windows_reports_the_adapters_own_memory() {
        use winsafe::prelude::*;
        let descs: Vec<_> = winsafe::CreateDXGIFactory1().unwrap().EnumAdapters1().map(|a| a.unwrap().GetDesc1().unwrap()).collect();
        assert!(!descs.is_empty(), "DXGI lists at least its software adapter");
        for d in descs.iter().filter(|d| d.DedicatedVideoMemory > 0) {
            // The first adapter with these ids is the one matched.
            let first = descs.iter().find(|e| e.VendorId == d.VendorId && e.DeviceId == d.DeviceId).unwrap();
            assert_eq!(detect_video_memory(d.VendorId, d.DeviceId), Some(first.DedicatedVideoMemory as u64));
        }
        assert_eq!(detect_video_memory(0xdead, 0xbeef), None, "no such adapter");
    }

    /// System Info names the card's own memory, after the driver, when the card reports one; an
    /// integrated GPU or an unknown card shows no such line.
    #[test]
    fn system_info_shows_the_cards_memory() {
        let info = GpuInfo { adapter: "Card".into(), driver: "Driver 1".into(), video_memory_mb: Some(8192), ..Default::default() };
        let lines = info.lines();
        assert_eq!(lines.get(2).map(String::as_str), Some("Driver: Driver 1"));
        assert_eq!(lines.get(3).map(String::as_str), Some("Graphics memory: 8.0G"));
        let none = GpuInfo { video_memory_mb: None, ..info }.lines();
        assert!(none.iter().all(|l| !l.starts_with("Graphics memory")), "{none:?}");
        assert_eq!(none.len() + 1, lines.len());
    }

    /// The Linux reader finds the card by its PCI ids in a `/sys/class/drm`-shaped folder and reads
    /// amdgpu's VRAM size; a card without one, unreadable ids or a malformed size give nothing.
    #[test]
    fn drm_video_memory_reads_the_matching_cards_vram() {
        let drm = std::env::temp_dir().join(format!("pc-drm-{}", std::process::id()));
        let card = |name: &str, vendor: &str, device: &str, vram: Option<&str>| {
            let dev = drm.join(name).join("device");
            std::fs::create_dir_all(&dev).unwrap();
            std::fs::write(dev.join("vendor"), vendor).unwrap();
            std::fs::write(dev.join("device"), device).unwrap();
            if let Some(v) = vram {
                std::fs::write(dev.join("mem_info_vram_total"), v).unwrap();
            }
        };
        // An Intel iGPU (no VRAM file), an AMD card, and an entry with garbage ids.
        card("card0", "0x8086\n", "0x9a49\n", None);
        card("card1", "0x1002\n", "0x73bf\n", Some("17163091968\n"));
        card("card2", "not hex\n", "0x73bf\n", Some("1\n"));
        card("card3", "0x10de\n", "0x2684\n", Some("lots\n"));
        assert_eq!(drm_video_memory(&drm, 0x1002, 0x73bf), Some(17_163_091_968));
        assert_eq!(drm_video_memory(&drm, 0x8086, 0x9a49), None, "no amdgpu VRAM file");
        assert_eq!(drm_video_memory(&drm, 0x10de, 0x2684), None, "a malformed size");
        assert_eq!(drm_video_memory(&drm, 0xdead, 0xbeef), None, "no such card");
        assert_eq!(drm_video_memory(&drm.join("missing"), 0x1002, 0x73bf), None, "no drm folder");
        std::fs::remove_dir_all(&drm).unwrap();
    }

    /// Windows used to report no RAM at all, so the budget assumed 16 GB on every machine.
    #[cfg(windows)]
    #[test]
    fn windows_reports_installed_ram() {
        let ram = detect_physical_memory().unwrap_or(0);
        assert!(ram >= 256 << 20, "{ram} bytes");
        assert!(ram < 1 << 50, "{ram} bytes");
    }

    #[test]
    fn canvas_texture_bytes_price_every_tile_and_mip_level() {
        // The same sum DocTextures builds tile by tile (and texture_info reports).
        let brute = |size: [u32; 2], tile: u32, bpp: u64| -> u64 {
            let mut total = 0;
            for ty in (0..size[1]).step_by(tile as usize) {
                for tx in (0..size[0]).step_by(tile as usize) {
                    let (w, h) = (tile.min(size[0] - tx), tile.min(size[1] - ty));
                    total += (0..mip_count(w, h)).map(|l| u64::from((w >> l).max(1)) * u64::from((h >> l).max(1)) * bpp).sum::<u64>();
                }
            }
            total
        };
        for (size, tile) in [([1, 1], 64), ([300, 200], 64), ([128, 64], 64), ([1000, 7], 256), ([8192, 8193], 8192), ([20_000, 9_000], 8192)] {
            for bpp in [4, 8] {
                assert_eq!(canvas_texture_bytes(size, tile, bpp), brute(size, tile, bpp), "{size:?} tile {tile}");
            }
        }
        assert_eq!(canvas_texture_bytes([0, 500], 64, 4), 0);
        // A canvas declared in a few bytes of a file is priced without building (or looping over) it.
        let huge = canvas_texture_bytes([300_000, 300_000], 8192, 4);
        assert!(huge > 300_000u64 * 300_000 * 4 && huge > canvas_budget(Some(1 << 40), None));
        assert_eq!(canvas_texture_bytes([u32::MAX, u32::MAX], 64, 8), u64::MAX, "saturates");
        // A quarter of RAM (16 GB assumed), never below the compositor's floor.
        assert_eq!(canvas_budget(None, None), 4 << 30);
        assert_eq!(canvas_budget(Some(1 << 30), None), MIN_GPU_BUDGET);
        assert!(canvas_texture_bytes([12_000, 8_000], DEFAULT_TILE, 8) < canvas_budget(None, None), "a 96 MP 16-bit canvas stays on the GPU");
    }

    #[test]
    fn view_uniform_packs_rotation() {
        assert_eq!(VIEW_FLOATS, 32);
        assert_eq!(VIEW_UNIFORM_SIZE, 128);
        assert_eq!(VIEW_FLOATS * 4, VIEW_UNIFORM_SIZE as usize);
        assert!(gpu_view_ok(false, 0.0, 1.0));
        assert!(gpu_view_ok(false, 45.0_f32.to_radians(), 1.0));
        assert!(!gpu_view_ok(true, 45.0_f32.to_radians(), 1.0));
        assert!(!gpu_view_ok(false, 0.0, 2.0), "pixel aspect correction draws on the CPU");
        // Identity packing: rotation 0 matches the unrotated origin + scale map.
        let origin = [10.0, 20.0];
        let (scale, center) = (2.0, [40.0, 8.0]);
        let a = map_doc_px(origin, scale, center, 1.0, 0.0, 5.0, 9.0);
        assert!((a[0] - (origin[0] + 5.0 * scale)).abs() < 1e-4);
        assert!((a[1] - (origin[1] + 9.0 * scale)).abs() < 1e-4);
        let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, center, 1.0, 0.0, [0.0, 0.0, 10.0, 4.0]);
        assert!((x0 - origin[0]).abs() < 1e-4 && (y0 - origin[1]).abs() < 1e-4);
        assert!((x1 - (origin[0] + 20.0)).abs() < 1e-4 && (y1 - (origin[1] + 8.0)).abs() < 1e-4);
    }

    #[test]
    fn filter_modes() {
        assert_eq!(filter_mode(0.25), (0.0, 2.0));
        assert_eq!(filter_mode(1.0).0, 2.0);
        assert_eq!(filter_mode(1.5).0, 1.0);
        assert_eq!(filter_mode(3.3).0, 2.0);
    }

    #[test]
    fn mips_and_premultiply() {
        assert_eq!(mip_count(1, 1), 1);
        assert_eq!(mip_count(4096, 100), 13);
        assert_eq!(mip_count(5, 3), 3);
        assert_eq!(premultiply_rgba8(&[[1.0, 0.5, 0.0, 0.5]]), vec![128, 64, 0, 128]);
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn half_floats() {
        // Every finite half survives the round trip; ties round to even; overflow saturates.
        for h in 0..=u16::MAX {
            if h & 0x7c00 != 0x7c00 && h != 0x8000 {
                assert_eq!(f32_to_f16(f16_to_f32(h)), h, "{h:#06x}");
            }
        }
        assert_eq!(f32_to_f16(1.0), 0x3c00);
        assert_eq!(f32_to_f16(1.0 + 2f32.powi(-11)), 0x3c00);
        assert_eq!(f32_to_f16(1.0 + 3.0 * 2f32.powi(-11)), 0x3c02);
        assert_eq!(f32_to_f16(2f32.powi(-24)), 1);
        assert_eq!(f32_to_f16(2f32.powi(-26)), 0);
        assert_eq!(f32_to_f16(65504.0), 0x7bff);
        assert_eq!(f32_to_f16(1e9), 0x7bff);
        assert_eq!(f32_to_f16(f32::INFINITY), 0x7bff);
        assert_eq!(f32_to_f16(f32::NAN), 0);
        assert_eq!(f32_to_f16(-2.0), 0xc000);
        assert_eq!(premultiply_rgba16f(&[[2.0, -1.0, f32::NAN, 0.5]]), [0x00, 0x3c, 0, 0, 0, 0, 0x00, 0x38]);
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn shaders_validate() {
        use wgpu::naga;
        for (name, src) in [("canvas", CANVAS_WGSL), ("mip", MIP_WGSL), ("encode", ENCODE_WGSL)] {
            let module = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(src)));
            naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty())
                .validate(&module)
                .unwrap_or_else(|e| panic!("{name}: {e:?}"));
        }
    }
}