device-envoy-core 0.1.4

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
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
//! Browser implementations for CYD, buttons, flash storage, clocks, DNS, and simulators.
//!
//! Enable the `wasm` feature when compiling application code for a browser.
//!
//! ## Implementations
//!
//! - [`CydWasm`] provides an HTML-canvas display and browser pointer-based touch
//!   input.
//! - [`ButtonWasm`] provides browser-controlled button input.
//! - [`FlashBlockWasm`] provides flash-block storage backed by browser local
//!   storage.
//! - [`ClockSyncWasm`] provides browser clock synchronization; see the
//!   [`clock` module](clock).
//! - [`DnsSimulatorWasm`] provides deterministic DNS simulation; see the
//!   [`dns` module](dns).
//! - [`CydSimulatorWasm`] and [`WifiSimulatorWasm`] provide higher-level browser
//!   simulators; see the [`simulator` module](simulator).
//!
//! The [`cyd_web` module](cyd_web) supplies the browser shell for CYD
//! applications, and [`next_animation_frame`] provides browser frame pacing.

mod animation_frame;
pub mod clock;
pub mod cyd_web;
pub mod dns;
pub mod simulator;

use core::{
    cell::{Cell, RefCell},
    convert::Infallible,
    ops::Range,
};
use std::{collections::VecDeque, rc::Rc};

use crate::cyd::{
    Cyd, CydDisplay, CydTouch,
    backend::{CalibrationConfig, RawTouchEvent},
    display::{CydFrame, Orientation},
    touch::{RawPoint, TouchEvent},
};
use crate::{
    button::{__ButtonMonitor, BUTTON_POLL_INTERVAL, Button},
    flash_block::{
        Error as FlashBlockError, FlashBlock, FlashDevice, clear_block, load_block, save_block,
    },
    pixel_target::{PixelTarget, rgb888_from_rgb565},
};
use embassy_time::Timer;
use embedded_graphics::pixelcolor::RgbColor;
use embedded_graphics::{
    Drawable, Pixel,
    mono_font::{MonoFont, MonoTextStyle},
    pixelcolor::{IntoStorage, Rgb565, Rgb888},
    prelude::{Dimensions, DrawTarget, Point, Size},
    primitives::Rectangle,
    text::{Baseline, Text},
};
use serde::{Deserialize, Serialize};
use wasm_bindgen::Clamped;
use web_sys::{CanvasRenderingContext2d, ImageData, Storage};

pub use animation_frame::next_animation_frame;
pub use clock::ClockSyncWasm;
pub use dns::DnsSimulatorWasm;
pub use simulator::{
    CydSimulatorControlWasm, CydSimulatorWasm, WifiConnectOutcome, WifiSimulatorWasm,
};

const FLASH_BLOCK_SIZE: usize = 4096;
const FLASH_BLOCK_OFFSET: u32 = 0;
const FLASH_ERASED_BYTE: u8 = 0xFF;

const fn identity_calibration_config() -> CalibrationConfig {
    CalibrationConfig::new(1.0, 0.0, 0.0, 0.0, 1.0, 0.0)
}

