rust_widgets 0.9.6

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ 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
//! 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::HashMap;

use crate::core::{Color, Font, HorizontalAlignment, ObjectId, Point, Rect};
use crate::render::RenderCommand;

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

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

impl std::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.
#[derive(Debug, Clone)]
pub enum BatchCommand {
    /// Fill a rectangle with a solid colour.
    FillRect { rect: Rect, color: Color },
    /// Stroke a rectangular border.
    StrokeRect { rect: Rect, color: Color, width: f32 },
    /// Draw a line between two points.
    DrawLine { from: Point, to: Point, color: Color, width: f32 },
    /// Draw an image identified by its resource id.
    DrawImage { rect: Rect, image_id: ObjectId, opacity: f32 },
    /// Draw a clipped region of an image.
    DrawImageSubrect { dest: Rect, source: Rect, image_id: ObjectId, opacity: f32 },
    /// Draw text at the given position.
    DrawText { position: Point, text: String, color: Color, font_size: f32 },
    /// Push a clipping rectangle – subsequent commands are clipped.
    PushClip { rect: Rect },
    /// Pop the most recent clipping rectangle.
    PopClip,
    /// Apply a translation offset to all subsequent commands.
    Translate { dx: f32, dy: f32 },
    /// Apply an opacity multiplier to all subsequent commands.
    SetOpacity { opacity: f32 },
}

/// Trait implemented by renderers that can record and replay draw batches.
///
/// # Usage
///
/// ```rust,ignore
/// 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 {
    /// Begin recording a new batch. Returns the batch id.
    fn begin_batch(&mut self) -> BatchId;

    /// Finish recording the current batch.
    fn end_batch(&mut self);

    /// Record a single command into the currently open batch.
    fn record(&mut self, cmd: BatchCommand) -> Result<(), BatchError>;

    /// Replay a previously recorded batch by its id.
    fn replay(&mut self, id: BatchId);

    /// Remove a batch and free its resources.
    fn destroy_batch(&mut self, id: BatchId);

    /// Check whether a batch id is still valid.
    fn contains_batch(&self, id: BatchId) -> bool;

    /// Return the number of currently recorded batches.
    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(())
    }

    /// Replay a previously recorded batch by its id.
    ///
    /// Iterates over the stored [`BatchCommand`]s, translates each one to
    /// the corresponding [`RenderCommand`], and calls `execute_command` on
    /// the provided backend.
    pub(crate) fn replay(&self, backend: &mut SoftwarePaintBackend, id: BatchId) {
        let Some(cmds) = self.batches.get(&id) else {
            return;
        };
        for cmd in cmds {
            let rc = Self::translate_command(cmd, &self.images);
            PaintBackend::execute_command(backend, &rc);
        }
    }

    /// 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()
    }

    /// 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).
    fn translate_command(cmd: &BatchCommand, images: &HashMap<ObjectId, Vec<u8>>) -> RenderCommand {
        match cmd {
            BatchCommand::FillRect { rect, color } => {
                RenderCommand::FillRect { rect: *rect, color: *color }
            }

            BatchCommand::StrokeRect { rect, color, width } => {
                RenderCommand::DrawRectStroke { rect: *rect, color: *color, width: *width as u32 }
            }

            BatchCommand::DrawLine { from, to, color, width } => RenderCommand::DrawLineStroke {
                from: *from,
                to: *to,
                color: *color,
                width: *width as u32,
            },

            BatchCommand::DrawImage { rect, image_id, opacity: _opacity } => {
                let data = images.get(image_id).cloned().unwrap_or_default();
                RenderCommand::DrawImage {
                    x: rect.x,
                    y: rect.y,
                    width: rect.width,
                    height: rect.height,
                    data,
                }
            }

            BatchCommand::DrawImageSubrect {
                dest,
                source: _source,
                image_id,
                opacity: _opacity,
            } => {
                let data = images.get(image_id).cloned().unwrap_or_default();
                RenderCommand::DrawImage {
                    x: dest.x,
                    y: dest.y,
                    width: dest.width,
                    height: dest.height,
                    data,
                }
            }

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

            BatchCommand::PushClip { rect } => RenderCommand::PushClip {
                x: rect.x,
                y: rect.y,
                width: rect.width,
                height: rect.height,
            },

            BatchCommand::PopClip => RenderCommand::PopClip,

            // Translate / SetOpacity have no direct RenderCommand equivalent
            // in the current command set. They are skipped during replay.
            // Backends that need these semantics should implement them at a
            // higher layer (e.g. transform stack in the scene).
            BatchCommand::Translate { .. } | BatchCommand::SetOpacity { .. } => {
                // Emit a no-op placeholder that does nothing.
                RenderCommand::FillRect { rect: Rect::new(0, 0, 0, 0), color: Color::TRANSPARENT }
            }
        }
    }
}

impl BatchRenderer for SoftwarePaintBackend {
    fn begin_batch(&mut self) -> BatchId {
        self.batch_state.begin_batch()
    }

    fn end_batch(&mut self) {
        self.batch_state.end_batch()
    }

    fn record(&mut self, cmd: BatchCommand) -> Result<(), BatchError> {
        self.batch_state.record(cmd)
    }

    fn replay(&mut self, id: BatchId) {
        // Clone the state to avoid borrow issues, then replay.
        let state = self.batch_state.clone();
        state.replay(self, id);
    }

    fn destroy_batch(&mut self, id: BatchId) {
        self.batch_state.destroy_batch(id)
    }

    fn contains_batch(&self, id: BatchId) -> bool {
        self.batch_state.contains_batch(id)
    }

    fn batch_count(&self) -> usize {
        self.batch_state.batch_count()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    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() {
        let state = BatchState::new();
        // Should not panic
        let size = crate::core::Size::new(1, 1);
        let mut backend = SoftwarePaintBackend::new(size, 1.0);
        state.replay(&mut backend, BatchId::new(999));
    }

    #[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 emit a zero-size FillRect during replay
        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
    }

    #[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);
    }
}