PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Fix lag when dragging a floating selection with the Move tool
Roberto Moura8352b26c1a66
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 2ed1873a9..0e56af3bc 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -689,11 +689,33 @@ fn render_reduced_with(doc: &Document, b: Rect, w: u32, h: u32, damage: Option<R});debug_assert!(ok.is_ok());}- for (i, p) in acc.iter_mut().enumerate() {- let ((x0, x1), (y0, y1)) = (span(ox0 + i % ow, fw, w), span(oy0 + i / ow, fh, h));- let n = ((y1 - y0) * (x1 - x0)).max(1) as f32;- let a = p[3];- *p = if a > 0.0 { [p[0] / a, p[1] / a, p[2] / a, a / n] } else { [0.0; 4] };+ let col_w: Vec<usize> = (0..ow)+ .map(|x| {+ let (x0, x1) = span(ox0 + x, fw, w);+ (x1 - x0).max(1)+ })+ .collect();+ let norm_row = |row: usize, out: &mut [[f32; 4]]| {+ let (y0, y1) = span(oy0 + row, fh, h);+ let rh = (y1 - y0).max(1);+ for (p, &cw) in out.iter_mut().zip(&col_w) {+ let a = p[3];+ if a > 0.0 {+ let n = (rh * cw) as f32;+ *p = [p[0] / a, p[1] / a, p[2] / a, a / n];+ } else {+ *p = [0.0; 4];+ }+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ acc.par_chunks_mut(ow).enumerate().for_each(|(row, out)| norm_row(row, out));+ }+ #[cfg(target_arch = "wasm32")]+ for (row, out) in acc.chunks_mut(ow).enumerate() {+ norm_row(row, out);}Buffer { rect: out, px: acc }}@@ -1787,6 +1809,27 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Bufferblend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0);return;}+ if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_))+ && let Some(s) = layer.surface()+ && layer.blend == BlendMode::Normal+ && opacity >= 1.0+ && !clipped.iter().any(|c| c.visible)+ && layer.mask.is_none()+ && layer.vector_mask.is_none()+ && text_gamma(layer) == 1.0+ && !psblend::LAB_MIX.with(|l| l.get())+ && backdrop.px.iter().all(|p| p[3] <= 0.0)+ {+ s.read_rgba_into(rect, &mut backdrop.px);+ for p in &mut backdrop.px {+ if p[3] <= 0.0 {+ *p = [0.0; 4];+ } else if p[3] < 1.0 {+ *p = psblend::composite_normal_rgb([0.0; 4], *p, 1.0);+ }+ }+ return;+ }if clipped.is_empty()&& let Some(surf) = pixel_surface(layer){diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/float_cmds.rsindex e5450b233..5680bce58 100644--- a/crates/engine/src/float_cmds.rs+++ b/crates/engine/src/float_cmds.rs@@ -32,6 +32,7 @@ pub struct CutParts {pub layer: LayerId,rest: Surface,piece: Surface,+ piece_bounds: photocraft_geom::Rect,/// The pieces are the layer's mask (`"target":"mask"`), not its pixels.mask: bool,}@@ -55,41 +56,27 @@ impl CutParts {};let fmt = surf.format();let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true);- let full = if fmt == with_alpha { surf.clone() } else { surf.convert(with_alpha) };// A mask has no alpha: it keeps its format, and the cut leaves background colour.- let mut rest = if mask { surf.clone() } else { full.clone() };+ let base = if mask || fmt == with_alpha { surf.clone() } else { surf.convert(with_alpha) };+ let mut rest = base.clone();let mut piece = Surface::new(with_alpha);let fill = !copy && (mask || doc.is_background(layer));// A mask's untouched pixels (its default, e.g. white) move too, so take the whole canvas.- let b = sel.content_bounds().intersect(&if mask { doc.bounds() } else { surf.content_bounds() });+ let b = sel.content_bounds().intersect(&if mask { doc.bounds() } else { base.content_bounds() });if !b.is_empty() {- let n = with_alpha.channels();- let a = n - 1;- let mut rp = full.read_region(b);- let mut pp = rp.clone();- let w = b.width() as usize;- for (i, (p, r)) in pp.chunks_exact_mut(n).zip(rp.chunks_exact_mut(n)).enumerate() {- let k = sel.sample_channel(b.x0 + (i % w) as i32, b.y0 + (i / w) as i32, 0);- if k <= 0.0 {- p.fill(0.0);- } else {- p[a] *= k;- }- if !copy && !fill {- r[a] *= 1.0 - k;- }- }- if !mask {- rest.write_region(b, &rp);- }+ piece = cut_piece(&base, sel, b, with_alpha)?;if fill {- crate::pixels::try_fill_surface(&mut rest, b, background, Some(sel), true)?;+ let opaque_bg = [background[0], background[1], background[2], 1.0];+ crate::pixels::try_fill_surface(&mut rest, b, opaque_bg, Some(sel), false)?;+ if mask {+ rest.prune();+ }+ } else if !copy && !mask {+ crate::pixels::try_clear_surface(&mut rest, b, Some(sel))?;}- rest.prune();- piece.write_region(b, &pp);- piece.prune();}- Ok(Self { layer, rest, piece, mask })+ let piece_bounds = piece.content_bounds();+ Ok(Self { layer, rest, piece, piece_bounds, mask })}/// `doc` with the piece moved by whole pixels (dx, dy) over the cut-out layer.@@ -107,10 +94,14 @@ impl CutParts {} else {l.surface_mut().ok_or_else(|| EngineError::Other("the layer has no pixels to move".into()))?};+ if self.piece_bounds.is_empty() {+ *surf = self.rest.clone();+ return Ok(());+ }let mut out = self.rest.clone();- let piece = photocraft_algo::resample::translate_surface(&self.piece, dx, dy);+ let piece = self.piece.translated(dx, dy, self.piece_bounds);if self.mask {- crate::fill_cmds::composite_over(&mut out, &piece, piece.content_bounds(), None)?;+ crate::fill_cmds::composite_over(&mut out, &piece, self.piece_bounds.translate(dx, dy), None)?;} else {crate::transform_cmds::composite_over(&mut out, &piece);}@@ -119,6 +110,100 @@ impl CutParts {}}+/// Extract the selected pixels of `base` over `b` into a `with_alpha` surface, tile by tile in+/// parallel. Fully selected tiles on an alpha surface share `base`'s `Arc<Tile>` directly.+fn cut_piece(base: &Surface, sel: &Surface, b: photocraft_geom::Rect, with_alpha: PixelFormat) -> Result<Surface> {+ use photocraft_color::{SampleType, read_sample};+ use photocraft_geom::{TILE_SIZE, TileCoord};+ use photocraft_raster::Tile;+ use rayon::prelude::*;++ let mut piece = Surface::new(with_alpha);+ let src_fmt = base.format();+ let same_fmt = src_fmt == with_alpha;+ let n = with_alpha.channels();+ let a = n - 1;+ let dst_bpp = with_alpha.bytes_per_pixel();+ let src_bpp = src_fmt.bytes_per_pixel();+ let sb = with_alpha.sample.bytes();+ let alpha_off = dst_bpp - sb;+ let src_empty_default = same_fmt && base.default_bytes().iter().all(|&v| v == 0);+ let oom = |e| EngineError::Other(format!("not enough memory while floating selection ({e}); the document was not changed"));+ let mut coords = crate::allocation::capacity(b.tiles().count(), "floating selection")?;+ coords.extend(b.tiles());+ let tiles = coords+ .into_par_iter()+ .map(|tc| -> Result<Option<(TileCoord, Arc<Tile>)>> {+ let tr = tc.rect().intersect(&b);+ let mask = crate::fill_cmds::Mask::of(sel, tc);+ if mask.empty(tr) {+ return Ok(None);+ }+ let src_tile = base.tile(tc);+ if same_fmt && src_tile.is_none() && src_empty_default {+ return Ok(None);+ }+ if same_fmt+ && tr == tc.rect()+ && mask.full(tr)+ && let Some(t) = src_tile+ {+ return Ok(Some((tc, t.clone())));+ }+ let src_bytes = src_tile.map_or(base.default_bytes(), |t| t.bytes());+ let mut out = piece.try_default_tile().map_err(oom)?;+ let out_bytes = out.bytes_mut();+ let mut px = [0.0f32; 8];+ let mut has_content = false;+ for y in tr.y0..tr.y1 {+ let row = (y - tc.ty * TILE_SIZE) as usize * TILE_SIZE as usize;+ for x in tr.x0..tr.x1 {+ let k = mask.at(x, y);+ if k <= 0.0 {+ continue;+ }+ let idx = row + (x - tc.tx * TILE_SIZE) as usize;+ let dst_i = idx * dst_bpp;+ let Some(dst_px) = out_bytes.get_mut(dst_i..dst_i + dst_bpp) else { continue };+ let src_i = if src_bytes.len() == src_bpp { 0 } else { idx * src_bpp };+ let Some(src_px) = src_bytes.get(src_i..src_i + src_bpp) else { continue };+ if same_fmt && k >= 1.0 {+ if src_px.iter().any(|&v| v != 0) {+ dst_px.copy_from_slice(src_px);+ has_content = true;+ }+ continue;+ }+ if same_fmt {+ for (c, v) in px.iter_mut().enumerate().take(n) {+ *v = read_sample(src_px, src_fmt.sample, c);+ }+ px[a] *= k;+ } else {+ for (c, v) in px.iter_mut().enumerate().take(a) {+ *v = read_sample(src_px, src_fmt.sample, c);+ }+ px[a] = k;+ }+ if px[a] <= 0.0 {+ continue;+ }+ photocraft_raster::encode_pixel(&with_alpha, &px[..n], dst_px);+ let non_zero = match with_alpha.sample {+ SampleType::U8 => dst_px.get(alpha_off) != Some(&0) || dst_px.iter().any(|&v| v != 0),+ SampleType::U16 => dst_px.get(alpha_off..dst_bpp) != Some(&[0, 0]) || dst_px.iter().any(|&v| v != 0),+ SampleType::F32 => dst_px.iter().any(|&v| v != 0),+ };+ has_content |= non_zero;+ }+ }+ Ok(has_content.then(|| (tc, Arc::new(out))))+ })+ .collect::<Result<Vec<_>>>()?;+ piece.put_tiles(tiles.into_iter().flatten());+ Ok(piece)+}+/// A piece floating `offset` whole pixels from where it was cut, over document `revision`.#[derive(Clone, Debug)]pub struct Floating {diff --git a/crates/engine/src/float_cmds/tests.rs b/crates/engine/src/float_cmds/tests.rsindex bb2ba5b91..441a32d0a 100644--- a/crates/engine/src/float_cmds/tests.rs+++ b/crates/engine/src/float_cmds/tests.rs@@ -189,3 +189,63 @@ fn cutting_an_untouched_part_of_the_mask_moves_it_and_leaves_the_background_coloassert!((mask_at(&s, 12, 12) - 0.5).abs() < 0.01, "the hole takes the background colour");assert_eq!(mask_at(&s, 40, 12), 0.0);}++#[test]+fn float_shares_interior_tiles_on_cut_and_place() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 1024, "height": 1024})).unwrap();+ s.tools.background = [0.2, 0.4, 0.8, 1.0];+ let id = s.active().unwrap().active_layer.unwrap();+ // Paint non-uniform pixels so original tiles are distinct.+ s.edit("pattern", |doc, _| {+ let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap();+ for ty in 0..4 {+ for tx in 0..4 {+ surf.write_pixel(tx * 256 + 5, ty * 256 + 5, &[tx as f32 * 0.25, ty as f32 * 0.25, 0.5, 1.0]);+ }+ }+ Ok(())+ })+ .unwrap();+ // Select (100..900)^2, which fully covers interior tiles (1, 1) and (2, 2).+ s.execute("select.rect", json!({"x": 100, "y": 100, "width": 800, "height": 800})).unwrap();+ s.execute("select.float", json!({})).unwrap();+ let st = s.active().unwrap();+ let orig = st.doc.layer(id).unwrap().surface().unwrap();+ let parts = &floating(st).unwrap().parts;+ let tc1 = photocraft_geom::TileCoord { tx: 1, ty: 1 };+ let tc2 = photocraft_geom::TileCoord { tx: 2, ty: 2 };+ // Interior tiles of `piece` share the original layer's Arc<Tile>.+ assert!(Arc::ptr_eq(orig.tile(tc1).unwrap(), parts.piece.tile(tc1).unwrap()));+ assert!(Arc::ptr_eq(orig.tile(tc2).unwrap(), parts.piece.tile(tc2).unwrap()));+ // Interior tiles of the Background hole in `rest` share one solid fill Arc<Tile>.+ assert!(Arc::ptr_eq(parts.rest.tile(tc1).unwrap(), parts.rest.tile(tc2).unwrap()));+ // Moving by a whole tile (256, 0) shares the interior tile directly in the preview document.+ let shown = displayed(st, (256, 0)).unwrap();+ let shown_surf = shown.layer(id).unwrap().surface().unwrap();+ let moved_tc = photocraft_geom::TileCoord { tx: 2, ty: 1 };+ assert!(Arc::ptr_eq(orig.tile(tc1).unwrap(), shown_surf.tile(moved_tc).unwrap()));+}++#[test]+fn float_feathered_selection_preserves_partial_alpha_across_depths() {+ for depth in [8, 16, 32] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 120, "height": 80, "background": "transparent", "depth": depth})).unwrap();+ let id = s.active().unwrap().active_layer.unwrap();+ s.edit("paint", |doc, _| {+ doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 55, 80), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ s.execute("select.rect", json!({"x": 20, "y": 20, "width": 30, "height": 30, "feather": 4.0})).unwrap();+ s.execute("select.float", json!({"dx": 40, "dy": 0})).unwrap();+ s.execute("select.drop", json!({})).unwrap();+ let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap();+ // Center of moved piece is opaque red; center of hole is transparent; feathered edge has partial alpha.+ assert!(surf.rgba(75, 35)[3] > 0.95, "{depth}-bit moved center");+ assert!(surf.rgba(35, 35)[3] < 0.05, "{depth}-bit hole center");+ let edge_a = surf.rgba(60, 35)[3];+ assert!(edge_a > 0.1 && edge_a < 0.9, "{depth}-bit feathered edge alpha={edge_a}");+ }+}diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rsindex b046de03b..c03d3dc61 100644--- a/crates/engine/src/pixels.rs+++ b/crates/engine/src/pixels.rs@@ -239,16 +239,21 @@ pub(crate) fn try_fill_surface(s: &mut Surface, area: Rect, color: [f32; 4], sellet fmt = s.format();// Coverage 1 of an opaque colour replaces the colour (and the alpha, unless it is kept).let opaque = color[3] == 1.0 && (!lock_transparency || !fmt.alpha) && selection.is_none_or(|m| m.format().sample != photocraft_color::SampleType::F32);- let solid = opaque.then(|| {- let mut enc = [0.0f32; 8];- let n = photocraft_raster::from_rgba_into(&fmt, [color[0], color[1], color[2], 1.0], &mut enc);- s.solid_tile(enc.get(..n).unwrap_or(&[]))- });+ let mut enc = [0.0f32; 8];+ let enc_len = opaque.then(|| photocraft_raster::from_rgba_into(&fmt, [color[0], color[1], color[2], 1.0], &mut enc));+ let solid = enc_len.map(|n| s.solid_tile(enc.get(..n).unwrap_or(&[])));let whole = |full: bool| solid.as_ref().filter(|_| full).map(|t| TileEdit::Put(t.clone()));edit_tiles(s, area, selection, "filling pixels", whole, |k, px| {if k <= 0.0 {return false;}+ if k >= 1.0+ && let Some(m) = enc_len+ && let Some(src) = enc.get(..px.len().min(m))+ {+ px.copy_from_slice(src);+ return true;+ }fill_pixel(&fmt, px, color, k, lock_transparency);true})@@ -294,9 +299,7 @@ pub(crate) fn try_clear_surface(s: &mut Surface, area: Rect, selection: Option<&px.fill(0.0);}true- })?;- s.prune();- Ok(())+ })}/// A whole-tile shortcut of [`edit_tiles`].@@ -331,6 +334,7 @@ fn edit_tiles(coords.extend(area.tiles());// Untouched pixels read as the default where the surface has no tile.let blank = if coords.iter().any(|&tc| s.tile(tc).is_none()) { Some(s.try_default_tile().map_err(oom)?) } else { None };+ let dp = s.default_bytes();let surf = &*s;let edits = coords.into_par_iter()@@ -371,7 +375,11 @@ fn edit_tiles(}}}- Ok(out.map(|t| (tc, Some(Arc::new(t)))))+ Ok(match out {+ Some(t) if bpp > 0 && t.bytes().chunks_exact(bpp).all(|p| p == dp) => current.map(|_| (tc, None)),+ Some(t) => Some((tc, Some(Arc::new(t)))),+ None => None,+ })}).collect::<crate::Result<Vec<_>>>()?;for (tc, tile) in edits.into_iter().flatten() {diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rsindex 2452e7443..baead5674 100644--- a/crates/engine/src/transform_cmds.rs+++ b/crates/engine/src/transform_cmds.rs@@ -511,13 +511,124 @@ pub(crate) fn refresh_text(doc: &Document, l: &mut Layer) {}/// Normal-blend `top` over `dst` (both straight alpha, same format).+/// Works tile by tile in parallel on `top`'s allocated tiles: fully opaque tiles share their+/// `Arc<Tile>` directly with `dst`, and opaque/transparent pixels on border tiles copy encoded+/// bytes without a whole-region `f32` round trip.pub(crate) fn composite_over(dst: &mut Surface, top: &Surface) {+ use photocraft_color::{SampleType, read_sample};+ use photocraft_geom::TileCoord;+ use photocraft_raster::Tile;+ use rayon::prelude::*;+ use std::sync::Arc;++ let fmt = dst.format();+ let n = fmt.channels();+ if n == 0 || !fmt.alpha || top.format() != fmt {+ return;+ }+ let a = n - 1;+ if top.default_pixel().get(a).is_none_or(|&ta| ta <= 0.0) {+ let top_tiles: Vec<(TileCoord, Arc<Tile>)> = top.tiles().map(|(&tc, t)| (tc, t.clone())).collect();+ if top_tiles.is_empty() {+ return;+ }+ let bpp = fmt.bytes_per_pixel();+ let sb = fmt.sample.bytes();+ let alpha_off = bpp - sb;+ let dst_empty_default = dst.default_bytes().iter().all(|&b| b == 0);+ let dst_ref = &*dst;+ let edits: Vec<(TileCoord, Arc<Tile>)> = top_tiles+ .into_par_iter()+ .filter_map(|(tc, top_tile)| {+ let tb = top_tile.bytes();+ let all_opaque = match fmt.sample {+ SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) == Some(&u8::MAX)),+ SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) == Some(&[u8::MAX, u8::MAX])),+ SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) == 1.0),+ };+ if all_opaque {+ return Some((tc, top_tile));+ }+ let all_transparent = match fmt.sample {+ SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) == Some(&0)),+ SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) == Some(&[0, 0])),+ SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) <= 0.0),+ };+ if all_transparent {+ return None;+ }+ if dst_ref.tile(tc).is_none() && dst_empty_default {+ let clean_zero = match fmt.sample {+ SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) != Some(&0) || px.iter().all(|&b| b == 0)),+ SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) != Some(&[0, 0]) || px.iter().all(|&b| b == 0)),+ SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) > 0.0 || px.iter().all(|&b| b == 0)),+ };+ if clean_zero {+ return Some((tc, top_tile));+ }+ }+ let mut out_tile = match dst_ref.tile(tc) {+ Some(dt) => (**dt).clone(),+ None => dst_ref.try_default_tile().ok()?,+ };+ let mut tp = [0.0f32; 8];+ let mut dp = [0.0f32; 8];+ for (out_px, top_px) in out_tile.bytes_mut().chunks_exact_mut(bpp).zip(tb.chunks_exact(bpp)) {+ match fmt.sample {+ SampleType::U8 => {+ let ta_b = top_px[alpha_off];+ if ta_b == 0 {+ continue;+ }+ if ta_b == u8::MAX {+ out_px.copy_from_slice(top_px);+ continue;+ }+ }+ SampleType::U16 => {+ if top_px[alpha_off..bpp] == [0, 0] {+ continue;+ }+ if top_px[alpha_off..bpp] == [u8::MAX, u8::MAX] {+ out_px.copy_from_slice(top_px);+ continue;+ }+ }+ SampleType::F32 => {+ let ta = read_sample(top_px, SampleType::F32, a);+ if ta <= 0.0 {+ continue;+ }+ if ta == 1.0 {+ out_px.copy_from_slice(top_px);+ continue;+ }+ }+ }+ for c in 0..n {+ tp[c] = read_sample(top_px, fmt.sample, c);+ dp[c] = read_sample(out_px, fmt.sample, c);+ }+ let (ta, da) = (tp[a], dp[a]);+ let oa = ta + da * (1.0 - ta);+ if oa > 0.0 {+ for c in 0..a {+ dp[c] = (tp[c] * ta + dp[c] * da * (1.0 - ta)) / oa;+ }+ }+ dp[a] = oa;+ photocraft_raster::encode_pixel(&fmt, &dp[..n], out_px);+ }+ Some((tc, Arc::new(out_tile)))+ })+ .collect();+ dst.put_tiles(edits);+ return;+ }let b = top.content_bounds();if b.is_empty() {return;}- let n = dst.format().channels();- let a = n - 1;let t = top.read_region(b);let mut d = dst.read_region(b);for (dp, tp) in d.chunks_exact_mut(n).zip(t.chunks_exact(n)) {diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rsindex 958ab38b5..b524542b6 100644--- a/crates/raster/src/lib.rs+++ b/crates/raster/src/lib.rs@@ -132,19 +132,18 @@ fn sample_buffer<'a>(channels: usize, stack: &'a mut [f32], heap: &'a mut Vec<f3#[derive(Default)]struct UniformTiles {/// Per source tile (by address): the index of its value's tile in `canonical`, or `None`.- of: std::collections::HashMap<*const Tile, Option<usize>>,+ of: std::collections::HashMap<usize, Option<usize>>,canonical: Vec<Arc<Tile>>,}impl UniformTiles {/// The tile to share for a target reading window `r` of `s`, when every tile under it holds/// one and the same pixel value (`r` must lie on existing tiles).- fn window(&mut self, s: &Surface, r: Rect) -> Option<Arc<Tile>> {- let bpp = s.format.bytes_per_pixel();+ fn window(&self, s: &Surface, r: Rect) -> Option<Arc<Tile>> {let mut found = None;for c in r.tiles() {let t = s.tiles.get(&c)?;- let k = self.value_of(t, bpp)?;+ let k = (*self.of.get(&(Arc::as_ptr(t) as usize))?)?;if found.is_some_and(|f| f != k) {return None;}@@ -154,7 +153,8 @@ impl UniformTiles {}fn value_of(&mut self, t: &Arc<Tile>, bpp: usize) -> Option<usize> {- if let Some(k) = self.of.get(&Arc::as_ptr(t)) {+ let key = Arc::as_ptr(t) as usize;+ if let Some(k) = self.of.get(&key) {return *k;}let mut px = t.data.chunks_exact(bpp);@@ -165,7 +165,7 @@ impl UniformTiles {self.canonical.len() - 1}});- self.of.insert(Arc::as_ptr(t), k);+ self.of.insert(key, k);k}}@@ -830,6 +830,9 @@ impl Surface {let moved = content.translate(dx, dy);let targets: std::collections::BTreeSet<TileCoord> = sources().flat_map(|(c, _)| c.rect().translate(dx, dy).intersect(&moved).tiles()).collect();let mut uniform = UniformTiles::default();+ for (_, t) in sources() {+ uniform.value_of(t, bpp);+ }// The fill row: one tile row of the default pixel, so the regions a shift vacates// fill with bulk copies (empty when the default is zero — the tile starts zeroed).@@ -846,7 +849,7 @@ impl Surface {// One tile row of the default pixel, to compare a finished tile with a row at a time.let default_row = self.default_pixel.repeat(TILE_SIZE.unsigned_abs() as usize);- for dc in targets {+ let build_target = |dc: TileCoord| -> Option<(TileCoord, Arc<Tile>)> {let dr = dc.rect();let sr = dr.translate(dx.saturating_neg(), dy.saturating_neg());// Every pixel of the target comes from a source tile (none from the default pixel).@@ -858,10 +861,7 @@ impl Surface {&& sr.tiles().all(|sc| self.tiles.contains_key(&sc));if covered && let Some(shared) = uniform.window(self, sr) {// A tile of only the default pixel is left out, as `prune` would.- if shared.data.get(..bpp) != Some(&*self.default_pixel) {- out.tiles.insert(dc, shared);- }- continue;+ return (shared.data.get(..bpp) != Some(&*self.default_pixel)).then_some((dc, shared));}let mut tile = Tile { data: vec![0u8; (TILE_SIZE * TILE_SIZE) as usize * bpp].into_boxed_slice() };@@ -943,9 +943,16 @@ impl Surface {}// A target that got only default pixels isn't stored, as `prune` would drop it. Checked// after the copy, a row at a time: a tile with content stops at its first such row.- if tile.data.chunks(default_row.len()).any(|row| row != default_row) {- out.tiles.insert(dc, Arc::new(tile));- }+ tile.data.chunks(default_row.len()).any(|row| row != default_row).then(|| (dc, Arc::new(tile)))+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ out.tiles = targets.into_par_iter().filter_map(build_target).collect();+ }+ #[cfg(target_arch = "wasm32")]+ {+ out.tiles = targets.into_iter().filter_map(build_target).collect();}out}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex d2e535f3f..6f5df7ab7 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1631,9 +1631,9 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible:damage = Some(crate::adjust_preview::live_switch_damage(app, raw_key, r, visible));}let preview_key = raw_key ^ display_key;- // The Navigator may draw this texture only while it holds the plain document (no live- // preview, which can be composited only where the view is).- if raw_key == 0 {+ // The Navigator may draw this texture while it holds the plain document or a drag preview+ // that updates the full texture (not an adjustment preview composited only where the view is).+ if raw_key == 0 || navigator_waits_for_drag(app, idx) {app.navigator_plain.insert(id);} else {app.navigator_plain.remove(&id);diff --git a/crates/ui-egui/src/move_ui.rs b/crates/ui-egui/src/move_ui.rsindex fb49b0247..f9e5dd758 100644--- a/crates/ui-egui/src/move_ui.rs+++ b/crates/ui-egui/src/move_ui.rs@@ -213,6 +213,9 @@ fn floating_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, ufloating: true,});}+ if offset == (0, 0) && app.move_preview.as_ref().is_none_or(|p| p.offsets.is_empty()) {+ return None;+ }let st = app.session.documents().get(idx)?;let shown = app.move_preview.as_ref()?.offsets.last() != Some(&offset);if shown {@@ -535,4 +538,20 @@ mod tests {drag(&mut app, [16.0, 16.0], [26.0, 16.0], egui::Modifiers::NONE);assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 58, 16) == 1.0, "the whole layer moved");}++ #[test]+ fn floating_selection_does_not_snap_to_its_own_starting_outline_or_preview_at_zero() {+ let (mut app, _id) = selected_pixels(8);+ app.ui.extras.snap = true;+ app.ui.view.snap_to.document_bounds = false;+ let m = egui::Modifiers::NONE;+ crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m);+ assert!(super::display_doc(&mut app, 0).is_none(), "no preview composite at offset (0, 0) before the pointer moves");+ // A small 2 px move within the snap radius must move immediately instead of snapping back to (0, 0).+ crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 18.0, y: 17.0, pressure: 1.0 }, m);+ assert_eq!(super::floating_offset(&app), Some((2, 1)), "small drag moves without snapping to own selection bounds");+ assert!(super::display_doc(&mut app, 0).is_some(), "preview is shown once offset is non-zero");+ crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 18.0, y: 17.0 }, m);+ assert_eq!(offset(&app), Some((2, 1)));+ }}diff --git a/crates/ui-egui/src/navigator_gpu_tests.rs b/crates/ui-egui/src/navigator_gpu_tests.rsindex 454181ff7..0fa423a69 100644--- a/crates/ui-egui/src/navigator_gpu_tests.rs+++ b/crates/ui-egui/src/navigator_gpu_tests.rs@@ -72,6 +72,20 @@ fn navigator_draws_the_gpu_canvas_texture_and_follows_edits() {assert!(near(preview_px(&mut h, 0.75, 0.5), [0, 0, 255]), "right half now blue");assert!(!h.state().navigator_textures.contains_key(&id));+ // Dragging the selected pixels with the Move tool keeps the Navigator on the GPU texture+ // without falling back to a full-document CPU thumbnail composite on the UI thread.+ h.state_mut().ui.tool = crate::state::Tool::Move;+ crate::canvas::tool_event(h.state_mut(), crate::canvas::ToolEvent::Down { x: 250.0, y: 150.0, pressure: 1.0 }, egui::Modifiers::NONE);+ crate::canvas::tool_event(h.state_mut(), crate::canvas::ToolEvent::Move { x: 150.0, y: 150.0, pressure: 1.0 }, egui::Modifiers::NONE);+ h.run_steps(4);+ assert!(h.state().navigator_gpu.contains_key(&id), "Navigator stays on GPU canvas during Move drag");+ assert!(!h.state().navigator_textures.contains_key(&id), "no CPU thumbnail built during Move drag");+ crate::canvas::tool_event(h.state_mut(), crate::canvas::ToolEvent::Up { x: 150.0, y: 150.0 }, egui::Modifiers::NONE);+ h.state_mut().run("select.drop", json!({})).unwrap();+ h.state_mut().run("edit.undo", json!({})).unwrap();+ h.state_mut().run("select.deselect", json!({})).unwrap();+ h.run_steps(4);+// A flipped view draws on the CPU: the Navigator goes back to its CPU thumbnail.h.state_mut().ui.view.flip_horizontal = true;h.run_steps(6);diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rsindex 5efbe128b..6703fbd42 100644--- a/crates/ui-egui/src/snap_ui.rs+++ b/crates/ui-egui/src/snap_ui.rs@@ -250,7 +250,7 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) {// A guide never snaps to itself (or other guides).targets = targets.filtered(|k| k != SnapKind::Guide);}- if matches!(gesture, Gesture::SelectionMove { .. }) {+ if matches!(gesture, Gesture::SelectionMove { .. }) || crate::move_ui::moves_selected_pixels_with(app, tool) {// A moving selection never snaps back to where it started.targets = targets.filtered(|k| k != SnapKind::Selection);}