darkly 0.5.0

A GPU-native paint engine on wgpu: brushes, layers, blend modes, masks, selections, and undo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
//! GPU-side undo snapshot storage.
//!
//! Manages shared scratch textures (pre-operation snapshot, in-flight workspace
//! for save+modify+commit) and produces per-action [`UndoRegionEntry`] values
//! that own their own pixel data — no shared ring buffer.
//!
//! # Lifetime model
//!
//! Each undo entry owns its pixels via [`EntryPixels`]:
//!
//! - **`Pending { staging }`** — VRAM-resident. The `wgpu::Buffer` that backs
//!   the async readback. Holds until either (a) the readback completes and the
//!   entry transitions to `Ready`, dropping the buffer, or (b) a restore
//!   happens first, in which case the buffer feeds `copy_buffer_to_texture`
//!   directly (GPU-to-GPU, no readback wait).
//! - **`Ready(Vec<u8>)`** — DRAM-resident, unpadded row layout. The steady
//!   state for most actions, since most commits' readbacks finish before any
//!   restore is requested.
//!
//! When the action drops (max_steps overflow, byte-cap overflow, redo cleared,
//! teardown), the staging buffer or `Vec` drops with it. No shared storage, no
//! eviction at the storage layer, no aliasing.
//!
//! # Coordinate frame
//!
//! All public methods take [`CanvasRect`] for rect parameters and a
//! [`CanvasFrame`] for the source/target texture. Translation to texture-local
//! coordinates happens internally, immediately before each `copy_texture_*`
//! call. The scratch is texture-aligned (scratch[(x, y)] holds the pre-op
//! snapshot of source[(x, y)]) but the *metadata* — `Snapshot.saved` and
//! `UndoRegionEntry.canvas_rect` — is in canvas coords so it remains valid
//! across mid-stroke layer growth (the Storage Frame Rule).
//!
//! [`save_region`](Self::save_region) returns a [`Snapshot`] token. The token
//! is required by [`commit_region`](Self::commit_region) and
//! [`restore_from_scratch`](Self::restore_from_scratch) — you can't commit
//! without saving first. Commits validate (in debug) that the commit rect is
//! contained in the snapshot's saved rect.

use crate::coord::CanvasRect;
use crate::gpu::atlas::CanvasFrame;
use crate::gpu::readback::ReadbackRequest;
use crate::layer::LayerId;
use std::cell::RefCell;
use std::rc::Rc;

/// Token returned by [`RegionScratch::save_region`]. Carries the saved
/// rect (in canvas coords) and format; required to commit or restore from
/// the scratch.
///
/// `Copy` because it's just a small struct, and several flows hold it as a
/// field across deferred GPU work.
#[derive(Copy, Clone, Debug)]
pub struct Snapshot {
    pub saved: CanvasRect,
    pub format: wgpu::TextureFormat,
}

/// Alignment required by wgpu for bytes_per_row in buffer↔texture copies.
const COPY_ROW_ALIGNMENT: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;

/// Per-entry pixel storage, hybrid VRAM/DRAM.
///
/// Single-threaded — the engine drives commits, restores, and readback
/// completion from the same thread, so `Rc<RefCell<…>>` rather than
/// `Arc<Mutex<…>>`. WASM is single-threaded by construction; native tests
/// run with `--test-threads=1`.
pub enum EntryPixels {
    /// Async readback in flight. Holds the committed pixels in two
    /// sibling buffers — WebGPU disallows combining `MAP_READ` and
    /// `COPY_SRC` on a single buffer, so the readback and restore paths
    /// need separate VRAM. Both get filled from the same scratch in the
    /// commit encoder, so their contents are byte-identical.
    Pending {
        /// MAP_READ | COPY_DST — drives the async readback that flips the
        /// entry to `Ready`.
        readback: wgpu::Buffer,
        /// COPY_DST | COPY_SRC — source for the GPU-to-GPU restore path
        /// when a restore arrives before the readback completes. Both
        /// buffers drop together when the entry transitions to `Ready`.
        staging: wgpu::Buffer,
    },
    /// Readback completed, pixels live on the host heap (WASM linear memory
    /// in production, native DRAM in tests). The buffer layout is
    /// `unpadded_row_bytes * height` — restoring re-pads into a temp upload
    /// buffer because `copy_buffer_to_texture` requires
    /// `COPY_BYTES_PER_ROW_ALIGNMENT` rows.
    Ready(Vec<u8>),
}

