st77916 0.1.0

A Rust driver for the ST77916 TFT-LCD display controller
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
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
//! # ST77916 Driver Crate
//!
//! An `embedded-graphics` compatible driver for the Sitronix ST77916 TFT-LCD
//! display controller (360×390, 262K color).
//!
//! The driver is generic over the communication interface and reset pin,
//! allowing it to work with QSPI, SPI, or any other bus by implementing
//! [`ControllerInterface`] and [`ResetInterface`].
//!
//! ## Buffering modes
//!
//! The builder defaults to an **unbuffered** instance. Three modes are
//! available, selected at compile-time via the `BUF` type parameter:
//!
//! | Mode | Type | RAM | `DrawTarget` | Flush |
//! |------|------|-----|-------------|-------|
//! | Unbuffered (default) | `St77916<I, R>` | 0 | No | `send_pixels()` |
//! | Unbuffered DrawTarget | `St77916<I, R, Unbuffered<C>>` | 0 | Yes (fallible) | Each draw → HW |
//! | **Single-buffered** | `St77916<I, R, Buffered<C>>` | 1× FB | Yes (infallible) | `flush()` (dirty-aware) |
//! | **Double-buffered** | `St77916<I, R, DoubleBuffered<C>>` | 2× FB | Yes (infallible) | `swap_buffers()` + `flush_front()` |
//!
//! ## Single-buffered with dirty tracking
//!
//! The recommended mode for most applications. All `DrawTarget` operations
//! automatically track which rows were modified. [`flush()`](St77916::flush)
//! sends only the dirty band — a single contiguous slice with no allocation.
//! If nothing changed, `flush()` is a no-op.
//!
//! ```ignore
//! let mut display = St77916::builder(iface, reset, size)
//!     .with_init_commands(&PANEL_INIT)
//!     .buffered::<Rgb565>(Framebuffer::heap::<FB_SIZE>())
//!     .build(ColorMode::Rgb565, &mut delay)?;
//!
//! Circle::new(Point::new(100, 100), 50)
//!     .into_styled(PrimitiveStyle::with_fill(Rgb565::RED))
//!     .draw(&mut display)?;
//! display.flush()?;  // sends only the affected rows
//! ```
//!
//! ## Double-buffered
//!
//! Two framebuffers allow overlapping render and flush on hardware with
//! separate CPU and DMA memory buses. Drawing targets the back buffer;
//! [`swap_buffers()`](St77916::swap_buffers) exchanges front and back.
//!
//! ```ignore
//! let mut display = St77916::builder(iface, reset, size)
//!     .with_init_commands(&PANEL_INIT)
//!     .double_buffered::<Rgb565>(fb1, fb2)
//!     .build(ColorMode::Rgb565, &mut delay)?;
//!
//! // render to back buffer...
//! display.swap_buffers();
//! display.flush_front()?;  // send completed frame
//! ```
//!
//! ## Platform access
//!
//! [`interface_mut()`](St77916::interface_mut) exposes the underlying
//! [`ControllerInterface`] for platform-specific operations (e.g.
//! non-blocking DMA flush) that go beyond the trait's synchronous API.
//!
//! ## QSPI Protocol
//!
//! The ST77916 QSPI interface uses the same framing as many Sitronix/Shenghe
//! controllers:
//! - **0x02**: single-line write (command + address + data)
//! - **0x32**: quad-output write (command + address on D0, data on D0–D3)
//! - Address format: `[0x00, cmd_byte, 0x00]` (24-bit)
//!
//! See [`commands`] for the full register set from the datasheet.

#![no_std]

extern crate alloc;

pub mod commands;
mod graphics_core;

use alloc::boxed::Box;
use core::marker::PhantomData;

use embedded_graphics_core::pixelcolor::raw::{RawData, RawU16};
use embedded_graphics_core::pixelcolor::{Gray8, GrayColor, Rgb565, Rgb888, RgbColor};
use embedded_graphics_core::prelude::PixelColor;
use embedded_hal::delay::DelayNs;

// ---------------------------------------------------------------------------
// Display geometry
// ---------------------------------------------------------------------------

/// Display dimensions in pixels.
#[derive(Debug, Clone, Copy)]
pub struct DisplaySize {
    pub width: u16,
    pub height: u16,
}