#[cfg_attr(
    feature = "doc-images",
    doc = ::embed_doc_image::embed_image!(
        "linkage_blaze_gallery",
        "docs/assets/linkage_blaze_gallery.png"
    )
)]
/// A CYD device rendered to an HTML canvas with browser-supplied touch input.
///
/// `CydWasm` implements the portable [`Cyd`] interface used by the hardware
/// implementations. Write normal application code against the
/// [`cyd`](crate::cyd) module and its [`CydDisplay`] drawing APIs; only browser
/// setup and input plumbing need WASM-specific types.
///
/// Browser pointer handlers feed touch input through [`CydTouchWasmSource`],
/// where it is calibrated and oriented like hardware touch input.
/// [`CydFrameWasm::flush`] presents the current frame and awaits the next
/// browser animation frame for frame pacing.
///
/// ## See CYD in action
///
/// [Linkage Blaze] demonstrates animated clocks, mechanisms, and figures built
/// with Device Envoy's portable CYD display APIs. Explore the examples in the
/// [interactive Linkage Blaze gallery].
#[cfg_attr(
    feature = "doc-images",
    doc = "\n[![Linkage Blaze gallery showing CYD applications][linkage_blaze_gallery]][interactive Linkage Blaze gallery]\n"
)]
///
/// [Linkage Blaze]: https://github.com/CarlKCarlK/linkage-blaze
/// [interactive Linkage Blaze gallery]: https://carlkcarlk.github.io/linkage-blaze/demos/
///
/// # Example
///
/// ```rust,no_run
/// use device_envoy_core::{
///     cyd::display::Orientation,
///     wasm::{CydTouchWasmSource, CydWasm},
/// };
/// use embedded_graphics::{
///     mono_font::ascii::FONT_6X10,
///     pixelcolor::{Rgb888, RgbColor},
/// };
/// use wasm_bindgen::{JsCast, JsValue};
/// use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement};
///
/// fn create_cyd(canvas: HtmlCanvasElement) -> Result<CydWasm, JsValue> {
///     let orientation = Orientation::Landscape;
///     canvas.set_width(orientation.width());
///     canvas.set_height(orientation.height());
///     let context = canvas
///         .get_context("2d")?
///         .ok_or_else(|| JsValue::from_str("2D canvas context unavailable"))?
///         .dyn_into::<CanvasRenderingContext2d>()?;
///
///     Ok(CydWasm::new(
///         context,
///         orientation,
///         Rgb888::BLACK,
///         Rgb888::WHITE,
///         &FONT_6X10,
///         CydTouchWasmSource::new(),
///     ))
/// }
/// ```
pub struct CydWasm {
    display: CydDisplayWasm,
    touch: CydTouchWasm,
}

/// Owned HTML-canvas display half of [`CydWasm`].
#[derive(Clone)]
pub struct CydDisplayWasm {
    context: CanvasRenderingContext2d,
    size: Size,
    orientation: Orientation,
    background_color: Rgb888,
    foreground_color: Rgb888,
    background565: Rgb565,
    foreground565: Rgb565,
    font: &'static MonoFont<'static>,
}

/// Owned calibrated and oriented touch half of [`CydWasm`].
#[derive(Clone)]
pub struct CydTouchWasm {
    raw_touch_events: RawTouchEvents,
    interaction_state: Rc<Cell<InteractionState>>,
    latest_raw_point: Rc<Cell<Option<RawPoint>>>,
    calibration_config: CalibrationConfig,
    orientation: Orientation,
}

/// Input source used by browser pointer handlers to feed touch events to a [`CydWasm`].
#[derive(Clone)]
pub struct CydTouchWasmSource {
    raw_touch_events: RawTouchEvents,
    interaction_state: Rc<Cell<InteractionState>>,
    latest_raw_point: Rc<Cell<Option<RawPoint>>>,
}

/// Browser button state controlled by a [`ButtonWasmSource`].
pub struct ButtonWasm {
    pressed: Rc<Cell<bool>>,
}

#[derive(Clone)]
/// Input source used by browser controls to update a [`ButtonWasm`].
pub struct ButtonWasmSource {
    pressed: Rc<Cell<bool>>,
}

/// Flash-block storage backed by browser local storage.
pub struct FlashBlockWasm {
    flash_device: FlashDeviceWasm,
}

type RawTouchEvents = Rc<RefCell<VecDeque<RawTouchEvent>>>;

struct FlashDeviceWasm {
    storage: Storage,
    storage_key: String,
    bytes: [u8; FLASH_BLOCK_SIZE],
}

