Cut/copy/paste raster data

This commit is contained in:
Skyler Lehmkuhl
2026-03-02 00:01:18 -05:00
parent 1c3f794958
commit 87815fe379
11 changed files with 911 additions and 145 deletions
@@ -82,6 +82,14 @@ pub enum ClipboardContent {
/// Notes: (start_time, note, velocity, duration) — times relative to selection start
notes: Vec<(f64, u8, u8, f64)>,
},
/// Raw pixel data from a raster layer selection.
/// Pixels are sRGB-encoded premultiplied RGBA, `width × height × 4` bytes —
/// the same in-memory format as `RasterKeyframe::raw_pixels`.
RasterPixels {
pixels: Vec<u8>,
width: u32,
height: u32,
},
}
impl ClipboardContent {
@@ -176,6 +184,9 @@ impl ClipboardContent {
// No IDs to regenerate, just clone
(ClipboardContent::MidiNotes { notes: notes.clone() }, id_map)
}
ClipboardContent::RasterPixels { pixels, width, height } => {
(ClipboardContent::RasterPixels { pixels: pixels.clone(), width: *width, height: *height }, id_map)
}
ClipboardContent::Shapes { shapes } => {
// Regenerate shape IDs
let new_shapes: Vec<Shape> = shapes
@@ -257,6 +268,62 @@ impl ClipboardManager {
None
}
/// Copy raster pixels to the system clipboard as an image.
///
/// `pixels` must be sRGB-encoded premultiplied RGBA (`w × h × 4` bytes).
/// Converts to straight-alpha RGBA8 for arboard. Silently ignores errors
/// (arboard is a temporary integration point and will be replaced).
pub fn try_set_raster_image(&mut self, pixels: &[u8], width: u32, height: u32) {
let Some(system) = self.system.as_mut() else { return };
// Unpremultiply: sRGB-premul → straight RGBA8 for the system clipboard.
let straight: Vec<u8> = pixels.chunks_exact(4).flat_map(|p| {
let a = p[3];
if a == 0 {
[0u8, 0, 0, 0]
} else {
let inv = 255.0 / a as f32;
[
(p[0] as f32 * inv).round().min(255.0) as u8,
(p[1] as f32 * inv).round().min(255.0) as u8,
(p[2] as f32 * inv).round().min(255.0) as u8,
a,
]
}
}).collect();
let img = arboard::ImageData {
width: width as usize,
height: height as usize,
bytes: std::borrow::Cow::Owned(straight),
};
let _ = system.set_image(img);
}
/// Try to read an image from the system clipboard.
///
/// Returns sRGB-encoded premultiplied RGBA pixels on success, or `None` if
/// no image is available. Silently ignores errors.
pub fn try_get_raster_image(&mut self) -> Option<(Vec<u8>, u32, u32)> {
let img = self.system.as_mut()?.get_image().ok()?;
let width = img.width as u32;
let height = img.height as u32;
// Premultiply: straight RGBA8 → sRGB-premul.
let premul: Vec<u8> = img.bytes.chunks_exact(4).flat_map(|p| {
let a = p[3];
if a == 0 {
[0u8, 0, 0, 0]
} else {
let scale = a as f32 / 255.0;
[
(p[0] as f32 * scale).round() as u8,
(p[1] as f32 * scale).round() as u8,
(p[2] as f32 * scale).round() as u8,
a,
]
}
}).collect();
Some((premul, width, height))
}
/// Check if there's content available to paste
pub fn has_content(&mut self) -> bool {
if self.internal.is_some() {
@@ -8,6 +8,82 @@ use std::collections::HashSet;
use uuid::Uuid;
use vello::kurbo::{Affine, BezPath};
/// Shape of a raster pixel selection, in canvas pixel coordinates.
#[derive(Clone, Debug)]
pub enum RasterSelection {
/// Axis-aligned rectangle: (x0, y0, x1, y1), x1 >= x0, y1 >= y0.
Rect(i32, i32, i32, i32),
/// Closed freehand lasso polygon.
Lasso(Vec<(i32, i32)>),
}
impl RasterSelection {
/// Bounding box as (x0, y0, x1, y1).
pub fn bounding_rect(&self) -> (i32, i32, i32, i32) {
match self {
Self::Rect(x0, y0, x1, y1) => (*x0, *y0, *x1, *y1),
Self::Lasso(pts) => {
let x0 = pts.iter().map(|p| p.0).min().unwrap_or(0);
let y0 = pts.iter().map(|p| p.1).min().unwrap_or(0);
let x1 = pts.iter().map(|p| p.0).max().unwrap_or(0);
let y1 = pts.iter().map(|p| p.1).max().unwrap_or(0);
(x0, y0, x1, y1)
}
}
}
/// Returns true if the given canvas pixel is inside the selection.
pub fn contains_pixel(&self, px: i32, py: i32) -> bool {
match self {
Self::Rect(x0, y0, x1, y1) => px >= *x0 && px < *x1 && py >= *y0 && py < *y1,
Self::Lasso(pts) => point_in_polygon(px, py, pts),
}
}
}
/// Even-odd point-in-polygon test for integer coordinates.
fn point_in_polygon(px: i32, py: i32, polygon: &[(i32, i32)]) -> bool {
let n = polygon.len();
if n < 3 { return false; }
let mut inside = false;
let mut j = n - 1;
for i in 0..n {
let (xi, yi) = (polygon[i].0 as f64, polygon[i].1 as f64);
let (xj, yj) = (polygon[j].0 as f64, polygon[j].1 as f64);
let x = px as f64;
let y = py as f64;
if ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi) {
inside = !inside;
}
j = i;
}
inside
}
/// A pasted or cut selection that floats above the canvas until committed.
///
/// While a floating selection is alive `raw_pixels` on the target keyframe is
/// left in a "pre-composite" state (hole punched for cut, unchanged for copy).
/// The floating pixels are rendered as an overlay. Committing composites them
/// into `raw_pixels` and records a `RasterStrokeAction` for undo.
#[derive(Clone, Debug)]
pub struct RasterFloatingSelection {
/// sRGB-encoded premultiplied RGBA, width × height × 4 bytes.
pub pixels: Vec<u8>,
pub width: u32,
pub height: u32,
/// Top-left position in canvas pixel coordinates.
pub x: i32,
pub y: i32,
/// Which raster layer and keyframe this float belongs to.
pub layer_id: Uuid,
pub time: f64,
/// Snapshot of `raw_pixels` before the cut/paste was initiated, used for
/// undo (via `RasterStrokeAction`) when the float is committed, and for
/// Cancel (Escape) to restore the canvas without creating an undo entry.
pub canvas_before: Vec<u8>,
}
/// Tracks the most recently selected thing(s) across the entire document.
///
/// Lightweight overlay on top of per-domain selection state. Tells consumers
@@ -69,6 +145,16 @@ pub struct Selection {
/// Currently selected clip instances
selected_clip_instances: Vec<Uuid>,
/// Active raster pixel selection (marquee or lasso outline).
/// Transient UI state — not persisted.
#[serde(skip)]
pub raster_selection: Option<RasterSelection>,
/// Floating raster selection waiting to be committed or cancelled.
/// Transient UI state — not persisted.
#[serde(skip)]
pub raster_floating: Option<RasterFloatingSelection>,
}
impl Selection {
@@ -79,6 +165,8 @@ impl Selection {
selected_edges: HashSet::new(),
selected_faces: HashSet::new(),
selected_clip_instances: Vec::new(),
raster_selection: None,
raster_floating: None,
}
}
@@ -302,6 +390,8 @@ impl Selection {
self.selected_edges.clear();
self.selected_faces.clear();
self.selected_clip_instances.clear();
self.raster_selection = None;
self.raster_floating = None;
}
/// Check if selection is empty
+16 -21
View File
@@ -41,6 +41,8 @@ pub enum Tool {
Erase,
/// Smudge tool - smudge/blend raster pixels
Smudge,
/// Lasso select tool - freehand selection on raster layers
SelectLasso,
}
/// Region select mode
@@ -75,6 +77,17 @@ pub enum ToolState {
points: Vec<crate::raster_layer::StrokePoint>,
},
/// Drawing a freehand lasso selection on a raster layer
DrawingRasterLasso {
points: Vec<(i32, i32)>,
},
/// Drawing a rectangular marquee selection on a raster layer
DrawingRasterMarquee {
start: (i32, i32),
current: (i32, i32),
},
/// Dragging selected objects
DraggingSelection {
start_pos: Point,
@@ -224,6 +237,7 @@ impl Tool {
Tool::Split => "Split",
Tool::Erase => "Erase",
Tool::Smudge => "Smudge",
Tool::SelectLasso => "Lasso Select",
}
}
@@ -245,6 +259,7 @@ impl Tool {
Tool::Split => "split.svg",
Tool::Erase => "erase.svg",
Tool::Smudge => "smudge.svg",
Tool::SelectLasso => "lasso.svg",
}
}
@@ -272,29 +287,9 @@ impl Tool {
match layer_type {
None | Some(LayerType::Vector) => Tool::all(),
Some(LayerType::Audio) | Some(LayerType::Video) => &[Tool::Select, Tool::Split],
Some(LayerType::Raster) => &[Tool::Select, Tool::Draw, Tool::Erase, Tool::Smudge, Tool::Eyedropper],
Some(LayerType::Raster) => &[Tool::Select, Tool::SelectLasso, Tool::Draw, Tool::Erase, Tool::Smudge, Tool::Eyedropper],
_ => &[Tool::Select],
}
}
/// Get keyboard shortcut hint
pub fn shortcut_hint(self) -> &'static str {
match self {
Tool::Select => "V",
Tool::Draw => "P",
Tool::Transform => "Q",
Tool::Rectangle => "R",
Tool::Ellipse => "E",
Tool::PaintBucket => "B",
Tool::Eyedropper => "I",
Tool::Line => "L",
Tool::Polygon => "G",
Tool::BezierEdit => "A",
Tool::Text => "T",
Tool::RegionSelect => "S",
Tool::Split => "C",
Tool::Erase => "X",
Tool::Smudge => "U",
}
}
}