impl DisplaySize {
    pub const fn new(width: u16, height: u16) -> Self {
        Self { width, height }
    }
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Driver errors, generic over interface and reset error types.
#[derive(Debug)]
pub enum DriverError<InterfaceError, ResetError> {
    InterfaceError(InterfaceError),
    ResetError(ResetError),
    InvalidConfiguration(&'static str),
}

// ---------------------------------------------------------------------------
// Interface traits
// ---------------------------------------------------------------------------

/// Communication interface for the ST77916 (QSPI, SPI, parallel, etc.).
pub trait ControllerInterface {
    type Error;

    /// Send a command byte with no data.
    fn send_command(&mut self, cmd: u8) -> Result<(), Self::Error>;

    /// Send a command byte followed by data parameters.
    fn send_command_with_data(&mut self, cmd: u8, data: &[u8]) -> Result<(), Self::Error>;

    /// Send pixel data to the display RAM.
    ///
    /// Called after `set_window()` has defined the target region via CASET/RASET.
    /// The implementation must send RAMWR (0x2C) for the first chunk and
    /// RAMWRC (0x3C) for subsequent chunks, handling any transport-level
    /// chunking (e.g. DMA size limits).
    fn send_pixels(&mut self, pixels: &[u8]) -> Result<(), Self::Error>;
}

/// Hardware reset control for the ST77916.
pub trait ResetInterface {
    type Error;

    /// Perform the hardware reset sequence.
    ///
    /// Per the ST77916 datasheet (Section 7.4.7, p.42):
    /// pull RESX low for ≥10µs, then high, then wait ≥120ms before commands.
    fn reset(&mut self) -> Result<(), Self::Error>;
}

// ---------------------------------------------------------------------------
// Color mode
// ---------------------------------------------------------------------------

/// Pixel color format for the controller's COLMOD register.
pub enum ColorMode {
    /// 16-bit RGB565 (COLMOD 0x55)
    Rgb565,
    /// 18-bit RGB666 (COLMOD 0x66)
    Rgb666,
}

impl ColorMode {
    pub const fn bytes_per_pixel(&self) -> usize {
        match self {
            ColorMode::Rgb565 => 2,
            ColorMode::Rgb666 => 3,
        }
    }

    pub const fn colmod_param(&self) -> u8 {
        match self {
            ColorMode::Rgb565 => commands::COLMOD_RGB565,
            ColorMode::Rgb666 => commands::COLMOD_RGB666,
        }
    }
}

// ---------------------------------------------------------------------------
// Color encoding trait
// ---------------------------------------------------------------------------

/// Pixel color encoding for the ST77916 framebuffer.
///
/// Implementors define how a color is serialized into the framebuffer's byte
/// layout (big-endian for RGB565/RGB888, single byte for Gray8).
///
/// The trait provides default `fill_row` and `fill_buf` methods that fill
/// memory by repeating `encode()`. Color types can override these for faster
/// fills — for example, [`Rgb565`] detects uniform high/low bytes and uses
/// `buf.fill()` for a single-byte memset when possible.
pub trait St77916Color: PixelColor + Copy {
    const BYTES_PER_PIXEL: usize;

    /// Encode a single pixel into `out[..BYTES_PER_PIXEL]` in big-endian order.
    fn encode(self, out: &mut [u8]);

    /// Fill a row slice with a single repeated color.
    fn fill_row(color: Self, row: &mut [u8]) {
        let bpp = Self::BYTES_PER_PIXEL;
        let mut tmp = [0u8; 4];
        color.encode(&mut tmp[..bpp]);
        for chunk in row.chunks_exact_mut(bpp) {
            chunk.copy_from_slice(&tmp[..bpp]);
        }
    }

    /// Fill an entire buffer with a single color.
    fn fill_buf(color: Self, buf: &mut [u8]) {
        Self::fill_row(color, buf);
    }
}

impl St77916Color for Rgb565 {
    const BYTES_PER_PIXEL: usize = 2;

    #[inline]
    fn encode(self, out: &mut [u8]) {
        let raw = RawU16::from(self).into_inner();
        out[0] = (raw >> 8) as u8;
        out[1] = raw as u8;
    }