/// Metadata + owned pixels for a single undo region. No longer `Clone` —
/// each action owns exactly one entry, and the `Rc<RefCell<…>>` would
/// duplicate the pixel-ownership relationship if cloned.
pub struct UndoRegionEntry {
    pub layer_id: LayerId,
    /// Region in canvas-space pixel coords. Stable across layer growth.
    pub canvas_rect: CanvasRect,
    pub format: wgpu::TextureFormat,
    /// Bytes per row in the buffer (padded to COPY_ROW_ALIGNMENT).
    pub padded_row_bytes: u32,
    /// Bytes per row without padding (`width * bpp`).
    pub unpadded_row_bytes: u32,
    /// VRAM-equivalent byte cost of this entry (padded rows × height). Used
    /// for the [`crate::undo::UndoStack`] memory cap — treated as an upper
    /// bound even when the entry has transitioned to `Ready` (whose unpadded
    /// `Vec` may be slightly smaller). Conservative is correct here.
    pub byte_size: u64,
    /// Shared cell so the readback completion handler can flip
    /// `Pending → Ready` after the action has been pushed onto the undo
    /// stack. Cloned once into the readback request's context at commit
    /// time; the handler holds that clone, the entry holds the other.
    pub pixels: Rc<RefCell<EntryPixels>>,
}

/// Shared scratch + per-entry storage producer for GPU undo regions.
///
/// Holds only the in-flight workspace textures (one RGBA8, one R8) used as
/// pre-op snapshots and commit intermediaries. Each undo entry owns its own
/// pixel data — there is no shared ring buffer. Storage lifetime equals
/// action lifetime, so eviction happens at the policy layer
/// ([`crate::undo::UndoStack`]) rather than down here.
pub struct RegionScratch {
    // --- Scratch textures (one per format) ---
    scratch_rgba: wgpu::Texture,
    scratch_r8: wgpu::Texture,
    scratch_width: u32,
    scratch_height: u32,
}

impl RegionScratch {
    pub fn new(device: &wgpu::Device, canvas_width: u32, canvas_height: u32) -> Self {
        let scratch_rgba = Self::create_scratch(
            device,
            canvas_width,
            canvas_height,
            wgpu::TextureFormat::Rgba8Unorm,
            "scratch-rgba",
        );
        let scratch_r8 = Self::create_scratch(
            device,
            canvas_width,
            canvas_height,
            wgpu::TextureFormat::R8Unorm,
            "scratch-r8",
        );

        RegionScratch {
            scratch_rgba,
            scratch_r8,
            scratch_width: canvas_width,
            scratch_height: canvas_height,
        }
    }

    /// Grow scratch textures so they can fit a rect of at least `(w, h)`.
    /// No-op if the current scratch is already large enough. Reallocation
    /// is rare in practice — only happens when a save rect exceeds canvas
    /// bounds (paste-extent layer transform, oversized stroke, etc.).
    ///
    /// Call this once before encoding `save_region` for any rect that
    /// might exceed the current scratch dimensions; routine canvas-bounded
    /// callers can skip it (`save_region` doesn't grow on its own to keep
    /// borrowing simple at call sites that already hold an immutable
    /// borrow into `self`).
    pub fn ensure_scratch_capacity(&mut self, device: &wgpu::Device, w: u32, h: u32) {
        if w <= self.scratch_width && h <= self.scratch_height {
            return;
        }
        let new_w = w.max(self.scratch_width);
        let new_h = h.max(self.scratch_height);
        self.realloc_scratch_pair(device, new_w, new_h, None);
    }