/// Errors reported by browser-backed WASM support.
///
/// These errors concern persistent browser storage used by [`FlashBlockWasm`];
/// display drawing and calibrated touch use the in-memory simulator state.
#[derive(Debug)]
pub enum Error {
    /// The browser does not provide the requested storage facility.
    StorageUnavailable,
    /// The browser rejected or failed a storage operation.
    StorageAccess,
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum InteractionState {
    Ready,
    PointerDown,
    WaitingForFreshPress,
}

impl CydWasm {
    /// Construct a simulated CYD that presents frames onto `context`.
    ///
    /// `orientation` determines the logical display size and touch mapping. The
    /// caller should size the context's canvas to match. Colors and `font`
    /// configure the portable [`CydDisplay`] helpers, and `touch_source`
    /// receives input from the browser's pointer handlers.
    #[must_use]
    pub fn new(
        context: CanvasRenderingContext2d,
        orientation: Orientation,
        background_color: Rgb888,
        foreground_color: Rgb888,
        font: &'static MonoFont<'static>,
        touch_source: CydTouchWasmSource,
    ) -> Self {
        let display = CydDisplayWasm {
            context: context.clone(),
            size: orientation.size(),
            orientation,
            background_color,
            foreground_color,
            background565: Rgb565::from(background_color),
            foreground565: Rgb565::from(foreground_color),
            font,
        };
        let touch = CydTouchWasm {
            raw_touch_events: touch_source.raw_touch_events,
            interaction_state: touch_source.interaction_state,
            latest_raw_point: touch_source.latest_raw_point,
            calibration_config: identity_calibration_config(),
            orientation,
        };
        Self { display, touch }
    }

    #[must_use]
    /// Clone the input source that feeds browser pointer events to this device.
    pub fn touch_source(&self) -> CydTouchWasmSource {
        CydTouchWasmSource {
            raw_touch_events: self.touch.raw_touch_events.clone(),
            interaction_state: self.touch.interaction_state.clone(),
            latest_raw_point: self.touch.latest_raw_point.clone(),
        }
    }

    #[must_use]
    /// Clone the HTML-canvas display component.
    pub fn display(&self) -> CydDisplayWasm {
        self.display.clone()
    }

    /// Return owned display and calibrated touch handles.
    ///
    /// The handles share the same browser canvas and touch-event state as this
    /// device.
    #[must_use]
    pub fn owned_parts(&self) -> (CydDisplayWasm, CydTouchWasm) {
        (self.display.clone(), self.touch.clone())
    }
}

impl Cyd for CydWasm {
    /// Browser CYD display and touch operations are infallible.
    type Error = Infallible;
    type Display = CydDisplayWasm;
    type Touch = CydTouchWasm;

    fn parts(&mut self) -> (&mut Self::Display, &mut Self::Touch) {
        (&mut self.display, &mut self.touch)
    }

    fn orientation(&self) -> Orientation {
        self.display.orientation
    }
}

impl CydTouchWasmSource {
    /// Construct an empty browser touch-event source.
    #[must_use]
    pub fn new() -> Self {
        Self {
            raw_touch_events: Rc::new(RefCell::new(VecDeque::new())),
            interaction_state: Rc::new(Cell::new(InteractionState::Ready)),
            latest_raw_point: Rc::new(Cell::new(None)),
        }
    }

    /// Queue a calibrated-panel point in fixed landscape coordinates.
    ///
    /// The browser control converts logical canvas coordinates to this raw
    /// calibration boundary before calling the source. `CydTouchWasm::try_read`
    /// performs the one runtime-orientation mapping for the application.
    pub fn touch_down(&self, x: f32, y: f32) {
        match self.interaction_state.get() {
            InteractionState::WaitingForFreshPress => return,
            InteractionState::Ready | InteractionState::PointerDown => {
                self.interaction_state.set(InteractionState::PointerDown);
            }
        }
        assert!((0.0..=u16::MAX as f32).contains(&x));
        assert!((0.0..=u16::MAX as f32).contains(&y));
        let raw_point = RawPoint {
            x: x as u16,
            y: y as u16,
        };
        self.latest_raw_point.set(Some(raw_point));
        self.push(RawTouchEvent::Down {
            raw_x: raw_point.x,
            raw_y: raw_point.y,
        });
    }

    /// Queue a movement point in fixed landscape calibration coordinates.
    pub fn touch_move(&self, x: f32, y: f32) {
        if self.interaction_state.get() != InteractionState::PointerDown {
            return;
        }
        assert!((0.0..=u16::MAX as f32).contains(&x));
        assert!((0.0..=u16::MAX as f32).contains(&y));
        let raw_point = RawPoint {
            x: x as u16,
            y: y as u16,
        };
        self.latest_raw_point.set(Some(raw_point));
        self.push(RawTouchEvent::Move {
            raw_x: raw_point.x,
            raw_y: raw_point.y,
        });
    }