    fn fill_buf(color: Self, buf: &mut [u8]) {
        let raw = RawU16::from(color).into_inner();
        let hi = (raw >> 8) as u8;
        let lo = raw as u8;
        if hi == lo {
            buf.fill(hi);
        } else {
            for chunk in buf.chunks_exact_mut(2) {
                chunk[0] = hi;
                chunk[1] = lo;
            }
        }
    }
}

impl St77916Color for Rgb888 {
    const BYTES_PER_PIXEL: usize = 3;

    #[inline]
    fn encode(self, out: &mut [u8]) {
        out[0] = self.r();
        out[1] = self.g();
        out[2] = self.b();
    }

    fn fill_buf(color: Self, buf: &mut [u8]) {
        let r = color.r();
        let g = color.g();
        let b = color.b();
        if r == g && r == b {
            buf.fill(r);
        } else {
            for chunk in buf.chunks_exact_mut(3) {
                chunk[0] = r;
                chunk[1] = g;
                chunk[2] = b;
            }
        }
    }
}

impl St77916Color for Gray8 {
    const BYTES_PER_PIXEL: usize = 1;

    #[inline]
    fn encode(self, out: &mut [u8]) {
        out[0] = self.luma();
    }

    fn fill_buf(color: Self, buf: &mut [u8]) {
        buf.fill(color.luma());
    }
}

// ---------------------------------------------------------------------------
// Framebuffer helpers
// ---------------------------------------------------------------------------

/// Compute framebuffer size in bytes for a given display and color mode.
pub const fn framebuffer_size(display: DisplaySize, color: ColorMode) -> usize {
    (display.width as usize) * (display.height as usize) * color.bytes_per_pixel()
}

/// Holds either a static or heap-allocated framebuffer.
pub enum Framebuffer {
    Static(&'static mut [u8]),
    Heap(Box<[u8]>),
}

impl Framebuffer {
    /// Allocate a zeroed heap framebuffer of `N` bytes.
    pub fn heap<const N: usize>() -> Self {
        Framebuffer::Heap(Box::new([0u8; N]))
    }

    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        match self {
            Framebuffer::Static(arr) => arr,
            Framebuffer::Heap(boxed) => boxed,
        }
    }

    pub fn as_slice(&self) -> &[u8] {
        match self {
            Framebuffer::Static(arr) => arr,
            Framebuffer::Heap(boxed) => boxed,
        }
    }

    pub fn len(&self) -> usize {
        self.as_slice().len()
    }

    pub fn is_empty(&self) -> bool {
        self.as_slice().is_empty()
    }
}

impl core::ops::Deref for Framebuffer {
    type Target = [u8];
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl core::ops::DerefMut for Framebuffer {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_slice()
    }
}

// ---------------------------------------------------------------------------
// Dirty band tracker
// ---------------------------------------------------------------------------

/// Tracks the dirty vertical band of the framebuffer.
///
/// When `y_min > y_max` the region is clean (nothing to flush).
/// Draw operations expand the band; [`flush`](St77916::flush) resets it.
#[derive(Debug, Clone, Copy)]
pub(crate) struct DirtyBand {
    y_min: u16,
    y_max: u16,
}

impl DirtyBand {
    /// A clean (empty) dirty region.
    pub fn clean() -> Self {
        Self {
            y_min: u16::MAX,
            y_max: 0,
        }
    }

    /// Returns `true` if no pixels have been marked dirty.
    #[inline]
    pub fn is_clean(&self) -> bool {
        self.y_min > self.y_max
    }

    /// Expand the dirty band to include rows `y_start..=y_end`.
    #[inline]
    pub fn mark(&mut self, y_start: u16, y_end: u16) {
        self.y_min = self.y_min.min(y_start);
        self.y_max = self.y_max.max(y_end);
    }

    /// Mark the entire display dirty.
    #[inline]
    pub fn mark_all(&mut self, height: u16) {
        self.y_min = 0;
        self.y_max = height - 1;
    }