    /// Reallocate the scratch textures to `(new_w, new_h)` and copy the
    /// existing scratch contents into the new textures at
    /// `(dst_offset_x, dst_offset_y)`. Used during mid-stroke layer
    /// growth: the scratch holds the pre-stroke snapshot, which must
    /// remain anchored to the same canvas-space pixels even though the
    /// layer's local-coord origin has shifted.
    ///
    /// The newly-allocated regions outside the copied rect start at the
    /// GPU default (0 = transparent for RGBA, 0 = full transparency for R8).
    pub fn grow_scratch_preserving(
        &mut self,
        device: &wgpu::Device,
        encoder: &mut wgpu::CommandEncoder,
        new_w: u32,
        new_h: u32,
        dst_offset_x: u32,
        dst_offset_y: u32,
    ) {
        if new_w <= self.scratch_width
            && new_h <= self.scratch_height
            && dst_offset_x == 0
            && dst_offset_y == 0
        {
            return;
        }
        let target_w = new_w.max(self.scratch_width);
        let target_h = new_h.max(self.scratch_height);
        self.realloc_scratch_pair(
            device,
            target_w,
            target_h,
            Some((encoder, dst_offset_x, dst_offset_y)),
        );
    }

    /// Reallocate both scratch textures (RGBA8 + R8) to `(new_w, new_h)`.
    /// When `copy` is `Some((encoder, dst_x, dst_y))`, the existing
    /// scratch contents are copied into the new textures at the given
    /// offset before the old textures are dropped. `(scratch_width,
    /// scratch_height)` is updated to `(new_w, new_h)` regardless of copy.
    fn realloc_scratch_pair(
        &mut self,
        device: &wgpu::Device,
        new_w: u32,
        new_h: u32,
        copy: Option<(&mut wgpu::CommandEncoder, u32, u32)>,
    ) {
        let pairs = [
            (
                &mut self.scratch_rgba,
                wgpu::TextureFormat::Rgba8Unorm,
                "scratch-rgba",
            ),
            (
                &mut self.scratch_r8,
                wgpu::TextureFormat::R8Unorm,
                "scratch-r8",
            ),
        ];
        let copy_w = self.scratch_width;
        let copy_h = self.scratch_height;
        let (encoder_opt, dst_offset_x, dst_offset_y) = match copy {
            Some((enc, x, y)) => (Some(enc), x, y),
            None => (None, 0, 0),
        };
        let do_copy = encoder_opt.is_some() && copy_w > 0 && copy_h > 0;
        // The encoder borrow has to be threaded through the loop body; an
        // `Option<&mut _>` doesn't `Copy`, so reborrow via `as_deref_mut`
        // each iteration.
        let mut encoder_opt = encoder_opt;
        for (field, format, label) in pairs {
            let new_tex = Self::create_scratch(device, new_w, new_h, format, label);
            if do_copy {
                let encoder = encoder_opt
                    .as_deref_mut()
                    .expect("do_copy implies encoder present");
                // Clear the whole new texture to the format's pre-stroke default
                // first (white for an R8 mask, transparent otherwise); the copy
                // below then overwrites the preserved region, leaving the newly-
                // grown area at its correct default rather than zero (black).
                let new_view = new_tex.create_view(&wgpu::TextureViewDescriptor::default());
                encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("scratch-grow-clear"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: &new_view,
                        resolve_target: None,
                        depth_slice: None,
                        ops: wgpu::Operations {
                            load: wgpu::LoadOp::Clear(Self::scratch_default_clear(format)),
                            store: wgpu::StoreOp::Store,
                        },
                    })],
                    ..Default::default()
                });
                encoder.copy_texture_to_texture(
                    wgpu::TexelCopyTextureInfo {
                        texture: field,
                        mip_level: 0,
                        origin: wgpu::Origin3d::ZERO,
                        aspect: wgpu::TextureAspect::All,
                    },
                    wgpu::TexelCopyTextureInfo {
                        texture: &new_tex,
                        mip_level: 0,
                        origin: wgpu::Origin3d {
                            x: dst_offset_x,
                            y: dst_offset_y,
                            z: 0,
                        },
                        aspect: wgpu::TextureAspect::All,
                    },
                    wgpu::Extent3d {
                        width: copy_w,
                        height: copy_h,
                        depth_or_array_layers: 1,
                    },
                );
            }
            *field = new_tex;
        }
        self.scratch_width = new_w;
        self.scratch_height = new_h;
    }

    /// Copy a canvas-space rect from a layer/mask texture into the scratch
    /// texture and return a [`Snapshot`] token.
    ///
    /// The scratch is texture-aligned to `source`: the snapshot lands at the
    /// same layer-local `(x, y)` it came from on the source. This lets a
    /// later [`commit_region`](Self::commit_region) commit a sub-rect of the
    /// snapshot at its own canvas position.
    ///
    /// Grows the scratch textures on demand if the translated rect exceeds
    /// the current scratch capacity (e.g. on a paste-extent layer or a
    /// layer that was just grown past canvas). Callers that batch many
    /// saves at known dimensions may still pre-call
    /// [`ensure_scratch_capacity`](Self::ensure_scratch_capacity) to avoid
    /// the per-call branch, but it is no longer required for correctness.
    pub fn save_region(
        &mut self,
        device: &wgpu::Device,
        encoder: &mut wgpu::CommandEncoder,
        source: &CanvasFrame<'_>,
        format: wgpu::TextureFormat,
        canvas_rect: CanvasRect,
    ) -> Snapshot {
        let layer_rect = source
            .canvas_to_layer_rect(canvas_rect)
            .expect("save_region rect must overlap the source's canvas extent");
        self.ensure_scratch_capacity(device, layer_rect.x1(), layer_rect.y1());
        let scratch = self.scratch_for(format);

        encoder.copy_texture_to_texture(
            wgpu::TexelCopyTextureInfo {
                texture: source.texture,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: layer_rect.x0(),
                    y: layer_rect.y0(),
                    z: 0,
                },
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyTextureInfo {
                texture: scratch,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: layer_rect.x0(),
                    y: layer_rect.y0(),
                    z: 0,
                },
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::Extent3d {
                width: layer_rect.width,
                height: layer_rect.height,
                depth_or_array_layers: 1,
            },
        );

        Snapshot {
            saved: canvas_rect,
            format,
        }
    }

    /// Copy a sub-rect of the saved scratch region into a freshly-allocated
    /// per-entry staging buffer, returning the new undo entry plus a
    /// [`ReadbackRequest`] for the async `Pending → Ready` transition.
    ///
    /// The caller is responsible for submitting the request to its
    /// [`crate::gpu::readback::ReadbackScheduler`] paired with a context
    /// that, on completion, assigns the extracted pixels into
    /// `entry.pixels`'s `RefCell` — flipping the entry to `Ready` and
    /// dropping the staging buffer.
    ///
    /// # Lifetime contract for the staging buffers
    ///
    /// Two VRAM buffers are allocated:
    /// - **`readback`** (`MAP_READ | COPY_DST`) — fed straight from scratch
    ///   in this encoder, then handed to the scheduler. When `map_async`
    ///   resolves, the readback completion handler flips
    ///   `entry.pixels` to `Ready(vec)`, dropping both buffers.
    /// - **`staging`** (`COPY_DST | COPY_SRC`) — also fed from scratch in
    ///   this encoder, kept alive in `entry.pixels` so a restore-while-
    ///   pending can feed `copy_buffer_to_texture` GPU-to-GPU.
    ///
    /// WebGPU forbids combining `MAP_READ` and `COPY_SRC` on a single
    /// buffer, which is why the split exists. The cost is one extra
    /// `copy_texture_to_buffer` per commit and one extra `byte_size` of
    /// VRAM per *pending* entry — both transient (the readback resolves
    /// in 1-3 frames in production).
    ///
    /// `wgpu::Buffer` is Arc-backed; the readback request holds its own
    /// ref to `readback`, so dropping the original handle on transition
    /// to `Ready` is safe even if the request's `map_async` callback
    /// hasn't fully unwound.
    ///
    /// `canvas_rect` must be contained in `snapshot.saved`. In debug builds
    /// this is asserted at runtime; release builds will silently read whatever
    /// scratch contents lie at the rect (likely uninitialised junk from a
    /// prior op), so don't rely on the assert being inert.
    pub fn commit_region(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        layer_id: LayerId,
        source: &CanvasFrame<'_>,
        snapshot: &Snapshot,
        canvas_rect: CanvasRect,
    ) -> (UndoRegionEntry, ReadbackRequest) {
        debug_assert!(
            snapshot.saved.contains(canvas_rect),
            "commit_region rect {:?} not contained in snapshot.saved {:?}",
            canvas_rect,
            snapshot.saved,
        );
        let layer_rect = source
            .canvas_to_layer_rect(canvas_rect)
            .expect("commit_region rect must overlap the source's canvas extent");
        let bpp = snapshot.format.block_copy_size(None).unwrap_or(1);
        let unpadded_row_bytes = layer_rect.width * bpp;
        let padded_row_bytes = padded_row(layer_rect.width, bpp);
        let byte_size = padded_row_bytes as u64 * layer_rect.height as u64;

        let (readback, staging) = allocate_pending_buffers(device, byte_size);
        let scratch = self.scratch_for(snapshot.format);
        let texel_layout = wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(padded_row_bytes),
            rows_per_image: Some(layer_rect.height),
        };
        let extent = wgpu::Extent3d {
            width: layer_rect.width,
            height: layer_rect.height,
            depth_or_array_layers: 1,
        };
        let origin = wgpu::Origin3d {
            x: layer_rect.x0(),
            y: layer_rect.y0(),
            z: 0,
        };

        // Scratch is texture-aligned to the source (see `save_region`): the
        // snapshot of pixels at layer-space `(x, y)` lives at scratch `(x, y)`.
        // Two writes — one per buffer. WebGPU doesn't let a single buffer be
        // both MAP_READ and COPY_SRC, so the readback and the in-flight
        // GPU-to-GPU restore each need their own.
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: scratch,
                mip_level: 0,
                origin,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback,
                layout: texel_layout,
            },
            extent,
        );
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: scratch,
                mip_level: 0,
                origin,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &staging,
                layout: texel_layout,
            },
            extent,
        );

        let pixels = Rc::new(RefCell::new(EntryPixels::Pending {
            readback: readback.clone(),
            staging,
        }));
        let request = ReadbackRequest::from_buffer(
            readback,
            layer_rect.height,
            padded_row_bytes,
            unpadded_row_bytes,
        );

        let entry = UndoRegionEntry {
            layer_id,
            canvas_rect,
            format: snapshot.format,
            padded_row_bytes,
            unpadded_row_bytes,
            byte_size,
            pixels,
        };
        (entry, request)
    }

    /// Restore `entry`'s saved pixels into `target`, producing the forward
    /// entry (the pre-restore state) + its async-readback request for the
    /// inverse op. The constant-extent combinator of
    /// [`capture_region`](Self::capture_region) +
    /// [`upload_region`](Self::upload_region): capture the entry's rect, then
    /// upload, in one encoder (capture sequences before the overwrite). Use the
    /// two halves directly when the target texture is realloc'd between them
    /// (image rescale's extent change).
    pub fn restore_region(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        entry: &UndoRegionEntry,
        target: &CanvasFrame<'_>,
    ) -> (UndoRegionEntry, ReadbackRequest) {
        let (forward, request) = self.capture_region(
            encoder,
            device,
            entry.layer_id,
            entry.format,
            target,
            entry.canvas_rect,
        );
        self.upload_region(encoder, device, entry, target);
        (forward, request)
    }

    /// Capture `capture_rect` of `target`'s **current** pixels into a fresh
    /// undo entry (the forward / opposite-direction state) plus its async
    /// readback request.
    ///
    /// This is the first half of an undo restore: snapshot what's there now so
    /// the inverse operation can put it back. Pairs with
    /// [`upload_region`](Self::upload_region); a caller that needs to realloc
    /// the target texture (image rescale changes a node's extent) can do so
    /// *between* the two calls — capture reads the old extent, upload writes
    /// the new. For constant-extent restores pass `capture_rect ==
    /// entry.canvas_rect`; the pair then behaves like the old `restore_region`.
    ///
    /// The capture commands must be encoded (and, across an extent change,
    /// submitted) before the upload overwrites / the realloc replaces the
    /// target — same encoder preserves order for the constant-extent case.
    pub fn capture_region(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        layer_id: LayerId,
        format: wgpu::TextureFormat,
        target: &CanvasFrame<'_>,
        capture_rect: CanvasRect,
    ) -> (UndoRegionEntry, ReadbackRequest) {
        let layer_rect = target
            .canvas_to_layer_rect(capture_rect)
            .expect("capture_region rect must overlap the target's canvas extent");
        let bpp = format.block_copy_size(None).unwrap_or(1);
        let unpadded_row_bytes = layer_rect.width * bpp;
        let padded_row_bytes = padded_row(layer_rect.width, bpp);
        let byte_size = padded_row_bytes as u64 * layer_rect.height as u64;
        let origin = wgpu::Origin3d {
            x: layer_rect.x0(),
            y: layer_rect.y0(),
            z: 0,
        };
        let extent = wgpu::Extent3d {
            width: layer_rect.width,
            height: layer_rect.height,
            depth_or_array_layers: 1,
        };
        let texel_layout = wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(padded_row_bytes),
            rows_per_image: Some(layer_rect.height),
        };

        let (readback, staging) = allocate_pending_buffers(device, byte_size);
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: target.texture,
                mip_level: 0,
                origin,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback,
                layout: texel_layout,
            },
            extent,
        );
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: target.texture,
                mip_level: 0,
                origin,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &staging,
                layout: texel_layout,
            },
            extent,
        );

        let pixels = Rc::new(RefCell::new(EntryPixels::Pending {
            readback: readback.clone(),
            staging,
        }));
        let request = ReadbackRequest::from_buffer(
            readback,
            layer_rect.height,
            padded_row_bytes,
            unpadded_row_bytes,
        );
        let forward = UndoRegionEntry {
            layer_id,
            canvas_rect: capture_rect,
            format,
            padded_row_bytes,
            unpadded_row_bytes,
            byte_size,
            pixels,
        };
        (forward, request)
    }

    /// Upload `entry`'s saved pixels back into `target` at `entry.canvas_rect`
    /// — the second half of an undo restore. The `Ready` branch allocates a
    /// one-shot mapped-at-creation upload buffer so the copy stays in the
    /// encoder's command stream (`queue.write_texture` would re-order to the
    /// start of the next submit and stomp a same-encoder forward capture).
    ///
    /// `target` must already be sized so `entry.canvas_rect` maps fully into
    /// it (the caller realloc's the node texture for an extent-changing
    /// restore before calling this).
    pub fn upload_region(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        device: &wgpu::Device,
        entry: &UndoRegionEntry,
        target: &CanvasFrame<'_>,
    ) {
        let layer_rect = target
            .canvas_to_layer_rect(entry.canvas_rect)
            .expect("upload_region entry must overlap the target's canvas extent");
        let origin = wgpu::Origin3d {
            x: layer_rect.x0(),
            y: layer_rect.y0(),
            z: 0,
        };
        let extent = wgpu::Extent3d {
            width: layer_rect.width,
            height: layer_rect.height,
            depth_or_array_layers: 1,
        };
        let padded_row_bytes = entry.padded_row_bytes;
        let unpadded_row_bytes = entry.unpadded_row_bytes;
        let byte_size = entry.byte_size;
        let height = layer_rect.height;
        let texel_layout = wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(padded_row_bytes),
            rows_per_image: Some(height),
        };

        let pixels_borrow = entry.pixels.borrow();
        match &*pixels_borrow {
            EntryPixels::Pending { staging, .. } => {
                encoder.copy_buffer_to_texture(
                    wgpu::TexelCopyBufferInfo {
                        buffer: staging,
                        layout: texel_layout,
                    },
                    wgpu::TexelCopyTextureInfo {
                        texture: target.texture,
                        mip_level: 0,
                        origin,
                        aspect: wgpu::TextureAspect::All,
                    },
                    extent,
                );
            }
            EntryPixels::Ready(vec) => {
                // Re-pad the unpadded `Vec` into a fresh mapped-at-creation
                // upload buffer. `copy_buffer_to_texture` requires
                // bytes_per_row to be COPY_BYTES_PER_ROW_ALIGNMENT-aligned;
                // the `Ready` storage drops the padding for efficiency, so
                // we add it back here. The buffer is short-lived — the
                // encoder's submit takes the Arc-backed ref until the GPU
                // is done with it; the Rust handle drops at the end of
                // this scope.
                let upload = device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("undo-region-upload"),
                    size: byte_size,
                    usage: wgpu::BufferUsages::COPY_SRC,
                    mapped_at_creation: true,
                });
                {
                    let mut mapped = upload.slice(..).get_mapped_range_mut();
                    let unpadded_row = unpadded_row_bytes as usize;
                    let padded_row = padded_row_bytes as usize;
                    if unpadded_row == padded_row {
                        let n = vec.len().min(mapped.len());
                        mapped.slice(..n).copy_from_slice(&vec[..n]);
                    } else {
                        for row in 0..height as usize {
                            let src_off = row * unpadded_row;
                            let dst_off = row * padded_row;
                            mapped
                                .slice(dst_off..dst_off + unpadded_row)
                                .copy_from_slice(&vec[src_off..src_off + unpadded_row]);
                        }
                    }
                }
                upload.unmap();
                encoder.copy_buffer_to_texture(
                    wgpu::TexelCopyBufferInfo {
                        buffer: &upload,
                        layout: texel_layout,
                    },
                    wgpu::TexelCopyTextureInfo {
                        texture: target.texture,
                        mip_level: 0,
                        origin,
                        aspect: wgpu::TextureAspect::All,
                    },
                    extent,
                );
            }
        }
    }

    /// Restore a region directly from the scratch texture to the target,
    /// without going through the per-entry buffer. Used by `cancel_floating()`
    /// to undo the source region clear.
    ///
    /// `canvas_rect` must be contained in `snapshot.saved` — the scratch only
    /// holds the snapshot at that footprint; reading outside it would pull in
    /// uninitialised pixels from a prior op.
    pub fn restore_from_scratch(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        snapshot: &Snapshot,
        target: &CanvasFrame<'_>,
        canvas_rect: CanvasRect,
    ) {
        debug_assert!(
            snapshot.saved.contains(canvas_rect),
            "restore_from_scratch rect {:?} not contained in snapshot.saved {:?}",
            canvas_rect,
            snapshot.saved,
        );
        let layer_rect = target
            .canvas_to_layer_rect(canvas_rect)
            .expect("restore_from_scratch rect must overlap the target's canvas extent");
        let origin = wgpu::Origin3d {
            x: layer_rect.x0(),
            y: layer_rect.y0(),
            z: 0,
        };
        encoder.copy_texture_to_texture(
            wgpu::TexelCopyTextureInfo {
                texture: self.scratch_for(snapshot.format),
                mip_level: 0,
                origin,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyTextureInfo {
                texture: target.texture,
                mip_level: 0,
                origin,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::Extent3d {
                width: layer_rect.width,
                height: layer_rect.height,
                depth_or_array_layers: 1,
            },
        );
    }

    /// Reallocate scratch textures when the canvas size changes.
    pub fn resize_scratch(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        if width == self.scratch_width && height == self.scratch_height {
            return;
        }
        self.scratch_rgba = Self::create_scratch(
            device,
            width,
            height,
            wgpu::TextureFormat::Rgba8Unorm,
            "scratch-rgba",
        );
        self.scratch_r8 = Self::create_scratch(
            device,
            width,
            height,
            wgpu::TextureFormat::R8Unorm,
            "scratch-r8",
        );
        self.scratch_width = width;
        self.scratch_height = height;
    }

    /// Create a texture view for the scratch texture of the given format.
    /// Used by `DiffRectPass` to compare pre-stroke state against current canvas.
    pub fn scratch_view(&self, format: wgpu::TextureFormat) -> wgpu::TextureView {
        self.scratch_for(format)
            .create_view(&wgpu::TextureViewDescriptor::default())
    }

    /// Canvas dimensions of the scratch textures.
    pub fn scratch_dimensions(&self) -> (u32, u32) {
        (self.scratch_width, self.scratch_height)
    }

    // --- Internal ---

    fn scratch_for(&self, format: wgpu::TextureFormat) -> &wgpu::Texture {
        match format {
            wgpu::TextureFormat::R8Unorm => &self.scratch_r8,
            _ => &self.scratch_rgba,
        }
    }

    fn create_scratch(
        device: &wgpu::Device,
        width: u32,
        height: u32,
        format: wgpu::TextureFormat,
        label: &str,
    ) -> wgpu::Texture {
        device.create_texture(&wgpu::TextureDescriptor {
            label: Some(label),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::TEXTURE_BINDING
                // RENDER_ATTACHMENT so a grow can clear the newly-added region
                // to the format's default before the old content is copied in.
                | wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        })
    }

    /// The pre-stroke value a freshly-grown region of a scratch texture holds,
    /// mirroring the live texture's default fill: R8 masks default to white
    /// (255 = reveal), everything else to transparent/zero. Getting this wrong
    /// for an R8 mask corrupts undo — the grown region would restore to black.
    fn scratch_default_clear(format: wgpu::TextureFormat) -> wgpu::Color {
        match format {
            wgpu::TextureFormat::R8Unorm => wgpu::Color::WHITE,
            _ => wgpu::Color::TRANSPARENT,
        }
    }
}

/// Compute the row byte count padded to wgpu's copy alignment.
fn padded_row(width: u32, bytes_per_pixel: u32) -> u32 {
    let unpadded = width * bytes_per_pixel;
    unpadded.div_ceil(COPY_ROW_ALIGNMENT) * COPY_ROW_ALIGNMENT
}

/// Allocate the readback + staging buffer pair for a `Pending` entry.
/// WebGPU disallows mixing `MAP_READ` and `COPY_SRC` on one buffer, so the
/// readback (async DRAM transition) and the staging (GPU-to-GPU restore
/// fallback while the readback is in flight) live in separate VRAM
/// allocations.
fn allocate_pending_buffers(device: &wgpu::Device, byte_size: u64) -> (wgpu::Buffer, wgpu::Buffer) {
    let readback = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("undo-region-readback"),
        size: byte_size,
        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
        mapped_at_creation: false,
    });
    let staging = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("undo-region-staging"),
        size: byte_size,
        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
        mapped_at_creation: false,
    });
    (readback, staging)
}

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

    #[test]
    fn padded_row_alignment() {
        // 128 pixels × 4 bpp = 512 bytes, already aligned to 256.
        assert_eq!(padded_row(128, 4), 512);
        // 100 pixels × 4 bpp = 400 bytes → next multiple of 256 = 512.
        assert_eq!(padded_row(100, 4), 512);
        // 64 pixels × 1 bpp = 64 bytes → 256.
        assert_eq!(padded_row(64, 1), 256);
        // 256 pixels × 1 bpp = 256 bytes, already aligned.
        assert_eq!(padded_row(256, 1), 256);
        // 1 pixel × 4 bpp = 4 bytes → 256.
        assert_eq!(padded_row(1, 4), 256);
    }
}