    /// Queue a touch-release event and allow the next press.
    pub fn touch_up(&self) {
        let interaction_state = self.interaction_state.get();
        self.interaction_state.set(InteractionState::Ready);
        self.latest_raw_point.set(None);
        if interaction_state == InteractionState::WaitingForFreshPress {
            return;
        }
        self.push(RawTouchEvent::Up);
    }

    /// Discard pending input until the next touch-down event.
    pub fn wait_for_fresh_press(&self) {
        self.raw_touch_events.borrow_mut().clear();
        self.latest_raw_point.set(None);
        self.interaction_state
            .set(InteractionState::WaitingForFreshPress);
    }

    fn push(&self, raw_touch_event: RawTouchEvent) {
        self.raw_touch_events
            .borrow_mut()
            .push_back(raw_touch_event);
    }
}

impl Default for CydTouchWasmSource {
    fn default() -> Self {
        Self::new()
    }
}

impl ButtonWasmSource {
    /// Construct a released browser button source.
    #[must_use]
    pub fn new() -> Self {
        Self {
            pressed: Rc::new(Cell::new(false)),
        }
    }

    #[must_use]
    /// Return a button handle backed by this source's current state.
    pub fn button(&self) -> ButtonWasm {
        ButtonWasm {
            pressed: self.pressed.clone(),
        }
    }

    /// Set the browser button state to pressed.
    pub fn press(&self) {
        self.pressed.set(true);
    }

    /// Set the browser button state to released.
    pub fn release(&self) {
        self.pressed.set(false);
    }
}

impl Default for ButtonWasmSource {
    fn default() -> Self {
        Self::new()
    }
}

// TODO (may no longer apply) When a dedicated `device-envoy-wasm` crate exists, move `ButtonWasm`
// there so browser button plumbing lives beside the platform button adapter.
impl __ButtonMonitor for ButtonWasm {
    fn is_pressed_raw(&self) -> bool {
        self.pressed.get()
    }

    async fn wait_until_pressed_state(&mut self, pressed: bool) {
        loop {
            if self.is_pressed_raw() == pressed {
                break;
            }
            Timer::after(BUTTON_POLL_INTERVAL).await;
        }
    }
}

impl Button for ButtonWasm {}

impl FlashBlockWasm {
    /// Create browser-backed storage under `storage_key`.
    pub fn new(storage_key: &str) -> Result<Self, Error> {
        Ok(Self {
            flash_device: FlashDeviceWasm::new(storage_key)?,
        })
    }
}

impl FlashDeviceWasm {
    fn new(storage_key: &str) -> Result<Self, Error> {
        let window = web_sys::window().ok_or(Error::StorageUnavailable)?;
        let storage = window
            .local_storage()
            .map_err(|_error| Error::StorageAccess)?
            .ok_or(Error::StorageUnavailable)?;
        let mut flash_device = Self {
            storage,
            storage_key: storage_key.to_owned(),
            bytes: [FLASH_ERASED_BYTE; FLASH_BLOCK_SIZE],
        };
        flash_device.load_from_storage()?;
        Ok(flash_device)
    }

    fn load_from_storage(&mut self) -> Result<(), Error> {
        let Some(encoded_bytes) = self
            .storage
            .get_item(&self.storage_key)
            .map_err(|_error| Error::StorageAccess)?
        else {
            return Ok(());
        };

        if encoded_bytes.len() != FLASH_BLOCK_SIZE * 2 {
            return Ok(());
        }

        let mut decoded_bytes = [FLASH_ERASED_BYTE; FLASH_BLOCK_SIZE];
        if !decode_hex_into(&encoded_bytes, &mut decoded_bytes) {
            return Ok(());
        }
        self.bytes = decoded_bytes;
        Ok(())
    }

    fn persist(&self) -> Result<(), Error> {
        let encoded_bytes = encode_hex(&self.bytes);
        self.storage
            .set_item(&self.storage_key, &encoded_bytes)
            .map_err(|_error| Error::StorageAccess)
    }

    fn checked_range(&self, offset: u32, len: usize) -> Range<usize> {
        let start = usize::try_from(offset).expect("flash offset must fit in usize");
        let end = start
            .checked_add(len)
            .expect("flash range must fit in usize");
        assert!(
            end <= FLASH_BLOCK_SIZE,
            "flash range must stay within the block"
        );
        start..end
    }
}

impl FlashDevice for FlashDeviceWasm {
    type Error = Error;

    fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
        let checked_range = self.checked_range(offset, bytes.len());
        bytes.copy_from_slice(&self.bytes[checked_range]);
        Ok(())
    }

    fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
        let checked_range = self.checked_range(offset, bytes.len());
        self.bytes[checked_range].copy_from_slice(bytes);
        self.persist()
    }

    fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
        let len = usize::try_from(to.saturating_sub(from)).expect("flash erase length fits usize");
        let checked_range = self.checked_range(from, len);
        self.bytes[checked_range].fill(FLASH_ERASED_BYTE);
        self.persist()
    }
}

impl FlashBlock for FlashBlockWasm {
    type Error = FlashBlockError<Error>;

    fn load<T>(&mut self) -> Result<Option<T>, Self::Error>
    where
        T: Serialize + for<'de> Deserialize<'de>,
    {
        load_block::<FLASH_BLOCK_SIZE, T, _>(&mut self.flash_device, FLASH_BLOCK_OFFSET)
    }

    fn save<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + for<'de> Deserialize<'de>,
    {
        save_block::<FLASH_BLOCK_SIZE, _, _>(&mut self.flash_device, FLASH_BLOCK_OFFSET, value)
    }

    fn clear(&mut self) -> Result<(), Self::Error> {
        clear_block::<FLASH_BLOCK_SIZE, _>(&mut self.flash_device, FLASH_BLOCK_OFFSET)
    }
}

fn encode_hex(bytes: &[u8]) -> String {
    const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";

    let mut encoded = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        encoded.push(HEX_DIGITS[(byte >> 4) as usize] as char);
        encoded.push(HEX_DIGITS[(byte & 0x0F) as usize] as char);
    }
    encoded
}

fn decode_hex_into(encoded_bytes: &str, dst: &mut [u8]) -> bool {
    let encoded_bytes = encoded_bytes.as_bytes();
    if encoded_bytes.len() != dst.len() * 2 {
        return false;
    }

    for (dst_index, chunk) in encoded_bytes.chunks_exact(2).enumerate() {
        let Some(high) = decode_hex_nibble(chunk[0]) else {
            return false;
        };
        let Some(low) = decode_hex_nibble(chunk[1]) else {
            return false;
        };
        dst[dst_index] = (high << 4) | low;
    }

    true
}

const fn decode_hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

impl crate::cyd::backend::DisplayBackend for CydDisplayWasm {
    type Error = Infallible;
    type Frame<'a>
        = CydFrameWasm<'a>
    where
        Self: 'a;

    fn create_frame_mut(&mut self, rectangle: Rectangle) -> Self::Frame<'_> {
        let size = rectangle.size;
        let pixel_count = size.width as usize * size.height as usize;
        let pixels = vec![self.background565.into_storage(); pixel_count];
        CydFrameWasm {
            context: &self.context,
            pixels,
            rectangle,
            background565: self.background565,
            foreground565: self.foreground565,
            font: self.font,
        }
    }
}

impl CydDisplay for CydDisplayWasm {
    fn screen_size(&self) -> Size {
        self.size
    }

    fn background_color(&self) -> Rgb888 {
        self.background_color
    }

    fn foreground_color(&self) -> Rgb888 {
        self.foreground_color
    }

    fn background_565(&self) -> Rgb565 {
        self.background565
    }

    fn foreground_565(&self) -> Rgb565 {
        self.foreground565
    }

    fn fill_rectangle(&mut self, rectangle: Rectangle, color: Rgb565) -> Result<(), Infallible> {
        let screen_rectangle = Rectangle::new(Point::zero(), self.size);
        let rectangle = rectangle.intersection(&screen_rectangle);
        if rectangle.size.width == 0 || rectangle.size.height == 0 {
            return Ok(());
        }

        let pixel_count = rectangle.size.width as usize * rectangle.size.height as usize;
        let mut bytes = Vec::with_capacity(pixel_count * 4);
        for _pixel_index in 0..pixel_count {
            push_rgb565_rgba(&mut bytes, color.into_storage());
        }

        put_image_data(&self.context, rectangle, &bytes);
        Ok(())
    }