    /// Reset to clean.
    #[inline]
    pub fn reset(&mut self) {
        *self = Self::clean();
    }
}

// ---------------------------------------------------------------------------
// Buffered state marker
// ---------------------------------------------------------------------------

/// Marker type for a buffered [`St77916`] instance.
///
/// Wraps a [`Framebuffer`] and carries the pixel color format as a type
/// parameter for `embedded-graphics` [`DrawTarget`](embedded_graphics_core::draw_target::DrawTarget)
/// support.
pub struct Buffered<COLOR: St77916Color = Rgb565> {
    data: Framebuffer,
    dirty: DirtyBand,
    _color: PhantomData<COLOR>,
}

/// Marker type for a double-buffered [`St77916`] instance.
///
/// Holds two [`Framebuffer`]s (front and back). Drawing goes to the back
/// buffer; [`swap_buffers`](St77916::swap_buffers) exchanges them, and
/// [`flush_front`](St77916::flush_front) sends the front buffer to the
/// display. This lets the CPU render the next frame while DMA flushes
/// the previous one.
pub struct DoubleBuffered<COLOR: St77916Color = Rgb565> {
    bufs: [Framebuffer; 2],
    back_idx: usize,
    _color: PhantomData<COLOR>,
}

impl<COLOR: St77916Color> DoubleBuffered<COLOR> {
    fn back(&self) -> &Framebuffer {
        &self.bufs[self.back_idx]
    }

    fn back_mut(&mut self) -> &mut Framebuffer {
        &mut self.bufs[self.back_idx]
    }

    fn front(&self) -> &Framebuffer {
        &self.bufs[self.back_idx ^ 1]
    }
}

/// Marker type for an unbuffered [`St77916`] with `DrawTarget` support.
///
/// Unlike [`Buffered`], this allocates no memory. Each `DrawTarget` draw
/// operation sends pixels directly to the display over the bus. This is
/// zero-cost in RAM but means every draw call is a hardware transaction.
///
/// Create via the builder:
/// ```ignore
/// St77916::builder(iface, reset, size)
///     .unbuffered::<Rgb565>()
///     .build(ColorMode::Rgb565, &mut delay)?;
/// ```
pub struct Unbuffered<COLOR: St77916Color = Rgb565> {
    _color: PhantomData<COLOR>,
}

// ---------------------------------------------------------------------------
// Driver
// ---------------------------------------------------------------------------

/// Driver for the ST77916 TFT-LCD display controller.
///
/// Generic over:
/// - `IFACE`: communication interface ([`ControllerInterface`])
/// - `RST`: reset pin ([`ResetInterface`])
/// - `BUF`: buffer state — `()` for unbuffered (default),
///   [`Buffered<COLOR>`] for an internal framebuffer with `DrawTarget`, or
///   [`Unbuffered<COLOR>`] for `DrawTarget` without a framebuffer.
pub struct St77916<IFACE, RST, BUF = ()>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    interface: IFACE,
    reset: RST,
    config: DisplaySize,
    buffer: BUF,
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

/// Builder for [`St77916`].
///
/// Defaults to an unbuffered instance. Call [`.buffered()`](Self::buffered)
/// before `.build()` to opt into a framebuffer.
pub struct St77916Builder<IFACE, RST, BUF = ()>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    interface: IFACE,
    reset: RST,
    config: DisplaySize,
    init_commands: Option<&'static [(u8, &'static [u8], u16)]>,
    buffer: BUF,
}

// -- Methods available on all builder variants --

impl<IFACE, RST, BUF> St77916Builder<IFACE, RST, BUF>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Provide a custom init command sequence.
    ///
    /// Each entry is `(command, &data, delay_ms)`. The caller is responsible
    /// for the complete sequence including page selects (CSC1–CSC4),
    /// sleep-out, COLMOD, and display-on.
    pub fn with_init_commands(mut self, commands: &'static [(u8, &'static [u8], u16)]) -> Self {
        self.init_commands = Some(commands);
        self
    }
}

// -- Unbuffered builder: can transition to buffered, or build directly --

