rust_widgets 2.8.4

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Batch rendering primitives.
//!
//! Provides types for organizing draw commands into batches that can be
//! recorded once and replayed efficiently by the renderer.

use crate::compat::{fmt, HashMap, String, Vec};

use crate::core::{Color, Font, HorizontalAlignment, ObjectId, Point, Rect, Size};
use crate::render::{
    RenderCommand, ShapedText, SoftwareRenderConfig, SoftwareSurface, TextMetrics,
};

use super::paint::{route_command_to_surface, PaintBackend, SoftwarePaintBackend};

/// A zero-copy [`PaintBackend`] view over a borrowed [`SoftwareSurface`].
///
/// # Why this exists (D09-RENDER-05)
///
/// `SoftwarePaintBackend::replay` has to read its own `batch_state` while painting
/// into its own `surface`. Borrowing `self` for both is rejected by the compiler,
/// and the historical workaround was to `clone()` the whole batch state — which
/// copied every batch and every image regardless of which batch was replayed.
/// Passing the surface alone as `&mut SoftwareSurface` would split the borrow, but
/// the surface has no `PaintBackend` impl of its own. This view supplies one, so
/// the replay path can paint through the surface while the batch maps stay
/// borrowed immutably. Because the adapter is `#[repr(transparent)]`, its address
/// is the address of the referenced surface: the cast is sound and free.
#[repr(transparent)]
struct SurfacePaintBackend<'a>(&'a mut SoftwareSurface);

impl PaintBackend for SurfacePaintBackend<'_> {
    fn begin_frame(&mut self, clear: Color) {
        self.0.begin_frame(clear);
    }
    fn end_frame(&mut self) {
        self.0.end_frame();
    }
    fn execute_command(&mut self, command: &RenderCommand) {
        // Delegate to the backend's own command match so the two paths cannot drift;
        // reproducing the match here would be a second copy of the same routing.
        route_command_to_surface(self.0, command);
    }
    fn size(&self) -> Size {
        self.0.size()
    }
    fn set_size(&mut self, size: Size) {
        self.0.resize(size);
    }
    fn dpi_scale(&self) -> f32 {
        self.0.dpi_scale()
    }
    fn set_dpi_scale(&mut self, dpi_scale: f32) {
        self.0.set_dpi_scale(dpi_scale);
    }
    fn measure_text(&self, text: &str, font: &Font) -> TextMetrics {
        self.0.measure_text(text, font)
    }
    fn shape_text(&self, text: &str, font: &Font) -> ShapedText {
        self.0.shape_text(text, font)
    }
    fn frame_rgba(&self) -> &[u8] {
        self.0.frame_rgba()
    }
    fn apply_render_config(&mut self, config: SoftwareRenderConfig) {
        self.0.apply_render_config(config);
    }
    fn render_config(&self) -> SoftwareRenderConfig {
        self.0.render_config()
    }
}

/// Opaque identifier for a recorded batch of draw commands.
///
/// A `BatchId` is created when a batch is recorded and can later be
/// used to replay that batch without re-recording the individual commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BatchId(pub u64);

impl BatchId {
    /// Creates a new `BatchId` from a raw u64 value.
    pub const fn new(id: u64) -> Self {
        Self(id)
    }

    /// Returns the raw u64 value backing this identifier.
    pub const fn get(&self) -> u64 {
        self.0
    }
}

impl From<u64> for BatchId {
    fn from(id: u64) -> Self {
        Self(id)
    }
}

/// Errors that can occur during batch recording operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BatchError {
    /// Attempted to record a command without an open batch.
    /// Call `begin_batch()` first.
    NoActiveBatch,
}

impl fmt::Display for BatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BatchError::NoActiveBatch => {
                write!(f, "called record() without an open batch; call begin_batch() first")
            }
        }
    }
}

impl core::error::Error for BatchError {}

