Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

41.9 KB
Raw Blame
//! Native selection tool generators (Rect, Lasso, Magic Wand) and layer selection operations
//! (Clear, Delete Outside, Fill Color, Cut, Copy, Paste, Move to New Layer) executing directly
//! on `Document`'s sparse tile grids with CoW Undo/Redo.

use super::mask::{
    FloatingSelection, SelectionClipboard, SelectionCombineMode, SelectionMetaSnapshot,
    SparseSelectionMask, WandReferMode,
};
use crate::document::{Document, LayerNodeMeta};
use crate::io::compositor_cpu;
use crate::memory::ScratchBackend;
use crate::tiles::{
    pixel_to_tile_coord, RectI32, TileCoord, TileKind, TILE_SIZE, TILE_SIZE_I32,
};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SelectionOpResult {
    pub selection: SelectionMetaSnapshot,
    pub modified: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_layer_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SelectionFillResult {
    pub modified: bool,
    pub dirty_rect: RectI32,
}

/// Creates or combines a rectangular selection directly into `doc.selection`.
pub fn select_rect(
    doc: &mut Document,
    rect: RectI32,
    mode: SelectionCombineMode,
) -> SelectionMetaSnapshot {
    let dw = doc.dimensions.width;
    let dh = doc.dimensions.height;
    let doc_rect = RectI32::new(0, 0, dw, dh);
    let clipped = rect.intersect(doc_rect);

    let sel = doc
        .selection
        .get_or_insert_with(|| SparseSelectionMask::new_empty(dw, dh));
    sel.doc_width = dw;
    sel.doc_height = dh;

    if clipped.is_empty() {
        if mode == SelectionCombineMode::Replace || mode == SelectionCombineMode::Intersect {
            doc.selection = None;
            return SelectionMetaSnapshot::empty();
        }
        return sel.snapshot_meta();
    }

    let incoming = vec![255u8; (clipped.width as usize) * (clipped.height as usize)];
    sel.combine_rect(clipped, &incoming, mode);
    if sel.is_empty() {
        doc.selection = None;
        return SelectionMetaSnapshot::empty();
    }
    sel.snapshot_meta()
}

/// Rasterizes a polygon (lasso) with optional 4×4 supersampled anti-aliasing into `doc.selection`.
pub fn select_lasso(
    doc: &mut Document,
    polygon: &[(f32, f32)],
    anti_alias: bool,
    mode: SelectionCombineMode,
) -> SelectionMetaSnapshot {
    let dw = doc.dimensions.width;
    let dh = doc.dimensions.height;
    if polygon.len() < 3 {
        if mode == SelectionCombineMode::Replace || mode == SelectionCombineMode::Intersect {
            doc.selection = None;
            return SelectionMetaSnapshot::empty();
        }
        return doc
            .selection
            .as_ref()
            .map(|s| s.snapshot_meta())
            .unwrap_or_else(SelectionMetaSnapshot::empty);
    }

    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for &(px, py) in polygon {
        min_x = min_x.min(px);
        min_y = min_y.min(py);
        max_x = max_x.max(px);
        max_y = max_y.max(py);
    }
    if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() {
        if mode == SelectionCombineMode::Replace || mode == SelectionCombineMode::Intersect {
            doc.selection = None;
            return SelectionMetaSnapshot::empty();
        }
        return doc
            .selection
            .as_ref()
            .map(|s| s.snapshot_meta())
            .unwrap_or_else(SelectionMetaSnapshot::empty);
    }
    let doc_rect = RectI32::new(0, 0, dw, dh);
    let raw_rect = RectI32::new(
        (min_x.floor() as i32).saturating_sub(1),
        (min_y.floor() as i32).saturating_sub(1),
        ((max_x.ceil() - min_x.floor()) as i32)
            .saturating_add(3)
            .max(0) as u32,
        ((max_y.ceil() - min_y.floor()) as i32)
            .saturating_add(3)
            .max(0) as u32,
    );
    let clipped = raw_rect.intersect(doc_rect);
    if clipped.is_empty() {
        if mode == SelectionCombineMode::Replace || mode == SelectionCombineMode::Intersect {
            doc.selection = None;
            return SelectionMetaSnapshot::empty();
        }
        return doc
            .selection
            .as_ref()
            .map(|s| s.snapshot_meta())
            .unwrap_or_else(SelectionMetaSnapshot::empty);
    }

    let mask = rasterize_polygon_mask(polygon, clipped, anti_alias);
    let sel = doc
        .selection
        .get_or_insert_with(|| SparseSelectionMask::new_empty(dw, dh));
    sel.doc_width = dw;
    sel.doc_height = dh;
    sel.combine_rect(clipped, &mask, mode);
    if sel.is_empty() {
        doc.selection = None;
        return SelectionMetaSnapshot::empty();
    }
    sel.snapshot_meta()
}

/// Fast parallel scanline polygon rasterizer (4×4 supersampled AA or crisp 1-bit binary).
pub fn rasterize_polygon_mask(
    polygon: &[(f32, f32)],
    rect: RectI32,
    anti_alias: bool,
) -> Vec<u8> {
    let w = rect.width as usize;
    let h = rect.height as usize;
    let mut mask = vec![0u8; w * h];
    if polygon.len() < 3 || w == 0 || h == 0 {
        return mask;
    }

    let n = polygon.len();
    // Pre-build edge table `(x0, y0, x1, y1)` skipping horizontal edges
    let mut edges: Vec<(f32, f32, f32, f32)> = Vec::with_capacity(n);
    for i in 0..n {
        let a = polygon[i];
        let b = polygon[(i + 1) % n];
        if (a.1 - b.1).abs() > 1e-6 {
            edges.push((a.0, a.1, b.0, b.1));
        }
    }
    if edges.is_empty() {
        return mask;
    }

    let sub = if anti_alias { 4usize } else { 1usize };
    let inv_sub = 1.0 / sub as f32;
    let rx0 = rect.x as f32;
    let ry0 = rect.y as f32;

    mask.par_chunks_exact_mut(w)
        .enumerate()
        .for_each(|(ry, out_row)| {
            let mut xs = Vec::with_capacity(32);
            let mut accum = if anti_alias { vec![0u8; w] } else { Vec::new() };

            for sy in 0..sub {
                let sample_y = ry0 + ry as f32 + (sy as f32 + 0.5) * inv_sub;
                xs.clear();
                for &(x0, y0, x1, y1) in &edges {
                    if (y0 <= sample_y && y1 > sample_y) || (y1 <= sample_y && y0 > sample_y) {
                        let t = (sample_y - y0) / (y1 - y0);
                        xs.push(x0 + t * (x1 - x0));
                    }
                }
                if xs.len() < 2 {
                    continue;
                }
                xs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

                let mut pair = 0;
                while pair + 1 < xs.len() {
                    let x_start = xs[pair] - rx0;
                    let x_end = xs[pair + 1] - rx0;
                    pair += 2;
                    if x_end <= 0.0 || x_start >= w as f32 {
                        continue;
                    }
                    if anti_alias {
                        let px0 = x_start.floor().max(0.0) as usize;
                        let px1 = (x_end.ceil().min(w as f32) as usize).min(w);
                        for (px, slot) in accum.iter_mut().enumerate().take(px1).skip(px0) {
                            for sx in 0..4 {
                                let sample_x = px as f32 + (sx as f32 + 0.5) * 0.25;
                                if sample_x >= x_start && sample_x < x_end {
                                    *slot += 1;
                                }
                            }
                        }
                    } else {
                        let px0 = (x_start + 0.5).floor().max(0.0) as usize;
                        let px1 = ((x_end + 0.5).floor().min(w as f32) as usize).min(w);
                        for cell in &mut out_row[px0..px1] {
                            *cell = 255;
                        }
                    }
                }
            }

            if anti_alias {
                for x in 0..w {
                    let c = accum[x];
                    if c > 0 {
                        out_row[x] = ((c as u32 * 255 + 8) / 16).min(255) as u8;
                    }
                }
            }
        });

    mask
}

/// Builds a composited RGBA8 reference buffer over `[0..w, 0..h]` according to `WandReferMode`.
pub fn build_reference_rgba8(
    doc: &Document,
    refer_mode: WandReferMode,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Vec<u8>, String> {
    let w = doc.dimensions.width;
    let h = doc.dimensions.height;
    let rect = RectI32::new(0, 0, w, h);

    match refer_mode {
        WandReferMode::All => compositor_cpu::composite_document_full_rgba(doc, scratch),
        WandReferMode::Active => {
            if let Some(aid) = doc.active_layer_id.as_deref() {
                if let Some(layer) = doc.layer(aid) {
                    return layer.grid.read_rgba8_rect(rect, false, scratch);
                }
            }
            Ok(vec![0u8; (w as usize) * (h as usize) * 4])
        }
        WandReferMode::Reference => {
            let ref_ids: Vec<&str> = doc
                .layers
                .iter()
                .filter(|l| {
                    l.meta.is_reference.unwrap_or(false)
                        && l.meta.layer_type.has_tiles()
                        && doc.is_layer_effectively_visible(&l.meta.id)
                })
                .map(|l| l.meta.id.as_str())
                .collect();
            if ref_ids.is_empty() {
                // Fallback to active layer if no explicit Reference layers are flagged
                return build_reference_rgba8(doc, WandReferMode::Active, scratch);
            }
            let mut acc = vec![0u8; (w as usize) * (h as usize) * 4];
            for layer in doc.layers.iter().rev() {
                if !ref_ids.contains(&layer.meta.id.as_str()) {
                    continue;
                }
                let op = doc.effective_opacity(&layer.meta.id);
                if op <= 0.001 || layer.grid.tiles.is_empty() {
                    continue;
                }
                let mut src = layer.grid.read_rgba8_rect(rect, false, scratch)?;
                if layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {
                    let mask = layer.grid.read_mask8_rect(rect, scratch)?;
                    for (px, &m) in src.as_chunks_mut::<4>().0.iter_mut().zip(mask.iter()) {
                        px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;
                    }
                }
                compositor_cpu::blend_rgba8_over(&mut acc, &src, op, layer.meta.blend_mode);
            }
            Ok(acc)
        }
    }
}

/// Magic Wand selection directly on Rust's `Document` sparse tiles.
/// Supports `tolerance` (`0..=255`), `contiguous` (scanline flood vs global), `anti_alias`,
/// `refer_mode` (`Active | All | Reference`), and boolean `mode`.
#[allow(clippy::too_many_arguments)]
pub fn select_magic_wand(
    doc: &mut Document,
    start_x: i32,
    start_y: i32,
    tolerance: f32,
    contiguous: bool,
    anti_alias: bool,
    refer_mode: WandReferMode,
    mode: SelectionCombineMode,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<SelectionMetaSnapshot, String> {
    let w = doc.dimensions.width as usize;
    let h = doc.dimensions.height as usize;
    if w == 0 || h == 0 || start_x < 0 || start_y < 0 || start_x >= w as i32 || start_y >= h as i32 {
        return Ok(doc
            .selection
            .as_ref()
            .map(|s| s.snapshot_meta())
            .unwrap_or_else(SelectionMetaSnapshot::empty));
    }

    let ref_rgba = build_reference_rgba8(doc, refer_mode, scratch)?;
    let sx = start_x as usize;
    let sy = start_y as usize;
    let seed_i = (sy * w + sx) * 4;
    let sr = ref_rgba[seed_i] as f32;
    let sg = ref_rgba[seed_i + 1] as f32;
    let sb = ref_rgba[seed_i + 2] as f32;
    let sa = ref_rgba[seed_i + 3] as f32;

    // Parity with selectionUtils.ts: RGBA Euclidean distance / 2 <= tolerance
    let tol = tolerance.clamp(0.0, 255.0);
    let max_dist_sq = (tol * 2.0) * (tol * 2.0);
    let aa_outer = ((tol + 12.0).min(255.0) * 2.0).powi(2);

    let pixel_dist_sq = |p: usize| -> f32 {
        let i = p * 4;
        let dr = ref_rgba[i] as f32 - sr;
        let dg = ref_rgba[i + 1] as f32 - sg;
        let db = ref_rgba[i + 2] as f32 - sb;
        let da = ref_rgba[i + 3] as f32 - sa;
        dr * dr + dg * dg + db * db + da * da
    };

    let mut mask = vec![0u8; w * h];
    let mut min_x = w;
    let mut min_y = h;
    let mut max_x = 0usize;
    let mut max_y = 0usize;
    let mut any_selected = false;

    if contiguous {
        let mut visited = vec![0u8; w * h];
        let mut stack = Vec::with_capacity(4096);
        stack.push((sx, sy));

        while let Some((cx, cy)) = stack.pop() {
            let row = cy * w;
            if visited[row + cx] != 0 {
                continue;
            }
            let mut x1 = cx;
            while x1 > 0 && visited[row + x1 - 1] == 0 && pixel_dist_sq(row + x1 - 1) <= max_dist_sq {
                x1 -= 1;
            }
            if visited[row + x1] != 0 || pixel_dist_sq(row + x1) > max_dist_sq {
                continue;
            }
            let mut x2 = cx;
            while x2 + 1 < w && visited[row + x2 + 1] == 0 && pixel_dist_sq(row + x2 + 1) <= max_dist_sq {
                x2 += 1;
            }
            any_selected = true;
            min_x = min_x.min(x1);
            max_x = max_x.max(x2);
            min_y = min_y.min(cy);
            max_y = max_y.max(cy);

            let mut span_up = false;
            let mut span_dn = false;
            for x in x1..=x2 {
                let p = row + x;
                visited[p] = 1;
                mask[p] = 255;
                if cy > 0 {
                    let up = (cy - 1) * w + x;
                    let ok = visited[up] == 0 && pixel_dist_sq(up) <= max_dist_sq;
                    if !span_up && ok {
                        stack.push((x, cy - 1));
                        span_up = true;
                    } else if span_up && !ok {
                        span_up = false;
                    }
                }
                if cy + 1 < h {
                    let dn = (cy + 1) * w + x;
                    let ok = visited[dn] == 0 && pixel_dist_sq(dn) <= max_dist_sq;
                    if !span_dn && ok {
                        stack.push((x, cy + 1));
                        span_dn = true;
                    } else if span_dn && !ok {
                        span_dn = false;
                    }
                }
            }
        }

        // Smooth 1px anti-aliased boundary fringe along contiguous perimeter
        if anti_alias && any_selected {
            let x0 = min_x.saturating_sub(1);
            let y0 = min_y.saturating_sub(1);
            let x1 = (max_x + 1).min(w - 1);
            let y1 = (max_y + 1).min(h - 1);
            let orig = mask.clone();
            for y in y0..=y1 {
                let row = y * w;
                for x in x0..=x1 {
                    let p = row + x;
                    if orig[p] != 0 {
                        continue;
                    }
                    let adj = (x > 0 && orig[p - 1] != 0)
                        || (x + 1 < w && orig[p + 1] != 0)
                        || (y > 0 && orig[p - w] != 0)
                        || (y + 1 < h && orig[p + w] != 0);
                    if adj {
                        let d2 = pixel_dist_sq(p);
                        if d2 < aa_outer {
                            let t = 1.0 - (d2.sqrt() - max_dist_sq.sqrt()) / 24.0;
                            let a = (t.clamp(0.0, 1.0) * 255.0).round() as u8;
                            if a > 0 {
                                mask[p] = a;
                                min_x = min_x.min(x);
                                max_x = max_x.max(x);
                                min_y = min_y.min(y);
                                max_y = max_y.max(y);
                            }
                        }
                    }
                }
            }
        }
    } else {
        // Non-contiguous global match (parallelized with Rayon)
        mask.par_chunks_exact_mut(w)
            .enumerate()
            .for_each(|(y, row_out)| {
                let row = y * w;
                for (x, out_px) in row_out.iter_mut().enumerate().take(w) {
                    let d2 = pixel_dist_sq(row + x);
                    if d2 <= max_dist_sq {
                        *out_px = 255;
                    } else if anti_alias && d2 < aa_outer {
                        let t = 1.0 - (d2.sqrt() - max_dist_sq.sqrt()) / 24.0;
                        *out_px = (t.clamp(0.0, 1.0) * 255.0).round() as u8;
                    }
                }
            });
        for y in 0..h {
            let row = y * w;
            for x in 0..w {
                if mask[row + x] > 0 {
                    any_selected = true;
                    min_x = min_x.min(x);
                    max_x = max_x.max(x);
                    min_y = min_y.min(y);
                    max_y = max_y.max(y);
                }
            }
        }
    }

    if !any_selected {
        if mode == SelectionCombineMode::Replace || mode == SelectionCombineMode::Intersect {
            doc.selection = None;
            return Ok(SelectionMetaSnapshot::empty());
        }
        return Ok(doc
            .selection
            .as_ref()
            .map(|s| s.snapshot_meta())
            .unwrap_or_else(SelectionMetaSnapshot::empty));
    }

    // Extract tight sub-rect to pass into sparse selection mask
    let sub_w = max_x - min_x + 1;
    let sub_h = max_y - min_y + 1;
    let mut tight = vec![0u8; sub_w * sub_h];
    for ry in 0..sub_h {
        let src_off = (min_y + ry) * w + min_x;
        let dst_off = ry * sub_w;
        tight[dst_off..dst_off + sub_w].copy_from_slice(&mask[src_off..src_off + sub_w]);
    }
    let rect = RectI32::new(min_x as i32, min_y as i32, sub_w as u32, sub_h as u32);
    let sel = doc
        .selection
        .get_or_insert_with(|| SparseSelectionMask::new_empty(w as u32, h as u32));
    sel.doc_width = w as u32;
    sel.doc_height = h as u32;
    sel.combine_rect(rect, &tight, mode);
    if sel.is_empty() {
        doc.selection = None;
        return Ok(SelectionMetaSnapshot::empty());
    }
    Ok(sel.snapshot_meta())
}

/// Clears pixels inside the active selection on `layer_id` with CoW Undo.
pub fn clear_selection_pixels(
    doc: &mut Document,
    layer_id: &str,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<SelectionFillResult, String> {
    let Some(sel) = doc.selection.clone() else {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    };
    if sel.bounds.is_empty() {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }
    let rect = sel.bounds.intersect(RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height));
    if rect.is_empty() {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }

    let mask = sel.read_rect(rect);
    let node = doc
        .layer_mut(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
    if node.meta.locked || !node.meta.layer_type.has_tiles() {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }

    let before_snap = node.grid.snapshot_all_cow(TileKind::Raster);
    let mut rgba = node.grid.read_rgba8_rect(rect, false, scratch)?;
    let mut changed = false;
    for (px, &m) in rgba.as_chunks_mut::<4>().0.iter_mut().zip(mask.iter()) {
        if m == 0 || px[3] == 0 {
            continue;
        }
        changed = true;
        if m == 255 {
            px[0] = 0;
            px[1] = 0;
            px[2] = 0;
            px[3] = 0;
        } else {
            let keep = 255u32 - u32::from(m);
            let new_a = ((u32::from(px[3]) * keep + 127) / 255) as u8;
            px[3] = new_a;
            if new_a == 0 {
                px[0] = 0;
                px[1] = 0;
                px[2] = 0;
            }
        }
    }
    if !changed {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }
    let thresh = node.meta.mono_threshold.unwrap_or(128);
    node.grid.write_rgba8_rect(&rgba, rect, thresh, scratch)?;
    let deltas = node
        .grid
        .diff_from_full_snapshot(layer_id, TileKind::Raster, &before_snap);
    doc.record_stroke_deltas(layer_id, "clear", "Clear Selection", deltas, None, None);
    Ok(SelectionFillResult {
        modified: true,
        dirty_rect: rect,
    })
}

/// Deletes pixels OUTSIDE the active selection on `layer_id` with CoW Undo.
pub fn clear_outside_selection(
    doc: &mut Document,
    layer_id: &str,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<SelectionFillResult, String> {
    let Some(sel) = doc.selection.clone() else {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    };
    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
    let node = doc
        .layer_mut(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
    if node.meta.locked || !node.meta.layer_type.has_tiles() || node.grid.tiles.is_empty() {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }

    let before_snap = node.grid.snapshot_all_cow(TileKind::Raster);
    let coords: Vec<TileCoord> = node.grid.tiles.keys().copied().collect();
    let thresh = node.meta.mono_threshold.unwrap_or(128);
    let mut dirty = RectI32::empty();

    for coord in coords {
        let tile_rect = RectI32::new(
            coord.tx * TILE_SIZE_I32,
            coord.ty * TILE_SIZE_I32,
            TILE_SIZE as u32,
            TILE_SIZE as u32,
        )
        .intersect(doc_rect);
        if tile_rect.is_empty() {
            continue;
        }
        let mask = sel.read_rect(tile_rect);
        let mut rgba = node.grid.read_rgba8_rect(tile_rect, false, scratch)?;
        let mut tile_changed = false;
        for (px, &m) in rgba.as_chunks_mut::<4>().0.iter_mut().zip(mask.iter()) {
            if m == 255 || px[3] == 0 {
                continue;
            }
            tile_changed = true;
            if m == 0 {
                px[0] = 0;
                px[1] = 0;
                px[2] = 0;
                px[3] = 0;
            } else {
                let new_a = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;
                px[3] = new_a;
                if new_a == 0 {
                    px[0] = 0;
                    px[1] = 0;
                    px[2] = 0;
                }
            }
        }
        if tile_changed {
            node.grid.write_rgba8_rect(&rgba, tile_rect, thresh, scratch)?;
            dirty = dirty.union(tile_rect);
        }
    }

    let deltas = node
        .grid
        .diff_from_full_snapshot(layer_id, TileKind::Raster, &before_snap);
    if deltas.is_empty() {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }
    doc.record_stroke_deltas(layer_id, "clear", "Delete Outside Selection", deltas, None, None);
    Ok(SelectionFillResult {
        modified: true,
        dirty_rect: dirty,
    })
}

/// Fills the active selection (or entire canvas if no selection) on `layer_id` with `rgba8`.
pub fn fill_selection_color(
    doc: &mut Document,
    layer_id: &str,
    rgba8: [u8; 4],
    opacity: f32,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<SelectionFillResult, String> {
    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
    let sel_opt = doc.selection.clone();
    let target_rect = sel_opt
        .as_ref()
        .map(|s| s.bounds.intersect(doc_rect))
        .unwrap_or(doc_rect);
    if target_rect.is_empty() {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }

    let node = doc
        .layer_mut(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
    if node.meta.locked || !node.meta.layer_type.has_tiles() {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }

    let alpha_locked = node.meta.alpha_locked.unwrap_or(false);
    let thresh = node.meta.mono_threshold.unwrap_or(128);
    let before_snap = node.grid.snapshot_all_cow(TileKind::Raster);
    let src_alpha_f = (rgba8[3] as f32 / 255.0) * opacity.clamp(0.0, 1.0);

    let min_tx = pixel_to_tile_coord(target_rect.x, 0);
    let min_ty = pixel_to_tile_coord(target_rect.y, 0);
    let max_tx = pixel_to_tile_coord(target_rect.right() - 1, 0);
    let max_ty = pixel_to_tile_coord(target_rect.bottom() - 1, 0);

    for ty in min_ty..=max_ty {
        for tx in min_tx..=max_tx {
            let tile_rect = RectI32::new(
                tx * TILE_SIZE_I32,
                ty * TILE_SIZE_I32,
                TILE_SIZE as u32,
                TILE_SIZE as u32,
            )
            .intersect(target_rect);
            if tile_rect.is_empty() {
                continue;
            }
            let mask_opt = sel_opt.as_ref().map(|s| s.read_rect(tile_rect));
            let mut dst = node.grid.read_rgba8_rect(tile_rect, false, scratch)?;
            for (i, px) in dst.as_chunks_mut::<4>().0.iter_mut().enumerate() {
                let m = mask_opt.as_ref().map(|v| v[i]).unwrap_or(255);
                if m == 0 {
                    continue;
                }
                let sa = src_alpha_f * (m as f32 / 255.0);
                if sa <= 1e-4 {
                    continue;
                }
                let da = px[3] as f32 / 255.0;
                if alpha_locked {
                    if da <= 1e-4 {
                        continue;
                    }
                    px[0] = (px[0] as f32 * (1.0 - sa) + rgba8[0] as f32 * sa)
                        .round()
                        .clamp(0.0, 255.0) as u8;
                    px[1] = (px[1] as f32 * (1.0 - sa) + rgba8[1] as f32 * sa)
                        .round()
                        .clamp(0.0, 255.0) as u8;
                    px[2] = (px[2] as f32 * (1.0 - sa) + rgba8[2] as f32 * sa)
                        .round()
                        .clamp(0.0, 255.0) as u8;
                } else {
                    let out_a = sa + da * (1.0 - sa);
                    if out_a > 1e-4 {
                        let inv = 1.0 / out_a;
                        let k = da * (1.0 - sa);
                        px[0] = ((rgba8[0] as f32 * sa + px[0] as f32 * k) * inv)
                            .round()
                            .clamp(0.0, 255.0) as u8;
                        px[1] = ((rgba8[1] as f32 * sa + px[1] as f32 * k) * inv)
                            .round()
                            .clamp(0.0, 255.0) as u8;
                        px[2] = ((rgba8[2] as f32 * sa + px[2] as f32 * k) * inv)
                            .round()
                            .clamp(0.0, 255.0) as u8;
                        px[3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
                    }
                }
            }
            node.grid.write_rgba8_rect(&dst, tile_rect, thresh, scratch)?;
        }
    }

    let deltas = node
        .grid
        .diff_from_full_snapshot(layer_id, TileKind::Raster, &before_snap);
    if deltas.is_empty() {
        return Ok(SelectionFillResult {
            modified: false,
            dirty_rect: RectI32::empty(),
        });
    }
    doc.record_stroke_deltas(layer_id, "fill", "Fill Selection", deltas, None, None);
    Ok(SelectionFillResult {
        modified: true,
        dirty_rect: target_rect,
    })
}

/// Extracts masked RGBA8 pixels inside the active selection (or whole layer if no selection).
pub fn copy_selection(
    doc: &Document,
    layer_id: &str,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Option<SelectionClipboard>, String> {
    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
    let node = doc
        .layer(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
    if !node.meta.layer_type.has_tiles() {
        return Ok(None);
    }

    let (rect, mask_opt) = if let Some(ref sel) = doc.selection {
        let r = sel.bounds.intersect(doc_rect);
        if r.is_empty() {
            return Ok(None);
        }
        (r, Some(sel.read_rect(r)))
    } else {
        (doc_rect, None)
    };

    let mut rgba = node.grid.read_rgba8_rect(rect, false, scratch)?;
    let mut any_non_zero = false;
    if let Some(mask) = mask_opt {
        for (px, &m) in rgba.as_chunks_mut::<4>().0.iter_mut().zip(mask.iter()) {
            let a = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;
            px[3] = a;
            if a == 0 {
                px[0] = 0;
                px[1] = 0;
                px[2] = 0;
            } else {
                any_non_zero = true;
            }
        }
    } else {
        any_non_zero = rgba.as_chunks::<4>().0.iter().any(|p| p[3] > 0);
    }

    if !any_non_zero {
        return Ok(None);
    }

    Ok(Some(SelectionClipboard {
        x: rect.x,
        y: rect.y,
        width: rect.width,
        height: rect.height,
        rgba,
        source_layer_name: node.meta.name.clone(),
    }))
}

/// Cuts the active selection pixels from `layer_id` into a [`SelectionClipboard`] with CoW Undo.
pub fn cut_selection(
    doc: &mut Document,
    layer_id: &str,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Option<SelectionClipboard>, String> {
    if let Some(node) = doc.layer(layer_id) {
        if node.meta.locked || !node.meta.layer_type.has_tiles() {
            return Ok(None);
        }
    }
    let copied = copy_selection(doc, layer_id, scratch)?;
    if copied.is_none() {
        return Ok(None);
    }
    if doc.selection.is_some() {
        let _ = clear_selection_pixels(doc, layer_id, scratch)?;
    } else {
        doc.clear_layer(layer_id, true)?;
    }
    Ok(copied)
}

/// Pastes a [`SelectionClipboard`] into a brand-new raster layer above the active layer with atomic CoW Undo.
pub fn paste_selection(
    doc: &mut Document,
    clip: &SelectionClipboard,
    new_layer_id: String,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<String, String> {
    let before_layers: Vec<LayerNodeMeta> = doc.layers.iter().map(|l| l.meta.clone()).collect();
    let before_active = doc.active_layer_id.clone();

    let name = format!("{} (Pasted)", clip.source_layer_name);
    let insert_idx = doc
        .active_layer_id
        .as_deref()
        .and_then(|aid| doc.layer_index(aid))
        .unwrap_or(0);
    let mut meta = LayerNodeMeta::new_raster(new_layer_id.clone(), name);
    if let Some(active) = doc.active_layer() {
        meta.parent_id = active.meta.parent_id.clone();
    }
    doc.add_layer(meta, Some(insert_idx), true, false);
    let rect = RectI32::new(clip.x, clip.y, clip.width, clip.height);
    if let Some(node) = doc.layer_mut(&new_layer_id) {
        let thresh = node.meta.mono_threshold.unwrap_or(128);
        node.grid.write_rgba8_rect(&clip.rgba, rect, thresh, scratch)?;
    }
    let after_grid = doc
        .layer(&new_layer_id)
        .map(|n| (new_layer_id.clone(), n.grid.clone_cow()))
        .into_iter()
        .collect();
    doc.dirty_for_render = true;
    doc.record_tree_history(
        "layer",
        "Paste Selection",
        Some(new_layer_id.clone()),
        before_layers,
        before_active,
        Vec::new(),
        after_grid,
        Vec::new(),
        None,
    );
    Ok(new_layer_id)
}

/// Moves the selected pixels from `src_layer_id` into a brand-new layer above it with atomic CoW Undo.
pub fn move_selection_to_new_layer(
    doc: &mut Document,
    src_layer_id: &str,
    new_layer_id: String,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Option<String>, String> {
    if let Some(node) = doc.layer(src_layer_id) {
        if node.meta.locked || !node.meta.layer_type.has_tiles() {
            return Ok(None);
        }
    }
    let Some(clip) = copy_selection(doc, src_layer_id, scratch)? else {
        return Ok(None);
    };
    let before_layers: Vec<LayerNodeMeta> = doc.layers.iter().map(|l| l.meta.clone()).collect();
    let before_active = doc.active_layer_id.clone();
    let src_before_grid = doc
        .layer(src_layer_id)
        .map(|n| (src_layer_id.to_string(), n.grid.clone_cow()));

    // Clear selected region from source layer without recording a separate undo step
    let rect = RectI32::new(clip.x, clip.y, clip.width, clip.height);
    if let Some(sel) = doc.selection.clone() {
        let mask = sel.read_rect(rect);
        if let Some(node) = doc.layer_mut(src_layer_id) {
            let mut rgba = node.grid.read_rgba8_rect(rect, false, scratch)?;
            for (px, &m) in rgba.as_chunks_mut::<4>().0.iter_mut().zip(mask.iter()) {
                if m == 255 {
                    px.copy_from_slice(&[0, 0, 0, 0]);
                } else if m > 0 {
                    let keep = 255u32 - u32::from(m);
                    px[3] = ((u32::from(px[3]) * keep + 127) / 255) as u8;
                }
            }
            let thresh = node.meta.mono_threshold.unwrap_or(128);
            node.grid.write_rgba8_rect(&rgba, rect, thresh, scratch)?;
        }
    } else {
        doc.clear_layer(src_layer_id, false)?;
    }

    let name = format!("{} (Selection)", clip.source_layer_name);
    let insert_idx = doc.layer_index(src_layer_id).unwrap_or(0);
    let mut meta = LayerNodeMeta::new_raster(new_layer_id.clone(), name);
    if let Some(src) = doc.layer(src_layer_id) {
        meta.parent_id = src.meta.parent_id.clone();
    }
    doc.add_layer(meta, Some(insert_idx), true, false);
    if let Some(node) = doc.layer_mut(&new_layer_id) {
        let thresh = node.meta.mono_threshold.unwrap_or(128);
        node.grid.write_rgba8_rect(&clip.rgba, rect, thresh, scratch)?;
    }
    let mut before_grids = Vec::new();
    let mut after_grids = Vec::new();
    if let Some(bg) = src_before_grid {
        before_grids.push(bg);
    }
    if let Some(src) = doc.layer(src_layer_id) {
        after_grids.push((src_layer_id.to_string(), src.grid.clone_cow()));
    }
    if let Some(dst) = doc.layer(&new_layer_id) {
        after_grids.push((new_layer_id.clone(), dst.grid.clone_cow()));
    }
    doc.selection = None;
    doc.dirty_for_render = true;
    doc.record_tree_history(
        "selection-move",
        "Move Selection to New Layer",
        Some(new_layer_id.clone()),
        before_layers,
        before_active,
        before_grids,
        after_grids,
        Vec::new(),
        None,
    );
    Ok(Some(new_layer_id))
}

/// Lifts selected pixels off `layer_id` into `doc.selection.floating` (clears under-layer region).
pub fn lift_floating_selection(
    doc: &mut Document,
    layer_id: &str,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<SelectionMetaSnapshot, String> {
    let Some(sel) = doc.selection.clone() else {
        return Ok(SelectionMetaSnapshot::empty());
    };
    if sel.floating.is_some() {
        return Ok(sel.snapshot_meta());
    }
    if let Some(node) = doc.layer(layer_id) {
        if node.meta.locked || !node.meta.layer_type.has_tiles() {
            return Ok(sel.snapshot_meta());
        }
    }
    let Some(clip) = copy_selection(doc, layer_id, scratch)? else {
        return Ok(sel.snapshot_meta());
    };

    // Snapshot source layer tiles before clearing so cancel/commit builds exact CoW deltas
    let before_tiles = {
        let Some(node) = doc.layer(layer_id) else {
            return Err(format!("Layer not found: {layer_id}"));
        };
        node.grid
            .tiles
            .iter()
            .map(|(&c, t)| (c, Some(t.clone())))
            .collect()
    };

    // Clear selected pixels from base layer without recording a separate undo step yet
    let rect = RectI32::new(clip.x, clip.y, clip.width, clip.height);
    let mask = sel.read_rect(rect);
    if let Some(node) = doc.layer_mut(layer_id) {
        let mut rgba = node.grid.read_rgba8_rect(rect, false, scratch)?;
        for (px, &m) in rgba.as_chunks_mut::<4>().0.iter_mut().zip(mask.iter()) {
            if m == 255 {
                px.copy_from_slice(&[0, 0, 0, 0]);
            } else if m > 0 {
                let keep = 255u32 - u32::from(m);
                px[3] = ((u32::from(px[3]) * keep + 127) / 255) as u8;
            }
        }
        let thresh = node.meta.mono_threshold.unwrap_or(128);
        let _ = node.grid.write_rgba8_rect(&rgba, rect, thresh, scratch);
    }

    if let Some(ref mut s) = doc.selection {
        s.floating = Some(FloatingSelection {
            layer_id: layer_id.to_string(),
            orig_x: clip.x,
            orig_y: clip.y,
            x: clip.x,
            y: clip.y,
            width: clip.width,
            height: clip.height,
            rgba: clip.rgba,
            before_tiles,
            version: crate::tiles::allocate_tile_version(),
        });
        s.bump_version();
        doc.dirty_for_render = true;
        return Ok(s.snapshot_meta());
    }
    Ok(SelectionMetaSnapshot::empty())
}

/// Moves an active floating selection to `(new_x, new_y)` (zero pixel copies!).
pub fn move_floating_selection(doc: &mut Document, new_x: i32, new_y: i32) -> SelectionMetaSnapshot {
    if let Some(ref mut sel) = doc.selection {
        if let Some(ref mut fl) = sel.floating {
            fl.x = new_x;
            fl.y = new_y;
            sel.bump_version();
            doc.dirty_for_render = true;
        }
        return sel.snapshot_meta();
    }
    SelectionMetaSnapshot::empty()
}

/// Commits an active floating selection back onto its layer at `(fl.x, fl.y)` with CoW Undo.
pub fn commit_floating_selection(
    doc: &mut Document,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<SelectionMetaSnapshot, String> {
    let Some(mut sel) = doc.selection.take() else {
        return Ok(SelectionMetaSnapshot::empty());
    };
    let Some(fl) = sel.floating.take() else {
        doc.selection = Some(sel);
        return Ok(doc.selection.as_ref().unwrap().snapshot_meta());
    };

    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
    let fl_rect = RectI32::new(fl.x, fl.y, fl.width, fl.height);
    let clipped = fl_rect.intersect(doc_rect);

    if let Some(node) = doc.layer_mut(&fl.layer_id) {
        if !clipped.is_empty() {
            let mut dst = node.grid.read_rgba8_rect(clipped, false, scratch)?;
            let cw = clipped.width as usize;
            let ch = clipped.height as usize;
            let fw = fl.width as usize;
            for ry in 0..ch {
                let sy = (clipped.y + ry as i32 - fl.y) as usize;
                for rx in 0..cw {
                    let sx = (clipped.x + rx as i32 - fl.x) as usize;
                    let si = (sy * fw + sx) * 4;
                    let di = (ry * cw + rx) * 4;
                    let sa = fl.rgba[si + 3] as f32 / 255.0;
                    if sa <= 1e-4 {
                        continue;
                    }
                    let da = dst[di + 3] as f32 / 255.0;
                    let out_a = sa + da * (1.0 - sa);
                    if out_a > 1e-4 {
                        let inv = 1.0 / out_a;
                        let k = da * (1.0 - sa);
                        dst[di] = ((fl.rgba[si] as f32 * sa + dst[di] as f32 * k) * inv)
                            .round()
                            .clamp(0.0, 255.0) as u8;
                        dst[di + 1] = ((fl.rgba[si + 1] as f32 * sa + dst[di + 1] as f32 * k) * inv)
                            .round()
                            .clamp(0.0, 255.0) as u8;
                        dst[di + 2] = ((fl.rgba[si + 2] as f32 * sa + dst[di + 2] as f32 * k) * inv)
                            .round()
                            .clamp(0.0, 255.0) as u8;
                        dst[di + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
                    }
                }
            }
            let thresh = node.meta.mono_threshold.unwrap_or(128);
            let _ = node.grid.write_rgba8_rect(&dst, clipped, thresh, scratch);
        }

        // Build CoW tile deltas against `fl.before_tiles`
        let mut all_coords: std::collections::HashSet<TileCoord> =
            fl.before_tiles.keys().copied().collect();
        all_coords.extend(node.grid.tiles.keys().copied());
        let mut deltas = Vec::new();
        for coord in all_coords {
            let before = fl.before_tiles.get(&coord).cloned().flatten();
            let after = node.grid.tiles.get(&coord).cloned();
            let same = match (&before, &after) {
                (None, None) => true,
                (Some(a), Some(b)) => Arc::ptr_eq(a, b) || a.version == b.version,
                _ => false,
            };
            if !same {
                deltas.push(crate::tiles::CowTileDelta {
                    layer_id: fl.layer_id.clone(),
                    kind: TileKind::Raster,
                    coord,
                    before,
                    after,
                    remote_epoch: node.grid.remote_epochs.get(&coord).copied().unwrap_or(0),
                });
            }
        }
        doc.record_stroke_deltas(
            &fl.layer_id,
            "selection-move",
            "Move Selection",
            deltas,
            None,
            None,
        );
    }

    // Shift selection mask by `(fl.x - fl.orig_x, fl.y - fl.orig_y)`
    let dx = fl.x - fl.orig_x;
    let dy = fl.y - fl.orig_y;
    if dx != 0 || dy != 0 {
        let old_bounds = sel.bounds;
        let old_buf = sel.read_rect(old_bounds);
        let shifted_rect = RectI32::new(
            old_bounds.x + dx,
            old_bounds.y + dy,
            old_bounds.width,
            old_bounds.height,
        );
        sel.combine_rect(shifted_rect, &old_buf, SelectionCombineMode::Replace);
    }

    if sel.is_empty() {
        doc.selection = None;
        Ok(SelectionMetaSnapshot::empty())
    } else {
        let meta = sel.snapshot_meta();
        doc.selection = Some(sel);
        Ok(meta)
    }
}