impl<IFACE, RST> St77916Builder<IFACE, RST, ()>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Opt into an internal framebuffer.
    ///
    /// The returned builder will produce a [`St77916`] with `DrawTarget`
    /// support. Specify the pixel color format via turbofish:
    ///
    /// ```ignore
    /// .buffered::<Rgb565>(Framebuffer::heap::<FB_SIZE>())
    /// ```
    pub fn buffered<COLOR: St77916Color>(
        self,
        framebuffer: Framebuffer,
    ) -> St77916Builder<IFACE, RST, Buffered<COLOR>> {
        St77916Builder {
            interface: self.interface,
            reset: self.reset,
            config: self.config,
            init_commands: self.init_commands,
            buffer: Buffered {
                data: framebuffer,
                dirty: DirtyBand::clean(),
                _color: PhantomData,
            },
        }
    }

    /// Opt into double-buffered rendering.
    ///
    /// Two framebuffers allow overlapping rendering and flushing.
    /// Drawing goes to the back buffer; call
    /// [`swap_buffers`](St77916::swap_buffers) to exchange, then
    /// [`flush_front`](St77916::flush_front) to send the front buffer
    /// to the display.
    ///
    /// ```ignore
    /// .double_buffered::<Rgb565>(
    ///     Framebuffer::heap::<FB_SIZE>(),
    ///     Framebuffer::heap::<FB_SIZE>(),
    /// )
    /// ```
    pub fn double_buffered<COLOR: St77916Color>(
        self,
        fb1: Framebuffer,
        fb2: Framebuffer,
    ) -> St77916Builder<IFACE, RST, DoubleBuffered<COLOR>> {
        St77916Builder {
            interface: self.interface,
            reset: self.reset,
            config: self.config,
            init_commands: self.init_commands,
            buffer: DoubleBuffered {
                bufs: [fb1, fb2],
                back_idx: 0,
                _color: PhantomData,
            },
        }
    }

    /// Opt into `DrawTarget` support without a framebuffer.
    ///
    /// Each draw operation sends pixels directly to the display. Zero RAM
    /// cost, but every draw is a hardware transaction.
    ///
    /// ```ignore
    /// .unbuffered::<Rgb565>()
    /// ```
    pub fn unbuffered<COLOR: St77916Color>(self) -> St77916Builder<IFACE, RST, Unbuffered<COLOR>> {
        St77916Builder {
            interface: self.interface,
            reset: self.reset,
            config: self.config,
            init_commands: self.init_commands,
            buffer: Unbuffered {
                _color: PhantomData,
            },
        }
    }

    /// Build an unbuffered driver instance (no `DrawTarget`).
    pub fn build<DELAY>(
        self,
        color: ColorMode,
        delay: &mut DELAY,
    ) -> Result<St77916<IFACE, RST>, DriverError<IFACE::Error, RST::Error>>
    where
        DELAY: DelayNs,
    {
        let mut driver = St77916 {
            interface: self.interface,
            reset: self.reset,
            config: self.config,
            buffer: (),
        };
        driver.hard_reset()?;
        run_init(&mut driver.interface, self.init_commands, delay, color)
            .map_err(DriverError::InterfaceError)?;
        Ok(driver)
    }
}

// -- Unbuffered builder: build with DrawTarget but no framebuffer --

impl<IFACE, RST, COLOR: St77916Color> St77916Builder<IFACE, RST, Unbuffered<COLOR>>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Build an unbuffered driver with `DrawTarget` support.
    #[allow(clippy::type_complexity)]
    pub fn build<DELAY>(
        self,
        color: ColorMode,
        delay: &mut DELAY,
    ) -> Result<St77916<IFACE, RST, Unbuffered<COLOR>>, DriverError<IFACE::Error, RST::Error>>
    where
        DELAY: DelayNs,
    {
        let mut driver = St77916 {
            interface: self.interface,
            reset: self.reset,
            config: self.config,
            buffer: self.buffer,
        };
        driver.hard_reset()?;
        run_init(&mut driver.interface, self.init_commands, delay, color)
            .map_err(DriverError::InterfaceError)?;
        Ok(driver)
    }
}

// -- Buffered builder: build with framebuffer --

