device-envoy-core 0.1.0

Shared traits and data types for device-envoy platform crates
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
#![cfg_attr(
    feature = "doc-images",
    doc = ::embed_doc_image::embed_image!("led2d1", "docs/assets/led2d1.png"),
    doc = ::embed_doc_image::embed_image!("led2d2", "docs/assets/led2d2.png")
)]
//! Shared 2D LED panel building blocks used across all device-envoy platforms.
//!
//! This module provides platform-independent types for NeoPixel-style (WS2812) LED panel
//! displays. See the platform crate (`device-envoy-rp` or `device-envoy-esp`) for the
//! primary documentation and examples.
//!
//! [led2d1]: https://raw.githubusercontent.com/CarlKCarlK/device-envoy/main/crates/device-envoy-core/docs/assets/led2d1.png
//! [led2d2]: https://raw.githubusercontent.com/CarlKCarlK/device-envoy/main/crates/device-envoy-core/docs/assets/led2d2.png

pub mod layout;

pub use embedded_graphics::geometry::Point;
pub use embedded_graphics::geometry::Size;
pub use layout::LedLayout;

use core::{
    borrow::Borrow,
    convert::Infallible,
    ops::{Deref, DerefMut, Index, IndexMut},
};
use embedded_graphics::pixelcolor::Rgb888;
use embedded_graphics::{
    draw_target::DrawTarget,
    mono_font::{
        DecorationDimensions, MonoFont,
        ascii::{
            FONT_4X6, FONT_5X7, FONT_5X8, FONT_6X9, FONT_6X10, FONT_6X12, FONT_6X13,
            FONT_6X13_BOLD, FONT_6X13_ITALIC, FONT_7X13, FONT_7X13_BOLD, FONT_7X13_ITALIC,
            FONT_7X14, FONT_7X14_BOLD, FONT_8X13, FONT_8X13_BOLD, FONT_8X13_ITALIC, FONT_9X15,
            FONT_9X15_BOLD, FONT_9X18, FONT_9X18_BOLD, FONT_10X20,
        },
        mapping::StrGlyphMapping,
    },
    prelude::*,
};
use smart_leds::RGB8;

use crate::led_strip::ToRgb888;
use crate::led_strip::{Frame1d as StripFrame, LedStrip as LedStripTrait};