/// A single draw command that can be recorded into a batch.
///
/// Each variant describes a primitive operation the renderer can replay.
/// Commands are replayed in the order they were recorded, so later commands
/// paint over earlier ones. Two commands are stateful rather than immediate:
/// [`BatchCommand::Translate`] and [`BatchCommand::SetOpacity`] accumulate into
/// the replay transform and affect every *subsequent* command in the batch,
/// exactly like their counterparts in an immediate-mode draw list.
#[derive(Debug, Clone)]
pub enum BatchCommand {
    /// Fill a rectangle with a solid colour.
    ///
    /// `color`'s alpha is multiplied by the active opacity, and the rectangle
    /// is offset by the active translation.
    FillRect {
        /// Target rectangle in batch-local pixel coordinates.
        rect: Rect,
        /// Fill colour.
        color: Color,
    },
    /// Stroke a rectangular border.
    ///
    /// Translated by the active offset; `width` is in pixels and is truncated
    /// to an integer by the replay path.
    StrokeRect {
        /// Rectangle whose outline is stroked.
        rect: Rect,
        /// Stroke colour, with alpha scaled by the active opacity.
        color: Color,
        /// Stroke width in pixels.
        width: f32,
    },
    /// Draw a line between two points.
    ///
    /// Both endpoints are offset by the active translation; `width` is in
    /// pixels and is truncated to an integer by the replay path.
    DrawLine {
        /// Start point, in batch-local pixel coordinates.
        from: Point,
        /// End point, in batch-local pixel coordinates.
        to: Point,
        /// Stroke colour, with alpha scaled by the active opacity.
        color: Color,
        /// Stroke width in pixels.
        width: f32,
    },
    /// Draw an image identified by its resource id.
    ///
    /// The replay path looks the id up in the backend's image cache, which
    /// must already contain raw RGBA bytes for it; an unknown id logs a warning
    /// and the command is dropped. The per-command `opacity` is multiplied by
    /// the active opacity and, when the product is below `1.0`, baked into the
    /// image's alpha bytes before drawing.
    DrawImage {
        /// Destination rectangle, offset by the active translation.
        rect: Rect,
        /// Cache key of the source image.
        image_id: ObjectId,
        /// Multiplier in `0.0..=1.0` applied to the image's alpha channel.
        opacity: f32,
    },
    /// Draw a clipped region of an image.
    ///
    /// # Deprecated behaviour
    ///
    /// The current replay implementation drops this command and logs a warning,
    /// because the image cache stores raw pixel bytes without the source
    /// dimensions needed to compute the source rectangle. Record it only if a
    /// future backend is expected to support cropping.
    DrawImageSubrect {
        /// Destination rectangle on the surface.
        dest: Rect,
        /// Sub-rectangle of the source image to draw.
        source: Rect,
        /// Cache key of the source image.
        image_id: ObjectId,
        /// Multiplier in `0.0..=1.0` applied to the image's alpha channel.
        opacity: f32,
    },
    /// Draw text at the given position.
    ///
    /// Replay renders with the batch's fixed default font family and
    /// `font_size`, left-aligned, so the recorded text carries no font or
    /// alignment of its own.
    DrawText {
        /// Baseline start point, offset by the active translation.
        position: Point,
        /// Text to draw.
        text: String,
        /// Text colour, with alpha scaled by the active opacity.
        color: Color,
        /// Font size in logical points.
        font_size: f32,
    },
    /// Push a clipping rectangle – subsequent commands are clipped.
    ///
    /// Translated by the active offset, and intersected with any enclosing
    /// clip. Must be balanced by a matching [`BatchCommand::PopClip`].
    PushClip {
        /// Clip rectangle in batch-local pixel coordinates.
        rect: Rect,
    },
    /// Pop the most recent clipping rectangle.
    PopClip,
    /// Apply a translation offset to all subsequent commands.
    ///
    /// The offsets accumulate rather than replace, and survive until the end of
    /// the batch: there is no "reset translation" command. Recorded clips are
    /// not affected retroactively.
    Translate {
        /// Additional X offset in pixels, added to the current translation.
        dx: f32,
        /// Additional Y offset in pixels, added to the current translation.
        dy: f32,
    },
    /// Apply an opacity multiplier to all subsequent commands.
    ///
    /// The multiplier is applied cumulatively (it multiplies the running
    /// value) and only affects alpha-bearing primitives, i.e. fills, strokes,
    /// lines, text, and images.
    SetOpacity {
        /// Multiplier in `0.0..=1.0`; `1.0` leaves alpha unchanged.
        opacity: f32,
    },
}

/// Trait implemented by renderers that can record and replay draw batches.
///
/// # Usage
///
/// ```text
/// fn render(batcher: &mut impl BatchRenderer) -> Result<(), BatchError> {
///     let batch_id = batcher.begin_batch();
///     batcher.record(BatchCommand::FillRect {
///         rect: Rect::new(0, 0, 100, 100),
///         color: Color::rgb(255, 0, 0),
///     })?;
///     batcher.end_batch();
///     batcher.replay(batch_id);
///     Ok(())
/// }
/// ```
pub trait BatchRenderer {
    /// Opens a new, empty batch and returns its identifier.
    ///
    /// Identifiers are allocated monotonically per renderer and are never
    /// reused, so a stale id simply becomes "not found" rather than aliasing a
    /// newer batch. Only one batch is open at a time: calling this while
    /// another batch is open abandons the previous one without closing it, and
    /// subsequent [`BatchRenderer::record`] calls go to the new batch.
    fn begin_batch(&mut self) -> BatchId;

    /// Closes the batch opened by the last [`BatchRenderer::begin_batch`].
    ///
    /// The recorded commands are retained for later
    /// [`BatchRenderer::replay`]; nothing is drawn here. Recording after this
    /// call fails with `BatchError::NoActiveBatch`. Calling it with no open
    /// batch is a no-op.
    fn end_batch(&mut self);

    /// Appends one command to the currently open batch.
    ///
    /// Commands are stored verbatim and in order; no drawing happens until
    /// [`BatchRenderer::replay`] is called.
    ///
    /// # Errors
    ///
    /// Returns `BatchError::NoActiveBatch` when there is no open batch, i.e.
    /// [`BatchRenderer::begin_batch`] was not called or
    /// [`BatchRenderer::end_batch`] has already closed it.
    fn record(&mut self, cmd: BatchCommand) -> Result<(), BatchError>;