impl<IFACE, RST, COLOR: St77916Color> St77916Builder<IFACE, RST, Buffered<COLOR>>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Build a buffered driver instance with `DrawTarget` support.
    #[allow(clippy::type_complexity)]
    pub fn build<DELAY>(
        self,
        color: ColorMode,
        delay: &mut DELAY,
    ) -> Result<St77916<IFACE, RST, Buffered<COLOR>>, DriverError<IFACE::Error, RST::Error>>
    where
        DELAY: DelayNs,
    {
        let mut driver = St77916 {
            interface: self.interface,
            reset: self.reset,
            config: self.config,
            buffer: self.buffer,
        };
        driver.hard_reset()?;
        run_init(&mut driver.interface, self.init_commands, delay, color)
            .map_err(DriverError::InterfaceError)?;
        Ok(driver)
    }
}

// -- DoubleBuffered builder: build with two framebuffers --

impl<IFACE, RST, COLOR: St77916Color> St77916Builder<IFACE, RST, DoubleBuffered<COLOR>>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Build a double-buffered driver instance with `DrawTarget` support.
    #[allow(clippy::type_complexity)]
    pub fn build<DELAY>(
        self,
        color: ColorMode,
        delay: &mut DELAY,
    ) -> Result<St77916<IFACE, RST, DoubleBuffered<COLOR>>, DriverError<IFACE::Error, RST::Error>>
    where
        DELAY: DelayNs,
    {
        let mut driver = St77916 {
            interface: self.interface,
            reset: self.reset,
            config: self.config,
            buffer: self.buffer,
        };
        driver.hard_reset()?;
        run_init(&mut driver.interface, self.init_commands, delay, color)
            .map_err(DriverError::InterfaceError)?;
        Ok(driver)
    }
}

// ---------------------------------------------------------------------------
// Shared init helper
// ---------------------------------------------------------------------------