/// Platform-agnostic LED panel device contract.
///
/// Platform crates implement this for their concrete LED panel types so shared logic can
/// drive LED panels without knowing the underlying hardware backend.
///
/// This page serves as the definitive reference for what a generated LED panel type
/// provides. For first-time readers, start with the `led2d` module documentation in your
/// platform crate (`device-envoy-rp` or `device-envoy-esp`), then return here for a
/// complete list of available methods and associated constants.
///
/// Design intent:
///
/// - Primitive operations are [`Led2d::write_frame`] and [`Led2d::animate`].
/// - Convenience text operations ([`Led2d::write_text_to_frame`] and [`Led2d::write_text`])
///   are default methods derived from primitives and associated constants.
/// - This trait is intended for static dispatch on embedded targets.
///
/// The trait takes `const W` and `const H` so dimensions remain compile-time constants and
/// can be used in frame types like [`Frame2d<W, H>`].
///
/// # Example: Write Text
///
/// In this example, we render text on a 12x4 panel.
///
/// ![LED panel preview](https://raw.githubusercontent.com/CarlKCarlK/device-envoy/main/crates/device-envoy-core/docs/assets/led2d1.png)
///
/// ```rust,no_run
/// use device_envoy_core::led2d::Led2d;
/// use smart_leds::RGB8;
///
/// fn write_rust<const W: usize, const H: usize>(led2d: &impl Led2d<W, H>) {
///     let colors = [
///         RGB8::new(0, 255, 255),
///         RGB8::new(255, 0, 0),
///         RGB8::new(255, 255, 0),
///     ];
///     led2d.write_text("Rust", &colors);
/// }
///
/// # use device_envoy_core::led2d::{Frame2d, Led2dFont};
/// # struct Led12x4;
/// # impl Led2d<12, 4> for Led12x4 {
/// #     const MAX_FRAMES: usize = 2;
/// #     const MAX_BRIGHTNESS: u8 = 22;
/// #     const FONT: Led2dFont = Led2dFont::Font3x4Trim;
/// #     fn write_frame(&self, _frame2d: Frame2d<12, 4>) {}
/// #     fn animate<I>(&self, _frames: I)
/// #     where
/// #         I: IntoIterator,
/// #         I::Item: core::borrow::Borrow<(Frame2d<12, 4>, embassy_time::Duration)>,
/// #     {
/// #     }
/// # }
/// # let led12x4 = Led12x4;
/// # write_rust(&led12x4);
/// ```
///
/// # Example: Animated Text
///
/// This example animates text on an LED panel.
///
/// ![LED panel preview](https://raw.githubusercontent.com/CarlKCarlK/device-envoy/main/crates/device-envoy-core/docs/assets/led2d2.png)
///
/// ```rust,no_run
/// use device_envoy_core::led2d::{Frame2d, Led2d};
/// use smart_leds::colors;
///
/// fn animate_go_go<const W: usize, const H: usize>(led2d: &impl Led2d<W, H>) {
///     let mut frame_0 = Frame2d::new();
///     led2d.write_text_to_frame("Go", &[], &mut frame_0);
///
///     let mut frame_1 = Frame2d::new();
///     led2d.write_text_to_frame("\nGo", &[colors::HOT_PINK, colors::LIME], &mut frame_1);
///
///     let frame_duration = embassy_time::Duration::from_secs(1);
///     led2d.animate([(frame_0, frame_duration), (frame_1, frame_duration)]);
/// }
///
/// # use device_envoy_core::led2d::Led2dFont;
/// # struct Led8x12;
/// # impl Led2d<8, 12> for Led8x12 {
/// #     const MAX_FRAMES: usize = 2;
/// #     const MAX_BRIGHTNESS: u8 = 22;
/// #     const FONT: Led2dFont = Led2dFont::Font4x6Trim;
/// #     fn write_frame(&self, _frame2d: Frame2d<8, 12>) {}
/// #     fn animate<I>(&self, _frames: I)
/// #     where
/// #         I: IntoIterator,
/// #         I::Item: core::borrow::Borrow<(Frame2d<8, 12>, embassy_time::Duration)>,
/// #     {
/// #     }
/// # }
/// # let led8x12 = Led8x12;
/// # animate_go_go(&led8x12);
/// ```
pub trait Led2d<const W: usize, const H: usize> {
    /// The width of the panel.
    const WIDTH: usize = W;
    /// The height of the panel.
    const HEIGHT: usize = H;
    /// Total LEDs in this panel (width × height).
    const LEN: usize = W * H;
    /// Panel dimensions as a [`Size`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    const SIZE: Size = Frame2d::<W, H>::SIZE;
    /// Top-left corner coordinate as a [`Point`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    const TOP_LEFT: Point = Frame2d::<W, H>::TOP_LEFT;
    /// Top-right corner coordinate as a [`Point`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    const TOP_RIGHT: Point = Frame2d::<W, H>::TOP_RIGHT;
    /// Bottom-left corner coordinate as a [`Point`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    const BOTTOM_LEFT: Point = Frame2d::<W, H>::BOTTOM_LEFT;
    /// Bottom-right corner coordinate as a [`Point`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    const BOTTOM_RIGHT: Point = Frame2d::<W, H>::BOTTOM_RIGHT;
    /// Maximum number of animation frames allowed.
    ///
    /// Usually configured by the platform macro (for example `led2d!`).
    const MAX_FRAMES: usize;
    /// Maximum brightness level, automatically limited by the power budget.
    ///
    /// Many implementations assume each LED draws about 60 mA at full brightness and compute
    /// a safe cap from power budget and LED count.
    const MAX_BRIGHTNESS: u8;
    /// The font used by default text helpers.
    ///
    /// Used by [`Led2d::write_text_to_frame`] and [`Led2d::write_text`].
    const FONT: Led2dFont;

    /// Write a frame to the LED panel.
    ///
    /// See your platform crate's led2d module docs for possible usage examples.
    fn write_frame(&self, frame2d: Frame2d<W, H>);