    fn fill_contiguous<I>(&mut self, rectangle: Rectangle, pixels: I) -> Result<(), Infallible>
    where
        I: IntoIterator<Item = Rgb565>,
    {
        if rectangle.size.width == 0 || rectangle.size.height == 0 {
            return Ok(());
        }

        let mut bytes =
            Vec::with_capacity(rectangle.size.width as usize * rectangle.size.height as usize * 4);
        for pixel in pixels {
            push_rgb565_rgba(&mut bytes, pixel.into_storage());
        }

        put_image_data(&self.context, rectangle, &bytes);
        Ok(())
    }
}

impl CydTouch for CydTouchWasm {
    type Error = Infallible;

    fn try_read(&mut self) -> Result<Option<TouchEvent>, Infallible> {
        Ok(self
            .raw_touch_events
            .borrow_mut()
            .pop_front()
            .map(|raw_touch_event| match raw_touch_event {
                RawTouchEvent::Down { raw_x, raw_y } => {
                    let (x, y) = self.calibration_config.map_raw_to_screen(raw_x, raw_y);
                    TouchEvent::Down {
                        point: self
                            .orientation
                            .map_landscape_point(Point::new(x as i32, y as i32)),
                    }
                }
                RawTouchEvent::Move { raw_x, raw_y } => {
                    let (x, y) = self.calibration_config.map_raw_to_screen(raw_x, raw_y);
                    TouchEvent::Move {
                        point: self
                            .orientation
                            .map_landscape_point(Point::new(x as i32, y as i32)),
                    }
                }
                RawTouchEvent::Up => TouchEvent::Up,
            }))
    }
}

fn put_image_data(context: &CanvasRenderingContext2d, rectangle: Rectangle, bytes: &[u8]) {
    let image_data = ImageData::new_with_u8_clamped_array_and_sh(
        Clamped(bytes),
        rectangle.size.width,
        rectangle.size.height,
    )
    .expect("ImageData dimensions match the rectangle");
    context
        .put_image_data(
            &image_data,
            f64::from(rectangle.top_left.x),
            f64::from(rectangle.top_left.y),
        )
        .expect("put_image_data with in-bounds coordinates cannot fail");
}

fn push_rgb565_rgba(bytes: &mut Vec<u8>, pixel: u16) {
    let color = rgb888_from_rgb565(pixel);
    bytes.push(color.r());
    bytes.push(color.g());
    bytes.push(color.b());
    bytes.push(255);
}

/// A single in-progress frame backed by an `Rgb565` pixel buffer.
///
/// Drawing uses logical display coordinates. [`CydFrame::flush`] presents the
/// buffered region to the canvas and awaits the next browser animation frame.
pub struct CydFrameWasm<'a> {
    context: &'a CanvasRenderingContext2d,
    pixels: Vec<u16>,
    // Where this frame presents and how large it is: set from the `Rectangle`
    // passed to `frame_mut`, so `flush` needs no separate position argument.
    rectangle: Rectangle,
    background565: Rgb565,
    foreground565: Rgb565,
    font: &'static MonoFont<'static>,
}

impl CydFrameWasm<'_> {
    fn width(&self) -> usize {
        self.rectangle.size.width as usize
    }

    fn height(&self) -> usize {
        self.rectangle.size.height as usize
    }

    fn local_x(&self, x: i32) -> Option<usize> {
        usize::try_from(x.checked_sub(self.rectangle.top_left.x)?).ok()
    }

    fn local_y(&self, y: i32) -> Option<usize> {
        usize::try_from(y.checked_sub(self.rectangle.top_left.y)?).ok()
    }

    /// Convert the `Rgb565` buffer to RGBA8 and `putImageData` it at the frame's top-left.
    fn present(&self) {
        let mut bytes = Vec::with_capacity(self.pixels.len() * 4);
        for pixel in &self.pixels {
            let color = rgb888_from_rgb565(*pixel);
            bytes.push(color.r());
            bytes.push(color.g());
            bytes.push(color.b());
            bytes.push(255);
        }
        let image_data = ImageData::new_with_u8_clamped_array_and_sh(
            Clamped(&bytes),
            self.rectangle.size.width,
            self.rectangle.size.height,
        )
        .expect("ImageData dimensions match the pixel buffer");
        self.context
            .put_image_data(
                &image_data,
                f64::from(self.rectangle.top_left.x),
                f64::from(self.rectangle.top_left.y),
            )
            .expect("put_image_data with in-bounds coordinates cannot fail");
    }
}