    /// Re-draws a previously recorded batch immediately.
    ///
    /// Commands are executed in recorded order, so later commands overdraw
    /// earlier ones. Batches are not consumed and can be replayed repeatedly.
    /// Replaying an id that was never created or has been destroyed is a
    /// no-op.
    fn replay(&mut self, id: BatchId);

    /// Removes a batch and discards its recorded commands.
    ///
    /// If `id` is the batch currently being recorded, recording is closed as
    /// well, so subsequent [`BatchRenderer::record`] calls fail. Unknown ids
    /// are ignored. Ids are not recycled, so `id` never becomes valid again.
    fn destroy_batch(&mut self, id: BatchId);

    /// Returns `true` while `id` still refers to a live batch.
    ///
    /// A batch is live from its [`BatchRenderer::begin_batch`] until
    /// [`BatchRenderer::destroy_batch`].
    fn contains_batch(&self, id: BatchId) -> bool;

    /// Returns the number of live batches, including any currently open one.
    fn batch_count(&self) -> usize;
}

/// Default font family used when replaying a `DrawText` batch command.
const BATCH_DEFAULT_FONT_FAMILY: &str = "Arial";

/// Extension data held alongside the batch implementation on
/// [`SoftwarePaintBackend`].
///
/// This struct is stored as a field of the backend and provides all
/// the bookkeeping needed to satisfy the `BatchRenderer` trait.
#[derive(Debug, Clone)]
pub(crate) struct BatchState {
    /// Incrementing counter used to generate fresh `BatchId` values.
    next_id: u64,
    /// Active batch being recorded, if any.
    current_batch: Option<BatchId>,
    /// All recorded batches, keyed by `BatchId`.
    batches: HashMap<BatchId, Vec<BatchCommand>>,
    /// Optional image data cache mapping `ObjectId` → RGBA pixel bytes.
    /// Populated externally before replay so that `DrawImage` /
    /// `DrawImageSubrect` commands can be translated into `RenderCommand`s.
    pub(crate) images: HashMap<ObjectId, Vec<u8>>,
}

impl BatchState {
    /// Creates a fresh, empty batch state.
    pub(crate) fn new() -> Self {
        Self { next_id: 0, current_batch: None, batches: HashMap::new(), images: HashMap::new() }
    }

    /// Begin recording a new batch. Returns the batch id.
    pub(crate) fn begin_batch(&mut self) -> BatchId {
        let id = BatchId::new(self.next_id);
        self.next_id += 1;
        self.batches.insert(id, Vec::new());
        self.current_batch = Some(id);
        id
    }

    /// Finish recording the current batch.
    pub(crate) fn end_batch(&mut self) {
        self.current_batch = None;
    }

    /// Record a single command into the currently open batch.
    ///
    /// # Errors
    ///
    /// Returns `Err(BatchError::NoActiveBatch)` if there is no open batch
    /// (i.e. `begin_batch` has not been called, or `end_batch` has already
    /// been called).
    pub(crate) fn record(&mut self, cmd: BatchCommand) -> Result<(), BatchError> {
        let id = self.current_batch.ok_or(BatchError::NoActiveBatch)?;
        if let Some(cmds) = self.batches.get_mut(&id) {
            cmds.push(cmd);
        }
        Ok(())
    }

    /// Remove a batch and free its resources.
    pub(crate) fn destroy_batch(&mut self, id: BatchId) {
        if self.current_batch == Some(id) {
            self.current_batch = None;
        }
        self.batches.remove(&id);
    }

    /// Check whether a batch id is still valid.
    pub(crate) fn contains_batch(&self, id: BatchId) -> bool {
        self.batches.contains_key(&id)
    }

    /// Return the number of currently recorded batches.
    pub(crate) fn batch_count(&self) -> usize {
        self.batches.len()
    }
}

/// Accumulated transform state that tracks translation and opacity
/// across consecutive [`BatchCommand`]s.
#[derive(Debug, Clone, Copy)]
struct TransformState {
    /// Accumulated X offset.
    dx: f32,
    /// Accumulated Y offset.
    dy: f32,
    /// Accumulated opacity multiplier (1.0 = fully opaque).
    opacity: f32,
}

impl TransformState {
    fn apply_to_rect(&self, rect: &Rect) -> Rect {
        Rect::new(
            (rect.x as f32 + self.dx).round() as i32,
            (rect.y as f32 + self.dy).round() as i32,
            rect.width,
            rect.height,
        )
    }

    fn apply_to_point(&self, pt: &Point) -> Point {
        Point::new((pt.x as f32 + self.dx).round() as i32, (pt.y as f32 + self.dy).round() as i32)
    }

    fn apply_to_color(&self, color: &Color) -> Color {
        // `self.opacity` can be NaN when a caller fed a non-finite `SetOpacity` (see below), and
        // `NaN.round() as u8` is 0, so the colour would silently vanish. Clamping first turns any
        // out-of-range value into a defined endpoint and any NaN into 0, which is the honest
        // "fully transparent" rather than "undefined turned into an arbitrary byte".
        Color {
            r: color.r,
            g: color.g,
            b: color.b,
            a: (color.a as f32 * self.opacity).clamp(0.0, 255.0) as u8,
        }
    }
}