    /// Animate frames on the LED panel.
    ///
    /// The duration type is [`embassy_time::Duration`](https://docs.rs/embassy-time/latest/embassy_time/struct.Duration.html), and `frames` can be any iterator whose
    /// items borrow `(Frame2d<W, H>, embassy_time::Duration)`.
    ///
    /// See the [Led2d trait documentation](Self) for usage examples.
    fn animate<I>(&self, frames: I)
    where
        I: IntoIterator,
        I::Item: Borrow<(Frame2d<W, H>, embassy_time::Duration)>;

    /// Write text into a frame.
    ///
    /// This is a default helper built on [`render_text_to_frame`] plus associated constants.
    ///
    /// Behavior:
    ///
    /// - Text is drawn with [`Led2d::FONT`].
    /// - `colors` cycles one color per character; an empty slice defaults to white.
    /// - A `\n` character starts a new line.
    /// - Characters beyond frame width are clipped.
    ///
    /// See the [Led2d trait documentation](Self) for usage examples.
    fn write_text_to_frame(&self, text: &str, colors: &[RGB8], frame: &mut Frame2d<W, H>) {
        render_text_to_frame(
            frame,
            &Self::FONT.to_font(),
            text,
            colors,
            Self::FONT.spacing_reduction(),
        );
    }

    /// Write text to the LED panel.
    ///
    /// This default helper is equivalent to:
    ///
    /// 1. Create `Frame2d::<W, H>::new()`.
    /// 2. Call [`Led2d::write_text_to_frame`].
    /// 3. Call [`Led2d::write_frame`].
    ///
    /// See the [Led2d trait documentation](Self) for usage examples.
    fn write_text(&self, text: &str, colors: &[RGB8]) {
        let mut frame = Frame2d::<W, H>::new();
        self.write_text_to_frame(text, colors, &mut frame);
        self.write_frame(frame);
    }
}

/// Extension trait for strip-backed [`Led2d`] implementations.
///
/// This keeps the base [`Led2d`] trait backend-agnostic while still providing
/// reusable default behavior for implementations that render via a [`crate::led_strip::LedStrip`].
#[doc(hidden)] // Platform plumbing trait used by RP/ESP generated led2d wrappers.
pub trait Led2dStripBacked<const N: usize> {
    /// Concrete strip type used by this panel implementation.
    type Strip: LedStripTrait<N> + ?Sized;

    /// Return the underlying strip handle.
    fn led_strip(&self) -> &Self::Strip;

    /// Return the `(x, y) -> strip_index` mapping table.
    fn mapping_by_xy(&self) -> &[u16; N];

    /// Return the panel width used by [`Led2dStripBacked::xy_to_index`].
    fn width(&self) -> usize;

    /// Convert `(column, row)` to strip index using [`Led2dStripBacked::mapping_by_xy`].
    #[must_use]
    fn xy_to_index(&self, x_index: usize, y_index: usize) -> usize {
        self.mapping_by_xy()[y_index * self.width() + x_index] as usize
    }

    /// Convert a 2D frame into a strip frame using the stored mapping.
    fn convert_frame<const W: usize, const H: usize>(
        &self,
        frame_2d: Frame2d<W, H>,
    ) -> StripFrame<N> {
        let mut frame_1d = [RGB8::new(0, 0, 0); N];
        for y_index in 0..H {
            for x_index in 0..W {
                let led_index = self.xy_to_index(x_index, y_index);
                frame_1d[led_index] = frame_2d[(x_index, y_index)];
            }
        }
        StripFrame::from(frame_1d)
    }

    /// Write a panel frame through the associated strip backend.
    fn write_frame<const W: usize, const H: usize>(&self, frame: Frame2d<W, H>) {
        let strip_frame = self.convert_frame(frame);
        self.led_strip().write_frame(strip_frame);
    }

    /// Animate panel frames through the associated strip backend.
    fn animate<const W: usize, const H: usize, I>(&self, frames: I)
    where
        I: IntoIterator,
        I::Item: Borrow<(Frame2d<W, H>, embassy_time::Duration)>,
    {
        self.led_strip().animate(frames.into_iter().map(|frame| {
            let (frame, duration) = *frame.borrow();
            (self.convert_frame(frame), duration)
        }));
    }
}