impl DrawTarget for CydFrameWasm<'_> {
    type Color = Rgb565;
    type Error = Infallible;

    fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
        CydFrame::fill(self, color);
        Ok(())
    }

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        for Pixel(point, color) in pixels {
            let Some(local_x) = self.local_x(point.x) else {
                continue;
            };
            let Some(local_y) = self.local_y(point.y) else {
                continue;
            };
            if local_x < CydFrameWasm::width(self) && local_y < CydFrameWasm::height(self) {
                let index = local_y * CydFrameWasm::width(self) + local_x;
                self.pixels[index] = color.into_storage();
            }
        }
        Ok(())
    }
}

impl Dimensions for CydFrameWasm<'_> {
    fn bounding_box(&self) -> Rectangle {
        self.rectangle
    }
}

impl PixelTarget for CydFrameWasm<'_> {
    fn width(&self) -> usize {
        usize::try_from(self.rectangle.top_left.x)
            .expect("frame top-left x must be non-negative")
            .checked_add(CydFrameWasm::width(self))
            .expect("frame width must fit in usize")
    }

    fn height(&self) -> usize {
        usize::try_from(self.rectangle.top_left.y)
            .expect("frame top-left y must be non-negative")
            .checked_add(CydFrameWasm::height(self))
            .expect("frame height must fit in usize")
    }

    fn put_pixel(&mut self, x: usize, y: usize, color: Rgb888) {
        let Some(local_x) = self.local_x(x as i32) else {
            return;
        };
        let Some(local_y) = self.local_y(y as i32) else {
            return;
        };
        if local_x >= CydFrameWasm::width(self) || local_y >= CydFrameWasm::height(self) {
            return;
        }
        let stride = CydFrameWasm::width(self);
        self.pixels[local_y * stride + local_x] = Rgb565::from(color).into_storage();
    }

    /// The frame buffer already stores RGB565, so a decoded image pixel can be
    /// written verbatim with no RGB888 round-trip.
    fn put_pixel_565(&mut self, x: usize, y: usize, rgb565: u16) {
        let Some(local_x) = self.local_x(x as i32) else {
            return;
        };
        let Some(local_y) = self.local_y(y as i32) else {
            return;
        };
        if local_x >= CydFrameWasm::width(self) || local_y >= CydFrameWasm::height(self) {
            return;
        }
        let stride = CydFrameWasm::width(self);
        self.pixels[local_y * stride + local_x] = rgb565;
    }
}

impl CydFrame for CydFrameWasm<'_> {
    /// WASM frame presentation is infallible.
    type Error = Infallible;

    fn rectangle(&self) -> Rectangle {
        self.rectangle
    }

    fn fill(&mut self, color: Rgb565) -> &mut Self {
        self.pixels.fill(color.into_storage());
        self
    }

    fn clear(&mut self) -> &mut Self {
        self.fill(self.background565)
    }

    fn copy_from_565(&mut self, src: &[u16]) -> crate::Result<()> {
        if self.pixels.len() != src.len() {
            return Err(crate::Error::CopySize {
                src_len: src.len(),
                frame_len: self.pixels.len(),
            });
        }
        self.pixels.copy_from_slice(src);
        Ok(())
    }

    fn write_text(&mut self, text: &str) -> &mut Self {
        let style = MonoTextStyle::new(self.font, self.foreground565);
        Text::with_baseline(text, self.rectangle.top_left, style, Baseline::Top)
            .draw(self)
            .expect("drawing onto an Infallible frame cannot fail");
        self
    }

    async fn flush(&mut self) -> Result<(), Infallible> {
        // Present immediately so the first drawn frame is visible without
        // waiting a browser tick, then yield to the next animation frame to
        // pace the loop.
        self.present();
        next_animation_frame().await;
        Ok(())
    }
}