fn run_init<IFACE: ControllerInterface, DELAY: DelayNs>(
    interface: &mut IFACE,
    init_commands: Option<&[(u8, &[u8], u16)]>,
    delay: &mut DELAY,
    color: ColorMode,
) -> Result<(), IFACE::Error> {
    if let Some(cmds) = init_commands {
        for &(cmd, data, delay_ms) in cmds {
            if data.is_empty() {
                interface.send_command(cmd)?;
            } else {
                interface.send_command_with_data(cmd, data)?;
            }
            if delay_ms > 0 {
                delay.delay_ms(delay_ms as u32);
            }
        }
    } else {
        interface.send_command(commands::SWRESET)?;
        delay.delay_ms(120);
        interface.send_command(commands::SLPOUT)?;
        delay.delay_ms(120);
        interface.send_command_with_data(commands::COLMOD, &[color.colmod_param()])?;
        delay.delay_ms(5);
        interface.send_command_with_data(commands::MADCTL, &[0x00])?;
        interface.send_command(commands::INVON)?;
        interface.send_command(commands::DISPON)?;
        delay.delay_ms(20);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Methods available on ALL variants (unbuffered and buffered)
// ---------------------------------------------------------------------------

impl<IFACE, RST> St77916<IFACE, RST>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Create a builder.
    ///
    /// ```ignore
    /// // Unbuffered (default):
    /// let display = St77916::builder(iface, reset, size)
    ///     .build(ColorMode::Rgb565, &mut delay)?;
    ///
    /// // Buffered:
    /// let display = St77916::builder(iface, reset, size)
    ///     .buffered::<Rgb565>(Framebuffer::heap::<FB_SIZE>())
    ///     .build(ColorMode::Rgb565, &mut delay)?;
    /// ```
    pub fn builder(
        interface: IFACE,
        reset: RST,
        config: DisplaySize,
    ) -> St77916Builder<IFACE, RST> {
        St77916Builder {
            interface,
            reset,
            config,
            init_commands: None,
            buffer: (),
        }
    }
}

impl<IFACE, RST, BUF> St77916<IFACE, RST, BUF>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Mutable access to the underlying communication interface.
    ///
    /// Useful for platform-specific operations like non-blocking flush
    /// that go beyond the [`ControllerInterface`] trait.
    pub fn interface_mut(&mut self) -> &mut IFACE {
        &mut self.interface
    }

    /// Hardware reset via the [`ResetInterface`].
    pub fn hard_reset(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.reset.reset().map_err(DriverError::ResetError)
    }

    /// Send a command with no data.
    pub fn send_command(&mut self, cmd: u8) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.interface
            .send_command(cmd)
            .map_err(DriverError::InterfaceError)
    }

    /// Send a command with data parameters.
    pub fn send_command_with_data(
        &mut self,
        cmd: u8,
        data: &[u8],
    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.interface
            .send_command_with_data(cmd, data)
            .map_err(DriverError::InterfaceError)
    }

    /// Send pixel data to the display.
    ///
    /// Call [`set_window`](Self::set_window) first to define the target region.
    pub fn send_pixels(
        &mut self,
        pixels: &[u8],
    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.interface
            .send_pixels(pixels)
            .map_err(DriverError::InterfaceError)
    }

    /// Set the active drawing window (CASET + RASET).
    pub fn set_window(
        &mut self,
        x_start: u16,
        y_start: u16,
        x_end: u16,
        y_end: u16,
    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.send_command_with_data(
            commands::CASET,
            &[
                (x_start >> 8) as u8,
                (x_start & 0xFF) as u8,
                (x_end >> 8) as u8,
                (x_end & 0xFF) as u8,
            ],
        )?;
        self.send_command_with_data(
            commands::RASET,
            &[
                (y_start >> 8) as u8,
                (y_start & 0xFF) as u8,
                (y_end >> 8) as u8,
                (y_end & 0xFF) as u8,
            ],
        )
    }

    /// Convenience: set window to full display and send pixels.
    pub fn flush_pixels(
        &mut self,
        pixels: &[u8],
    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.set_window(0, 0, self.config.width - 1, self.config.height - 1)?;
        self.send_pixels(pixels)
    }

    /// Enter sleep mode.
    pub fn sleep_in<DELAY>(
        &mut self,
        delay: &mut DELAY,
    ) -> Result<(), DriverError<IFACE::Error, RST::Error>>
    where
        DELAY: DelayNs,
    {
        self.send_command(commands::SLPIN)?;
        delay.delay_ms(5);
        Ok(())
    }

    /// Exit sleep mode.
    pub fn sleep_out<DELAY>(
        &mut self,
        delay: &mut DELAY,
    ) -> Result<(), DriverError<IFACE::Error, RST::Error>>
    where
        DELAY: DelayNs,
    {
        self.send_command(commands::SLPOUT)?;
        delay.delay_ms(120);
        Ok(())
    }

    /// Turn display off.
    pub fn display_off(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.send_command(commands::DISPOFF)
    }

    /// Turn display on.
    pub fn display_on(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.send_command(commands::DISPON)
    }

    /// Set MADCTL (orientation, RGB/BGR order, scan direction).
    pub fn set_madctl(&mut self, value: u8) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.send_command_with_data(commands::MADCTL, &[value])
    }

    /// Set display brightness (0x00–0xFF).
    pub fn set_brightness(
        &mut self,
        value: u8,
    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.send_command_with_data(commands::WRDISBV, &[value])
    }

    /// Get the configured display size.
    pub fn size(&self) -> DisplaySize {
        self.config
    }
}

// ---------------------------------------------------------------------------
// Methods only on the BUFFERED variant
// ---------------------------------------------------------------------------