/// Shared adapter that maps [`Frame2d`] panels onto a 1D LED strip device.
///
/// Platform crates can use this to build their `led2d` wrappers while keeping
/// mapping and frame-conversion logic in `device-envoy-core`.
#[doc(hidden)] // Platform plumbing adapter used by RP/ESP implementations.
pub struct Led2dStripAdapter<'a, const N: usize, S>
where
    S: LedStripTrait<N> + ?Sized,
{
    led_strip: &'a S,
    mapping_by_xy: [u16; N],
    width: usize,
}

impl<'a, const N: usize, S> Led2dStripAdapter<'a, N, S>
where
    S: LedStripTrait<N> + ?Sized,
{
    /// Create a strip-backed LED panel adapter from a strip and panel layout.
    #[must_use]
    pub fn new<const W: usize, const H: usize>(
        led_strip: &'a S,
        led_layout: &LedLayout<N, W, H>,
    ) -> Self {
        assert_eq!(
            W.checked_mul(H).expect("width * height must fit in usize"),
            N,
            "width * height must equal N"
        );
        Self {
            led_strip,
            mapping_by_xy: led_layout.xy_to_index(),
            width: W,
        }
    }
}

impl<'a, const N: usize, S> Led2dStripBacked<N> for Led2dStripAdapter<'a, N, S>
where
    S: LedStripTrait<N> + ?Sized,
{
    type Strip = S;

    fn led_strip(&self) -> &Self::Strip {
        self.led_strip
    }

    fn mapping_by_xy(&self) -> &[u16; N] {
        &self.mapping_by_xy
    }

    fn width(&self) -> usize {
        self.width
    }
}

// Packed bitmap for the internal 3x4 font (ASCII 0x20-0x7E).
const BIT_MATRIX3X4_FONT_DATA: [u8; 144] = [
    0x0a, 0xd5, 0x10, 0x4a, 0xa0, 0x01, 0x0a, 0xfe, 0x68, 0x85, 0x70, 0x02, 0x08, 0x74, 0x90, 0x86,
    0xa5, 0xc4, 0x08, 0x5e, 0x68, 0x48, 0x08, 0x10, 0xeb, 0x7b, 0xe7, 0xfd, 0x22, 0x27, 0xb8, 0x9b,
    0x39, 0xb4, 0x05, 0xd1, 0xa9, 0x3e, 0xea, 0x5d, 0x28, 0x0a, 0xff, 0xf3, 0xfc, 0xe4, 0x45, 0xd2,
    0xff, 0x7d, 0xff, 0xbc, 0xd9, 0xff, 0xb7, 0xcb, 0xb4, 0xe8, 0xe9, 0xfd, 0xfe, 0xcb, 0x25, 0xaa,
    0xd9, 0x7d, 0x97, 0x7d, 0xe7, 0xbf, 0xdf, 0x6f, 0xdf, 0x7f, 0x6d, 0xb7, 0xe0, 0xd0, 0xf7, 0xe5,
    0x6d, 0x48, 0xc0, 0x68, 0xdf, 0x35, 0x6f, 0x49, 0x40, 0x40, 0x86, 0xf5, 0xd7, 0xab, 0xe0, 0xc7,
    0x5f, 0x7d, 0xff, 0xbc, 0xd9, 0xff, 0x37, 0xcb, 0xb4, 0xe8, 0xe9, 0xfd, 0x1e, 0xcb, 0x25, 0xaa,
    0xd9, 0x7d, 0x17, 0x7d, 0xe7, 0xbf, 0xdf, 0x6f, 0xdf, 0x7f, 0x6d, 0xb7, 0xb1, 0x80, 0xf7, 0xe5,
    0x6d, 0x48, 0xa0, 0xa8, 0xdf, 0x35, 0x6f, 0x49, 0x20, 0x90, 0x86, 0xf5, 0xd7, 0xab, 0xb1, 0x80,
];
const BIT_MATRIX3X4_IMAGE_WIDTH: u32 = 48;
const BIT_MATRIX3X4_GLYPH_MAPPING: StrGlyphMapping<'static> = StrGlyphMapping::new("\0 \u{7e}", 0);