impl Default for TransformState {
    fn default() -> Self {
        Self { dx: 0.0, dy: 0.0, opacity: 1.0 }
    }
}

/// Translate a single [`BatchCommand`] into a [`RenderCommand`].
///
/// Some batch commands carry higher-level semantics not directly represented by
/// the low-level `RenderCommand` enum. In those cases the translation makes
/// reasonable assumptions (e.g. using the default UI font family with the
/// requested size for text, or embedding image data looked up from the cache).
///
/// Returns `None` for commands that only update the transform state (e.g.
/// [`BatchCommand::Translate`], [`BatchCommand::SetOpacity`]).
///
/// # Why this is a free function, not a `BatchState` method (D09-RENDER-05)
///
/// The replay path used to `clone()` the whole [`BatchState`] before calling
/// `BatchState::replay`, because a method on `self` could not take the shared
/// borrow of `batches`/`images` that translation needs *and* the mutable borrow
/// of `backend` that painting needs at the same time. That clone deep-copied
/// every unrelated batch command and every cached image byte on each replay, so
/// replaying one small batch cost the size of the entire state. Made free, it
/// takes the two maps as separate borrows, which lets [`replay_into`] split
/// `SoftwarePaintBackend`'s fields and pass them without any clone.
fn transform_command(
    cmd: &BatchCommand,
    images: &HashMap<ObjectId, Vec<u8>>,
    state: &mut TransformState,
) -> Option<RenderCommand> {
    match cmd {
        BatchCommand::FillRect { rect, color } => Some(RenderCommand::FillRect {
            rect: state.apply_to_rect(rect),
            color: state.apply_to_color(color),
        }),

        BatchCommand::StrokeRect { rect, color, width } => Some(RenderCommand::DrawRectStroke {
            rect: state.apply_to_rect(rect),
            color: state.apply_to_color(color),
            width: (*width).round().max(1.0) as u32,
        }),

        BatchCommand::DrawLine { from, to, color, width } => Some(RenderCommand::DrawLineStroke {
            from: state.apply_to_point(from),
            to: state.apply_to_point(to),
            color: state.apply_to_color(color),
            width: (*width).round().max(1.0) as u32,
        }),

        BatchCommand::DrawImage { rect, image_id, opacity } => {
            let mut data = images.get(image_id).cloned().unwrap_or_default();
            if data.is_empty() {
                log::warn!("[batch] DrawImage references unknown image id {image_id}; dropping");
                return None;
            }
            // Test-only accounting of how many source pixel bytes this translation
            // copies. It is the observable the D09-RENDER-05 regression test asserts
            // on: replaying a batch must not copy image data belonging to batches that
            // are not being replayed. Compiled out of production builds (principle #28).
            #[cfg(test)]
            note_image_bytes_translated(data.len());
            let applied_rect = state.apply_to_rect(rect);
            let combined_opacity = state.opacity * opacity;
            // RenderCommand::DrawImage has no alpha channel, so a partial
            // opacity is baked into the image's alpha bytes (RGBA).
            if combined_opacity < 1.0 && data.len() % 4 == 0 {
                for px in data.as_chunks_mut::<4>().0 {
                    px[3] = (px[3] as f32 * combined_opacity).round().clamp(0.0, 255.0) as u8;
                }
            }
            Some(RenderCommand::DrawImage {
                x: applied_rect.x,
                y: applied_rect.y,
                width: applied_rect.width,
                height: applied_rect.height,
                data,
            })
        }

        BatchCommand::DrawImageSubrect { image_id, .. } => {
            // Source-region cropping needs the source image's dimensions,
            // which the image cache (ObjectId -> raw RGBA bytes) does not
            // carry. Emitting a stretched full-image would silently render
            // the wrong pixels, so drop the command and report it instead.
            log::warn!(
                    "[batch] DrawImageSubrect (image={image_id}) dropped: source-crop requires image dimensions metadata that is not stored"
                );
            None
        }

        BatchCommand::DrawText { position, text, color, font_size } => {
            let font = Font::simple(BATCH_DEFAULT_FONT_FAMILY, *font_size);
            Some(RenderCommand::DrawText {
                origin: state.apply_to_point(position),
                text: text.clone(),
                font,
                color: state.apply_to_color(color),
                alignment: HorizontalAlignment::Left,
            })
        }

        BatchCommand::PushClip { rect } => {
            let applied = state.apply_to_rect(rect);
            Some(RenderCommand::PushClip {
                x: applied.x,
                y: applied.y,
                width: applied.width,
                height: applied.height,
            })
        }

        BatchCommand::PopClip => Some(RenderCommand::PopClip),

        // Translate and SetOpacity update the transform state but
        // produce no visible output.
        BatchCommand::Translate { dx, dy } => {
            state.dx += dx;
            state.dy += dy;
            None
        }
        BatchCommand::SetOpacity { opacity } => {
            // A non-finite opacity is not a meaningful factor: `NaN` poisons every later
            // multiplication and `Infinity` saturates every colour to one endpoint. Reject it at
            // the source so the batch keeps its last good opacity instead of silently losing the
            // colour for every command that follows.
            if opacity.is_finite() {
                state.opacity = (state.opacity * opacity).clamp(0.0, 1.0);
            } else {
                log::warn!(
                    "[batch] SetOpacity({opacity}) rejected: opacity must be finite; keeping {}",
                    state.opacity
                );
            }
            None
        }
    }
}