impl<IFACE, RST, COLOR: St77916Color> St77916<IFACE, RST, Buffered<COLOR>>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Flush only the dirty region of the framebuffer to the display.
    ///
    /// If nothing has been drawn since the last flush, this is a no-op.
    /// The dirty region is tracked automatically by all `DrawTarget` operations
    /// and is reset after each flush.
    pub fn flush(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        if self.buffer.dirty.is_clean() {
            return Ok(());
        }

        let y_min = self.buffer.dirty.y_min;
        let y_max = self.buffer.dirty.y_max;
        let bpp = COLOR::BYTES_PER_PIXEL;
        let stride = self.config.width as usize * bpp;

        self.set_window(0, y_min, self.config.width - 1, y_max)?;

        let start = y_min as usize * stride;
        let end = (y_max as usize + 1) * stride;
        self.interface
            .send_pixels(&self.buffer.data[start..end])
            .map_err(DriverError::InterfaceError)?;

        self.buffer.dirty.reset();
        Ok(())
    }

    /// Flush the entire framebuffer to the display, ignoring the dirty region.
    ///
    /// Use this after direct framebuffer manipulation via [`framebuffer_mut()`](Self::framebuffer_mut),
    /// or when the display contents may be out of sync (e.g., after wake from sleep).
    pub fn full_flush(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.set_window(0, 0, self.config.width - 1, self.config.height - 1)?;
        self.interface
            .send_pixels(&self.buffer.data)
            .map_err(DriverError::InterfaceError)?;
        self.buffer.dirty.reset();
        Ok(())
    }

    /// Get the framebuffer as a mutable byte slice.
    ///
    /// After writing directly to the framebuffer, call [`mark_dirty()`](Self::mark_dirty)
    /// or [`mark_all_dirty()`](Self::mark_all_dirty) so the next [`flush()`](Self::flush)
    /// includes the changes.
    pub fn framebuffer_mut(&mut self) -> &mut [u8] {
        self.buffer.data.as_mut_slice()
    }

    /// Get the framebuffer as an immutable byte slice.
    pub fn framebuffer(&self) -> &[u8] {
        self.buffer.data.as_slice()
    }

    /// Mark a vertical band as dirty so the next [`flush()`](Self::flush) will include it.
    pub fn mark_dirty(&mut self, y_start: u16, y_end: u16) {
        self.buffer.dirty.mark(y_start, y_end);
    }

    /// Mark the entire framebuffer as dirty.
    pub fn mark_all_dirty(&mut self) {
        self.buffer.dirty.mark_all(self.config.height);
    }

    /// Returns `true` if no draw operations have occurred since the last flush.
    pub fn is_clean(&self) -> bool {
        self.buffer.dirty.is_clean()
    }

    /// Flush a rectangular sub-region of the framebuffer.
    ///
    /// All coordinates are **inclusive** (matching the ST77916 CASET/RASET
    /// convention). Sends each row directly from the framebuffer without
    /// allocation. Does not interact with the dirty tracker — this is a
    /// manual override for callers who know exactly what region to flush.
    pub fn partial_flush(
        &mut self,
        x_start: u16,
        x_end: u16,
        y_start: u16,
        y_end: u16,
    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.set_window(x_start, y_start, x_end, y_end)?;
        let bpp = COLOR::BYTES_PER_PIXEL;
        let fb_stride = self.config.width as usize * bpp;
        let row_width = (x_end - x_start + 1) as usize * bpp;

        for y in y_start..=y_end {
            let offset = y as usize * fb_stride + x_start as usize * bpp;
            let row_end = offset + row_width;
            if row_end <= self.buffer.data.len() {
                self.interface
                    .send_pixels(&self.buffer.data[offset..row_end])
                    .map_err(DriverError::InterfaceError)?;
            } else {
                return Err(DriverError::InvalidConfiguration(
                    "Framebuffer slice out of bounds",
                ));
            }
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Methods only on the DOUBLE-BUFFERED variant
// ---------------------------------------------------------------------------

impl<IFACE, RST, COLOR: St77916Color> St77916<IFACE, RST, DoubleBuffered<COLOR>>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Swap front and back buffers.
    ///
    /// After this call, the previous back buffer becomes the front (ready
    /// for flushing) and vice versa.
    pub fn swap_buffers(&mut self) {
        self.buffer.back_idx ^= 1;
    }

    /// Flush the front buffer (the one NOT being rendered into) to the display.
    pub fn flush_front(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.set_window(0, 0, self.config.width - 1, self.config.height - 1)?;
        self.interface
            .send_pixels(self.buffer.front())
            .map_err(DriverError::InterfaceError)
    }

    /// Flush the back buffer (same as single-buffered `flush()`).
    pub fn flush(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
        self.set_window(0, 0, self.config.width - 1, self.config.height - 1)?;
        self.interface
            .send_pixels(self.buffer.back())
            .map_err(DriverError::InterfaceError)
    }

    /// Get the back buffer as a mutable byte slice.
    pub fn back_buffer_mut(&mut self) -> &mut [u8] {
        self.buffer.back_mut().as_mut_slice()
    }

    /// Get the front buffer as an immutable byte slice.
    pub fn front_buffer(&self) -> &[u8] {
        self.buffer.front().as_slice()
    }
}