/// Monospace 3x4 font matching the internal `BIT_MATRIX3X4` bitmap data.
#[must_use]
pub fn bit_matrix3x4_font() -> MonoFont<'static> {
    MonoFont {
        image: embedded_graphics::image::ImageRaw::new(
            &BIT_MATRIX3X4_FONT_DATA,
            BIT_MATRIX3X4_IMAGE_WIDTH,
        ),
        glyph_mapping: &BIT_MATRIX3X4_GLYPH_MAPPING,
        character_size: embedded_graphics::prelude::Size::new(3, 4),
        character_spacing: 0,
        baseline: 3,
        underline: DecorationDimensions::new(3, 1),
        strikethrough: DecorationDimensions::new(2, 1),
    }
}

/// Render text into a frame using the provided font.
///
/// Text flows left-to-right within the frame width; a `\n` character advances to the next row.
/// Characters that exceed the frame width are skipped (no wrapping). Colors cycle over the
/// `colors` slice (one color per character); an empty slice defaults to white.
///
/// `spacing_reduction` is a `(width_reduction, height_reduction)` pair in pixels used by the
/// trimmed [`Led2dFont`] variants to pack characters more tightly.
pub fn render_text_to_frame<const W: usize, const H: usize>(
    frame: &mut Frame2d<W, H>,
    font: &embedded_graphics::mono_font::MonoFont<'static>,
    text: &str,
    colors: &[RGB8],
    spacing_reduction: (i32, i32),
) {
    let glyph_width = font.character_size.width as i32;
    let glyph_height = font.character_size.height as i32;
    let advance_x = glyph_width - spacing_reduction.0;
    let advance_y = glyph_height - spacing_reduction.1;
    let width_limit = W as i32;
    let height_limit = H as i32;
    if height_limit <= 0 || width_limit <= 0 {
        return;
    }
    let baseline = font.baseline as i32;
    let mut x = 0i32;
    let mut y = baseline;
    let mut color_index: usize = 0;

    for ch in text.chars() {
        if ch == '\n' {
            x = 0;
            y += advance_y;
            if y - baseline >= height_limit {
                break;
            }
            continue;
        }

        // Clip characters that exceed width limit (no wrapping until explicit \n).
        if x + advance_x > width_limit {
            continue;
        }

        let color = if colors.is_empty() {
            smart_leds::colors::WHITE
        } else {
            colors[color_index % colors.len()]
        };
        color_index = color_index.wrapping_add(1);

        let mut buf = [0u8; 4];
        let slice = ch.encode_utf8(&mut buf);
        let style = embedded_graphics::mono_font::MonoTextStyle::new(font, color.to_rgb888());
        let position = embedded_graphics::prelude::Point::new(x, y);
        embedded_graphics::Drawable::draw(
            &embedded_graphics::text::Text::new(slice, position, style),
            frame,
        )
        .expect("drawing into frame cannot fail");

        x += advance_x;
    }
}