// Test-only counter of source image bytes copied by `transform_command`.
//
// # Why a counter rather than a global allocator shim (D09-RENDER-05)
//
// The defect is that replaying one batch used to deep-`clone()` the whole
// `BatchState` — every batch's commands and every cached image. The image bytes
// dominate that cost and are the part a test can count without a custom
// `GlobalAlloc`. This counter is compiled only under `cfg(test)`, so it adds no
// work to a release build, and the regression test resets it around the replay it
// is measuring.
#[cfg(test)]
thread_local! {
    #[allow(clippy::missing_const_for_thread_local)]
    static IMAGE_BYTES_TRANSLATED: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
}

/// Adds `bytes` to the test-only translation counter. (D09-RENDER-05)
#[cfg(test)]
fn note_image_bytes_translated(bytes: usize) {
    IMAGE_BYTES_TRANSLATED.with(|cell| cell.set(cell.get() + bytes));
}

/// Resets the test-only translation counter and returns its previous value. (D09-RENDER-05)
#[cfg(test)]
fn take_image_bytes_translated() -> usize {
    IMAGE_BYTES_TRANSLATED.with(|cell| cell.replace(0))
}

/// Replay batch `id` from `batches`/**`images`** into `surface` without cloning
/// the batch state.
///
/// # Why this does not clone (D09-RENDER-05)
///
/// [`SoftwarePaintBackend`] holds its batch data in `batch_state`, a field of the
/// backend itself. A plain `self.batch_state.replay(self, id)` borrows `self`
/// immutably (for the lookup) and mutably (for painting) in the same call, which
/// the borrow checker rejects — hence the historical `clone()`. Replaying into
/// the backend's **surface** field instead splits the borrow: the two batch maps
/// come from `batch_state` and the destination from `surface`, so the lookup
/// borrows only what it reads. Replay time and allocations are therefore
/// proportional to the replayed batch, not to the total size of the backend.
///
/// Commands are painted through [`SurfacePaintBackend`], a zero-copy view over the
/// surface, so the output is byte-for-byte what the backend's own command path
/// produces.
fn replay_into(
    batches: &HashMap<BatchId, Vec<BatchCommand>>,
    images: &HashMap<ObjectId, Vec<u8>>,
    surface: &mut SoftwareSurface,
    id: BatchId,
) {
    let Some(cmds) = batches.get(&id) else {
        return;
    };
    let mut state = TransformState::default();
    let mut backend = SurfacePaintBackend(surface);
    for cmd in cmds {
        if let Some(rc) = transform_command(cmd, images, &mut state) {
            backend.execute_command(&rc);
        }
    }
}

impl BatchRenderer for SoftwarePaintBackend {
    /// Opens a new batch in this backend's batch state.
    fn begin_batch(&mut self) -> BatchId {
        self.batch_state.begin_batch()
    }

    /// Closes the current batch, keeping its commands available for replay.
    fn end_batch(&mut self) {
        self.batch_state.end_batch()
    }

    /// Appends a command to the current batch.
    ///
    /// # Errors
    ///
    /// Returns `BatchError::NoActiveBatch` when no batch is open.
    fn record(&mut self, cmd: BatchCommand) -> Result<(), BatchError> {
        self.batch_state.record(cmd)
    }

    /// Replays the batch through this backend's own paint path.
    ///
    /// # What changed (D09-RENDER-05)
    ///
    /// This used to `clone()` the entire [`BatchState`] before replaying, which
    /// deep-copied every recorded batch and every cached image on the backend —
    /// so replaying one small batch cost as much as the whole state. It now
    /// borrows the batch data and the surface as separate fields of `self`
    /// (through [`replay_into`]), so nothing is cloned and the cost tracks only
    /// the target batch. Replay semantics are unchanged: commands are translated
    /// in order against the same transform/opacity state and drawn through the
    /// same `PaintBackend::execute_command` path.
    fn replay(&mut self, id: BatchId) {
        // Split the borrow of `self` so the batch data (read) and the paint target
        // (mutated) are distinct fields, and neither is the whole of `self` —
        // otherwise the immutable and mutable borrows overlap and the compiler
        // rejects the call (D09-RENDER-05).
        let SoftwarePaintBackend { surface, batch_state } = self;
        let BatchState { batches, images, .. } = batch_state;
        replay_into(batches, images, surface, id);
    }

    /// Drops a batch and its recorded commands.
    ///
    /// If the id is the batch currently open, recording is closed too.
    fn destroy_batch(&mut self, id: BatchId) {
        self.batch_state.destroy_batch(id)
    }

    /// Returns whether the id still refers to a live batch.
    fn contains_batch(&self, id: BatchId) -> bool {
        self.batch_state.contains_batch(id)
    }