/// Fonts available for use with LED panel displays.
///
/// Fonts with `Trim` suffix remove blank spacing to pack text more tightly on small displays.
#[derive(Clone, Copy, Debug)]
pub enum Led2dFont {
    /// 3x4 monospace font, trimmed (compact layout).
    Font3x4Trim,
    /// 4x6 monospace font.
    Font4x6,
    /// 3x5 monospace font, trimmed (compact layout).
    Font3x5Trim,
    /// 5x7 monospace font.
    Font5x7,
    /// 4x6 monospace font, trimmed (compact layout).
    Font4x6Trim,
    /// 5x8 monospace font.
    Font5x8,
    /// 4x7 monospace font, trimmed (compact layout).
    Font4x7Trim,
    /// 6x9 monospace font.
    Font6x9,
    /// 5x8 monospace font, trimmed (compact layout).
    Font5x8Trim,
    /// 6x10 monospace font.
    Font6x10,
    /// 5x9 monospace font, trimmed (compact layout).
    Font5x9Trim,
    /// 6x12 monospace font.
    Font6x12,
    /// 5x11 monospace font, trimmed (compact layout).
    Font5x11Trim,
    /// 6x13 monospace font.
    Font6x13,
    /// 5x12 monospace font, trimmed (compact layout).
    Font5x12Trim,
    /// 6x13 bold monospace font.
    Font6x13Bold,
    /// 5x12 bold monospace font, trimmed (compact layout).
    Font5x12TrimBold,
    /// 6x13 italic monospace font.
    Font6x13Italic,
    /// 5x12 italic monospace font, trimmed (compact layout).
    Font5x12TrimItalic,
    /// 7x13 monospace font.
    Font7x13,
    /// 6x12 monospace font, trimmed (compact layout).
    Font6x12Trim,
    /// 7x13 bold monospace font.
    Font7x13Bold,
    /// 6x12 bold monospace font, trimmed (compact layout).
    Font6x12TrimBold,
    /// 7x13 italic monospace font.
    Font7x13Italic,
    /// 6x12 italic monospace font, trimmed (compact layout).
    Font6x12TrimItalic,
    /// 7x14 monospace font.
    Font7x14,
    /// 6x13 monospace font, trimmed (compact layout).
    Font6x13Trim,
    /// 7x14 bold monospace font.
    Font7x14Bold,
    /// 6x13 bold monospace font, trimmed (compact layout).
    Font6x13TrimBold,
    /// 8x13 monospace font.
    Font8x13,
    /// 7x12 monospace font, trimmed (compact layout).
    Font7x12Trim,
    /// 8x13 bold monospace font.
    Font8x13Bold,
    /// 7x12 bold monospace font, trimmed (compact layout).
    Font7x12TrimBold,
    /// 8x13 italic monospace font.
    Font8x13Italic,
    /// 7x12 italic monospace font, trimmed (compact layout).
    Font7x12TrimItalic,
    /// 9x15 monospace font.
    Font9x15,
    /// 8x14 monospace font, trimmed (compact layout).
    Font8x14Trim,
    /// 9x15 bold monospace font.
    Font9x15Bold,
    /// 8x14 bold monospace font, trimmed (compact layout).
    Font8x14TrimBold,
    /// 9x18 monospace font.
    Font9x18,
    /// 8x17 monospace font, trimmed (compact layout).
    Font8x17Trim,
    /// 9x18 bold monospace font.
    Font9x18Bold,
    /// 8x17 bold monospace font, trimmed (compact layout).
    Font8x17TrimBold,
    /// 10x20 monospace font.
    Font10x20,
    /// 9x19 monospace font, trimmed (compact layout).
    Font9x19Trim,
}

impl Led2dFont {
    /// Return the `MonoFont` for this variant.
    #[must_use]
    pub fn to_font(self) -> MonoFont<'static> {
        match self {
            Self::Font3x4Trim => bit_matrix3x4_font(),
            Self::Font4x6 | Self::Font3x5Trim => FONT_4X6,
            Self::Font5x7 | Self::Font4x6Trim => FONT_5X7,
            Self::Font5x8 | Self::Font4x7Trim => FONT_5X8,
            Self::Font6x9 | Self::Font5x8Trim => FONT_6X9,
            Self::Font6x10 | Self::Font5x9Trim => FONT_6X10,
            Self::Font6x12 | Self::Font5x11Trim => FONT_6X12,
            Self::Font6x13 | Self::Font5x12Trim => FONT_6X13,
            Self::Font6x13Bold | Self::Font5x12TrimBold => FONT_6X13_BOLD,
            Self::Font6x13Italic | Self::Font5x12TrimItalic => FONT_6X13_ITALIC,
            Self::Font7x13 | Self::Font6x12Trim => FONT_7X13,
            Self::Font7x13Bold | Self::Font6x12TrimBold => FONT_7X13_BOLD,
            Self::Font7x13Italic | Self::Font6x12TrimItalic => FONT_7X13_ITALIC,
            Self::Font7x14 | Self::Font6x13Trim => FONT_7X14,
            Self::Font7x14Bold | Self::Font6x13TrimBold => FONT_7X14_BOLD,
            Self::Font8x13 | Self::Font7x12Trim => FONT_8X13,
            Self::Font8x13Bold | Self::Font7x12TrimBold => FONT_8X13_BOLD,
            Self::Font8x13Italic | Self::Font7x12TrimItalic => FONT_8X13_ITALIC,
            Self::Font9x15 | Self::Font8x14Trim => FONT_9X15,
            Self::Font9x15Bold | Self::Font8x14TrimBold => FONT_9X15_BOLD,
            Self::Font9x18 | Self::Font8x17Trim => FONT_9X18,
            Self::Font9x18Bold | Self::Font8x17TrimBold => FONT_9X18_BOLD,
            Self::Font10x20 | Self::Font9x19Trim => FONT_10X20,
        }
    }

    /// Return spacing reduction for trimmed variants as `(width_reduction, height_reduction)`.
    #[must_use]
    pub const fn spacing_reduction(self) -> (i32, i32) {
        match self {
            Self::Font3x4Trim
            | Self::Font4x6
            | Self::Font5x7
            | Self::Font5x8
            | Self::Font6x9
            | Self::Font6x10
            | Self::Font6x12
            | Self::Font6x13
            | Self::Font6x13Bold
            | Self::Font6x13Italic
            | Self::Font7x13
            | Self::Font7x13Bold
            | Self::Font7x13Italic
            | Self::Font7x14
            | Self::Font7x14Bold
            | Self::Font8x13
            | Self::Font8x13Bold
            | Self::Font8x13Italic
            | Self::Font9x15
            | Self::Font9x15Bold
            | Self::Font9x18
            | Self::Font9x18Bold
            | Self::Font10x20 => (0, 0),
            Self::Font3x5Trim
            | Self::Font4x6Trim
            | Self::Font4x7Trim
            | Self::Font5x8Trim
            | Self::Font5x9Trim
            | Self::Font5x11Trim
            | Self::Font5x12Trim
            | Self::Font5x12TrimBold
            | Self::Font5x12TrimItalic
            | Self::Font6x12Trim
            | Self::Font6x12TrimBold
            | Self::Font6x12TrimItalic
            | Self::Font6x13Trim
            | Self::Font6x13TrimBold
            | Self::Font7x12Trim
            | Self::Font7x12TrimBold
            | Self::Font7x12TrimItalic
            | Self::Font8x14Trim
            | Self::Font8x14TrimBold
            | Self::Font8x17Trim
            | Self::Font8x17TrimBold
            | Self::Font9x19Trim => (1, 1),
        }
    }
}

/// 2D pixel array used for general graphics on LED panels.
///
/// - Coordinates are `(x, y)` with `(0, 0)` at the top-left. The x-axis increases to the
///   right, and the y-axis increases downward.
/// - Set pixels using tuple indexing: `frame[(x, y)] = colors::RED;`.
/// - For shapes, lines, and text rendering, use the [`embedded-graphics`](https://docs.rs/embedded-graphics) crate.
///
/// ## Indexing and storage
///
/// `Frame2d` supports both:
///
/// - `(x, y)` tuple indexing: `frame[(x, y)]`
/// - Row-major array indexing: `frame[y][x]`
///
/// Tuple indexing matches display coordinates. Array indexing matches the underlying storage.
///
/// # Example: Draw pixels both directly and with [`embedded-graphics`](https://docs.rs/embedded-graphics)
///
/// ```rust,no_run
/// use device_envoy_core::{led2d::Frame2d, led_strip::ToRgb888};
/// use embedded_graphics::{
///     prelude::*,
///     primitives::{Circle, PrimitiveStyle, Rectangle},
/// };
/// use smart_leds::colors;
/// # use core::convert::Infallible;
/// # fn example() -> Result<(), Infallible> {
///
/// type Frame = Frame2d<12, 8>;
///
/// /// Calculate the top-left corner position to center a shape within a bounding box.
/// const fn centered_top_left(width: usize, height: usize, size: usize) -> Point {
///     assert!(size <= width);
///     assert!(size <= height);
///     Point::new(((width - size) / 2) as i32, ((height - size) / 2) as i32)
/// }
///
/// // Create a frame to draw on. This is just an in-memory 2D pixel buffer.
/// let mut frame = Frame::new();
///
/// // Use the embedded-graphics crate to draw a red rectangle border around the edge of the frame.
/// // We use `to_rgb888()` to convert from smart-leds RGB8 to embedded-graphics Rgb888.
/// Rectangle::new(Frame::TOP_LEFT, Frame::SIZE)
///     .into_styled(PrimitiveStyle::with_stroke(colors::RED.to_rgb888(), 1))
///     .draw(&mut frame)
///     ?;
///
/// // Direct pixel access: set the upper-left LED pixel (x = 0, y = 0).
/// // Frame2d stores LED colors directly, so we write an LED color here.
/// frame[(0, 0)] = colors::CYAN;
///
/// // Use the embedded-graphics crate to draw a green circle centered in the frame.
/// const DIAMETER: u32 = 6;
/// const CIRCLE_TOP_LEFT: Point = centered_top_left(Frame::WIDTH, Frame::HEIGHT, DIAMETER as usize);
/// Circle::new(CIRCLE_TOP_LEFT, DIAMETER)
///     .into_styled(PrimitiveStyle::with_stroke(colors::LIME.to_rgb888(), 1))
///     .draw(&mut frame)
///     ?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Frame2d<const W: usize, const H: usize>(pub [[RGB8; W]; H]);