    /// Returns the number of live batches held by this backend.
    fn batch_count(&self) -> usize {
        self.batch_state.batch_count()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compat::MiniToString;
    use crate::core::{Color, Point, Rect};

    // ── BatchId construction & conversions ──────────────────────────────

    #[test]
    fn batch_id_new_and_get() {
        let id = BatchId::new(42);
        assert_eq!(id.get(), 42);
    }

    #[test]
    fn batch_id_from_u64() {
        let id: BatchId = 99u64.into();
        assert_eq!(id.get(), 99);
    }

    #[test]
    fn batch_id_equality_and_hash() {
        let a = BatchId::new(1);
        let b = BatchId::new(1);
        let c = BatchId::new(2);
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn batch_id_copy_behavior() {
        let id = BatchId::new(7);
        let copied = id; // Copy
        assert_eq!(id, copied);
    }

    // ── BatchCommand variant construction ───────────────────────────────

    #[test]
    fn batch_command_fill_rect_roundtrip() {
        let cmd = BatchCommand::FillRect { rect: Rect::new(10, 20, 100, 200), color: Color::RED };
        match cmd {
            BatchCommand::FillRect { rect, color } => {
                assert_eq!(rect, Rect::new(10, 20, 100, 200));
                assert_eq!(color, Color::RED);
            }
            _ => panic!("expected FillRect variant"),
        }
    }

    #[test]
    fn batch_command_stroke_rect_roundtrip() {
        let cmd = BatchCommand::StrokeRect {
            rect: Rect::new(5, 5, 50, 50),
            color: Color::GREEN,
            width: 2.0,
        };
        match cmd {
            BatchCommand::StrokeRect { rect, color, width } => {
                assert_eq!(rect, Rect::new(5, 5, 50, 50));
                assert_eq!(color, Color::GREEN);
                assert!((width - 2.0).abs() < 1e-6);
            }
            _ => panic!("expected StrokeRect variant"),
        }
    }

    #[test]
    fn batch_command_draw_line_roundtrip() {
        let from = Point::new(0, 0);
        let to = Point::new(100, 100);
        let cmd = BatchCommand::DrawLine { from, to, color: Color::BLUE, width: 3.0 };
        match cmd {
            BatchCommand::DrawLine { from: f, to: t, color, width } => {
                assert_eq!(f, from);
                assert_eq!(t, to);
                assert_eq!(color, Color::BLUE);
                assert!((width - 3.0).abs() < 1e-6);
            }
            _ => panic!("expected DrawLine variant"),
        }
    }

    #[test]
    fn batch_command_draw_image_roundtrip() {
        let cmd =
            BatchCommand::DrawImage { rect: Rect::new(0, 0, 32, 32), image_id: 1u64, opacity: 0.8 };
        match cmd {
            BatchCommand::DrawImage { rect, image_id, opacity } => {
                assert_eq!(rect, Rect::new(0, 0, 32, 32));
                assert_eq!(image_id, 1u64);
                assert!((opacity - 0.8).abs() < 1e-6);
            }
            _ => panic!("expected DrawImage variant"),
        }
    }

    #[test]
    fn batch_command_draw_image_subrect_roundtrip() {
        let cmd = BatchCommand::DrawImageSubrect {
            dest: Rect::new(10, 10, 64, 64),
            source: Rect::new(0, 0, 32, 32),
            image_id: 2u64,
            opacity: 0.5,
        };
        match cmd {
            BatchCommand::DrawImageSubrect { dest, source, image_id, opacity } => {
                assert_eq!(dest, Rect::new(10, 10, 64, 64));
                assert_eq!(source, Rect::new(0, 0, 32, 32));
                assert_eq!(image_id, 2u64);
                assert!((opacity - 0.5).abs() < 1e-6);
            }
            _ => panic!("expected DrawImageSubrect variant"),
        }
    }

    #[test]
    fn batch_command_draw_text_roundtrip() {
        let cmd = BatchCommand::DrawText {
            position: Point::new(15, 30),
            text: "Hello".to_string(),
            color: Color::WHITE,
            font_size: 16.0,
        };
        match cmd {
            BatchCommand::DrawText { position, text, color, font_size } => {
                assert_eq!(position, Point::new(15, 30));
                assert_eq!(text, "Hello");
                assert_eq!(color, Color::WHITE);
                assert!((font_size - 16.0).abs() < 1e-6);
            }
            _ => panic!("expected DrawText variant"),
        }
    }

    #[test]
    fn batch_command_push_clip_roundtrip() {
        let cmd = BatchCommand::PushClip { rect: Rect::new(0, 0, 800, 600) };
        match cmd {
            BatchCommand::PushClip { rect } => {
                assert_eq!(rect, Rect::new(0, 0, 800, 600));
            }
            _ => panic!("expected PushClip variant"),
        }
    }

    #[test]
    fn batch_command_pop_clip_roundtrip() {
        let cmd = BatchCommand::PopClip;
        match cmd {
            BatchCommand::PopClip => {} // expected
            _ => panic!("expected PopClip variant"),
        }
    }

    #[test]
    fn batch_command_translate_roundtrip() {
        let cmd = BatchCommand::Translate { dx: 10.0, dy: 20.0 };
        match cmd {
            BatchCommand::Translate { dx, dy } => {
                assert!((dx - 10.0).abs() < 1e-6);
                assert!((dy - 20.0).abs() < 1e-6);
            }
            _ => panic!("expected Translate variant"),
        }
    }

    #[test]
    fn batch_command_set_opacity_roundtrip() {
        let cmd = BatchCommand::SetOpacity { opacity: 0.75 };
        match cmd {
            BatchCommand::SetOpacity { opacity } => {
                assert!((opacity - 0.75).abs() < 1e-6);
            }
            _ => panic!("expected SetOpacity variant"),
        }
    }

    // ── BatchState lifecycle ────────────────────────────────────────────

    #[test]
    fn batch_state_initial_state() {
        let state = BatchState::new();
        assert_eq!(state.batch_count(), 0);
        assert!(!state.contains_batch(BatchId::new(0)));
        assert!(state.current_batch.is_none());
    }

    #[test]
    fn batch_state_begin_end_batch_increments_id() {
        let mut state = BatchState::new();
        let id1 = state.begin_batch();
        assert_eq!(id1, BatchId::new(0));
        assert_eq!(state.batch_count(), 1);
        assert!(state.contains_batch(id1));
        state.end_batch();

        let id2 = state.begin_batch();
        assert_eq!(id2, BatchId::new(1));
        assert_eq!(state.batch_count(), 2);
        state.end_batch();
    }

    #[test]
    fn batch_state_record_commands() {
        let mut state = BatchState::new();
        let id = state.begin_batch();
        state
            .record(BatchCommand::FillRect { rect: Rect::new(0, 0, 50, 50), color: Color::RED })
            .unwrap();
        state.record(BatchCommand::PopClip).unwrap();
        state.end_batch();

        let cmds = state.batches.get(&id).unwrap();
        assert_eq!(cmds.len(), 2);
        assert!(matches!(cmds[0], BatchCommand::FillRect { .. }));
        assert!(matches!(cmds[1], BatchCommand::PopClip));
    }

    #[test]
    fn batch_state_record_without_begin_returns_error() {
        let mut state = BatchState::new();
        let result = state.record(BatchCommand::PopClip);
        assert_eq!(result, Err(BatchError::NoActiveBatch));
    }

    #[test]
    fn batch_state_destroy_batch_removes_it() {
        let mut state = BatchState::new();
        let id = state.begin_batch();
        state.end_batch();
        assert_eq!(state.batch_count(), 1);

        state.destroy_batch(id);
        assert_eq!(state.batch_count(), 0);
        assert!(!state.contains_batch(id));
    }

    #[test]
    fn batch_state_destroy_batch_clears_current() {
        let mut state = BatchState::new();
        let id = state.begin_batch();
        state.destroy_batch(id); // destroys while still open
        assert!(state.current_batch.is_none());
    }

    #[test]
    fn batch_state_replay_nonexistent_id_is_noop() {
        // Replay goes through the backend's `BatchRenderer::replay`, which is the one
        // production path (D09-RENDER-05 removed the cloning `BatchState::replay`).
        let size = crate::core::Size::new(1, 1);
        let mut backend = SoftwarePaintBackend::new(size, 1.0);
        backend.replay(BatchId::new(999));
        // No panic and nothing painted is the whole assertion.
    }

    #[test]
    fn batch_state_translate_command_skip_translate_and_set_opacity() {
        let mut state = BatchState::new();
        let id = state.begin_batch();
        state.record(BatchCommand::Translate { dx: 5.0, dy: 5.0 }).unwrap();
        state.record(BatchCommand::SetOpacity { opacity: 0.5 }).unwrap();
        state.end_batch();

        // Translate/SetOpacity are recorded in the batch, but during replay
        // they update the transform state instead of emitting a RenderCommand.
        let cmds = state.batches.get(&id).unwrap();
        assert_eq!(cmds.len(), 2);
        assert!(matches!(cmds[0], BatchCommand::Translate { .. }));
        assert!(matches!(cmds[1], BatchCommand::SetOpacity { .. }));
    }

    // ── BatchRenderer trait via SoftwarePaintBackend ────────────────────

    #[test]
    fn batch_renderer_trait_begin_end_record() {
        let size = crate::core::Size::new(100, 100);
        let mut backend = SoftwarePaintBackend::new(size, 1.0);
        let id = backend.begin_batch();
        backend
            .record(BatchCommand::FillRect { rect: Rect::new(0, 0, 10, 10), color: Color::RED })
            .unwrap();
        backend.end_batch();
        assert!(backend.contains_batch(id));
    }

    #[test]
    fn batch_renderer_destroy_batch() {
        let size = crate::core::Size::new(100, 100);
        let mut backend = SoftwarePaintBackend::new(size, 1.0);
        let id = backend.begin_batch();
        backend.end_batch();

        assert_eq!(backend.batch_count(), 1);
        backend.destroy_batch(id);
        assert_eq!(backend.batch_count(), 0);
    }

    #[test]
    fn batch_renderer_replay_fill_rect() {
        let size = crate::core::Size::new(50, 50);
        let mut backend = SoftwarePaintBackend::new(size, 1.0);
        backend.begin_frame(Color::WHITE);

        let id = backend.begin_batch();
        backend
            .record(BatchCommand::FillRect { rect: Rect::new(5, 5, 10, 10), color: Color::RED })
            .unwrap();
        backend.end_batch();

        backend.replay(id);
        backend.end_frame();

        // Verify pixel data was written at center of fill region
        let rgba = backend.frame_rgba();
        let stride = 50 * 4;
        // Pixel at (10, 10) should be RED
        let idx = 10 * stride + 10 * 4;
        assert_eq!(rgba[idx], 255); // R
        assert_eq!(rgba[idx + 1], 0); // G
        assert_eq!(rgba[idx + 2], 0); // B
        assert_eq!(rgba[idx + 3], 255); // A
    }

    /// Replaying one batch must not copy every other batch or image on the backend.
    ///
    /// # What this pins (D09-RENDER-05)
    ///
    /// `SoftwarePaintBackend::replay` used to `clone()` the whole `BatchState`
    /// before replaying, so replaying a small batch deep-copied every unrelated
    /// batch command *and* every cached image. This test observes the cost through
    /// the test-only image-byte counter: it replays a small batch while the backend
    /// also holds two large, unrelated image batches. The bytes copied by the
    /// replay must come only from the target batch, and must not grow when the
    /// unrelated images grow.
    #[test]
    fn replaying_a_batch_does_not_copy_unrelated_batches_or_images() {
        fn replay_and_measure(unrelated_image_bytes: usize) -> usize {
            let size = crate::core::Size::new(64, 64);
            let mut backend = SoftwarePaintBackend::new(size, 1.0);
            backend.begin_frame(Color::WHITE);

            // The target batch: one small fill, no image at all.
            let target = backend.begin_batch();
            backend
                .record(BatchCommand::FillRect { rect: Rect::new(2, 2, 8, 8), color: Color::RED })
                .unwrap();
            backend.end_batch();

            // Two unrelated batches, each holding a cached image of the given size.
            for image_index in 0..2u64 {
                let object_id = 1000 + image_index;
                backend.batch_state.images.insert(object_id, vec![7u8; unrelated_image_bytes]);
                let other = backend.begin_batch();
                backend
                    .record(BatchCommand::DrawImage {
                        rect: Rect::new(0, 0, 64, 64),
                        image_id: object_id,
                        opacity: 1.0,
                    })
                    .unwrap();
                backend.end_batch();
                let _ = other;
            }

            // Measure only the target replay.
            let _ = take_image_bytes_translated();
            backend.replay(target);
            take_image_bytes_translated()
        }

        let small = replay_and_measure(64 * 64 * 4);
        let large = replay_and_measure(512 * 64 * 4);

        assert_eq!(small, 0, "replaying a batch with no image must copy no image bytes");
        assert_eq!(
            large, 0,
            "unrelated images must not be copied when a different batch is replayed"
        );
    }

    /// The non-cloning replay must produce the same pixels as recording and drawing
    /// the commands directly — the optimisation must not change output. (D09-RENDER-05)
    #[test]
    fn replay_matches_direct_execution_including_opacity_and_translate() {
        let size = crate::core::Size::new(32, 32);

        // Reference: the same commands executed directly, in order.
        let mut reference = SoftwarePaintBackend::new(size, 1.0);
        reference.begin_frame(Color::BLACK);
        reference.execute_command(&RenderCommand::FillRect {
            rect: Rect::new(0, 0, 10, 10),
            color: Color::rgba(255, 0, 0, 128),
        });
        reference.execute_command(&RenderCommand::FillRect {
            rect: Rect::new(4, 4, 6, 6),
            color: Color::rgba(0, 255, 0, 128),
        });
        reference.end_frame();
        let expected = reference.frame_rgba().to_vec();

        // Replayed: the same geometry/colour produced through batch translation with a
        // `Translate` applied to make sure the transform path is exercised too.
        let mut backend = SoftwarePaintBackend::new(size, 1.0);
        backend.begin_frame(Color::BLACK);
        let id = backend.begin_batch();
        backend
            .record(BatchCommand::FillRect {
                rect: Rect::new(0, 0, 10, 10),
                color: Color::rgba(255, 0, 0, 128),
            })
            .unwrap();
        backend.record(BatchCommand::Translate { dx: 3.0, dy: 3.0 }).unwrap();
        backend
            .record(BatchCommand::FillRect {
                rect: Rect::new(1, 1, 6, 6),
                color: Color::rgba(0, 255, 0, 128),
            })
            .unwrap();
        backend.end_batch();
        backend.replay(id);
        backend.end_frame();

        assert_eq!(
            backend.frame_rgba(),
            expected.as_slice(),
            "replay must paint the same pixels as executing the translated commands directly"
        );
    }

    #[test]
    fn batch_renderer_contains_batch_after_creation() {
        let size = crate::core::Size::new(10, 10);
        let mut backend = SoftwarePaintBackend::new(size, 1.0);
        let id = backend.begin_batch();
        backend
            .record(BatchCommand::DrawLine {
                from: Point::new(0, 0),
                to: Point::new(10, 10),
                color: Color::RED,
                width: 1.0,
            })
            .unwrap();
        backend.end_batch();

        assert!(backend.contains_batch(id));
        assert_eq!(backend.batch_count(), 1);
    }
}