impl<const W: usize, const H: usize> Frame2d<W, H> {
    /// The width of the frame.
    pub const WIDTH: usize = W;
    /// The height of the frame.
    pub const HEIGHT: usize = H;
    /// Total pixels in this frame (width × height).
    pub const LEN: usize = W * H;
    /// Frame dimensions as a [`Size`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    pub const SIZE: Size = Size::new(W as u32, H as u32);
    /// Top-left corner coordinate as a [`Point`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    pub const TOP_LEFT: Point = Point::new(0, 0);
    /// Top-right corner coordinate as a [`Point`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    pub const TOP_RIGHT: Point = Point::new((W - 1) as i32, 0);
    /// Bottom-left corner coordinate as a [`Point`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    pub const BOTTOM_LEFT: Point = Point::new(0, (H - 1) as i32);
    /// Bottom-right corner coordinate as a [`Point`].
    ///
    /// For [`embedded-graphics`](https://docs.rs/embedded-graphics) drawing operations.
    pub const BOTTOM_RIGHT: Point = Point::new((W - 1) as i32, (H - 1) as i32);

    /// Create a new blank (all black) frame.
    #[must_use]
    pub const fn new() -> Self {
        Self([[RGB8::new(0, 0, 0); W]; H])
    }

    /// Create a frame filled with a single color.
    #[must_use]
    pub const fn filled(color: RGB8) -> Self {
        Self([[color; W]; H])
    }
}

impl<const W: usize, const H: usize> Deref for Frame2d<W, H> {
    type Target = [[RGB8; W]; H];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<const W: usize, const H: usize> DerefMut for Frame2d<W, H> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<const W: usize, const H: usize> Index<(usize, usize)> for Frame2d<W, H> {
    type Output = RGB8;

    fn index(&self, (x_index, y_index): (usize, usize)) -> &Self::Output {
        assert!(x_index < W, "x_index must be within width");
        assert!(y_index < H, "y_index must be within height");
        &self.0[y_index][x_index]
    }
}

impl<const W: usize, const H: usize> IndexMut<(usize, usize)> for Frame2d<W, H> {
    fn index_mut(&mut self, (x_index, y_index): (usize, usize)) -> &mut Self::Output {
        assert!(x_index < W, "x_index must be within width");
        assert!(y_index < H, "y_index must be within height");
        &mut self.0[y_index][x_index]
    }
}

impl<const W: usize, const H: usize> From<[[RGB8; W]; H]> for Frame2d<W, H> {
    fn from(array: [[RGB8; W]; H]) -> Self {
        Self(array)
    }
}

impl<const W: usize, const H: usize> From<Frame2d<W, H>> for [[RGB8; W]; H] {
    fn from(frame: Frame2d<W, H>) -> Self {
        frame.0
    }
}

impl<const W: usize, const H: usize> Default for Frame2d<W, H> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const W: usize, const H: usize> OriginDimensions for Frame2d<W, H> {
    fn size(&self) -> Size {
        Size::new(W as u32, H as u32)
    }
}

impl<const W: usize, const H: usize> DrawTarget for Frame2d<W, H> {
    type Color = Rgb888;
    type Error = Infallible;

    fn draw_iter<I>(&mut self, pixels: I) -> core::result::Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        for Pixel(coord, color) in pixels {
            let x_index = coord.x;
            let y_index = coord.y;
            if x_index >= 0 && x_index < W as i32 && y_index >= 0 && y_index < H as i32 {
                self.0[y_index as usize][x_index as usize] =
                    RGB8::new(color.r(), color.g(), color.b());
            }
        }
        Ok(())
    }
}