1#![no_std]
2#![warn(missing_docs)]
3#![doc = include_str!("../README.md")]
4
5extern crate alloc;
6
7use alloc::{boxed::Box, format, rc::Rc, vec, vec::Vec};
8use core::{cell::RefCell, fmt, time::Duration};
9
10use embedded_graphics_core::{
11 draw_target::DrawTarget,
12 geometry::{OriginDimensions, Point, Size},
13 pixelcolor::{Rgb565, raw::RawU16},
14 primitives::Rectangle,
15};
16use embedded_hal::{delay::DelayNs, digital::OutputPin};
17use i_slint_core::{input::TouchPhase, lengths::LogicalPoint, window::WindowInner};
18use mipidsi::{
19 interface::{Interface, InterfacePixelFormat},
20 models::Model,
21};
22use slint::{
23 LogicalPosition, PhysicalSize,
24 platform::{
25 self, Platform, PlatformError, PointerEventButton, WindowAdapter, WindowEvent,
26 software_renderer::{
27 LineBufferProvider, MinimalSoftwareWindow, RepaintBufferType, Rgb565Pixel,
28 },
29 },
30};
31
32const DEFAULT_POLL_INTERVAL: Duration = Duration::from_micros(16_667);
33const DEFAULT_IDLE_POLL_INTERVAL: Duration = Duration::from_secs(1);
34const PARTIAL_REPAINT_BUFFER_TYPE: RepaintBufferType = RepaintBufferType::ReusedBuffer;
35
36pub const MAX_TOUCH_CONTACTS: usize = 5;
41
42#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
49pub struct TouchPoint {
50 pub x: u16,
52 pub y: u16,
54}
55
56#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
62pub struct TouchContact {
63 pub id: u8,
65 pub position: TouchPoint,
67}
68
69impl TouchContact {
70 #[must_use]
72 pub const fn new(id: u8, position: TouchPoint) -> Self {
73 Self { id, position }
74 }
75}
76
77#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
79pub enum TouchMode {
80 #[default]
82 Single,
83 Multi,
85}
86
87#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
89pub enum OutOfBoundsTouch {
90 #[default]
92 Clamp,
93 Ignore,
98}
99
100impl TouchPoint {
101 #[must_use]
103 pub const fn new(x: u16, y: u16) -> Self {
104 Self { x, y }
105 }
106}
107
108pub trait TouchInput {
124 type Error;
126
127 fn read_touch(&mut self) -> Result<Option<TouchPoint>, Self::Error>;
129
130 fn read_touches(&mut self, contacts: &mut [TouchContact]) -> Result<usize, Self::Error> {
136 let Some(first) = contacts.first_mut() else {
137 return Ok(0);
138 };
139
140 match self.read_touch()? {
141 Some(position) => {
142 *first = TouchContact::new(0, position);
143 Ok(1)
144 }
145 None => Ok(0),
146 }
147 }
148}
149
150#[derive(Clone, Copy, Debug, Default)]
152pub struct NoTouch;
153
154impl TouchInput for NoTouch {
155 type Error = core::convert::Infallible;
156
157 fn read_touch(&mut self) -> Result<Option<TouchPoint>, Self::Error> {
158 Ok(None)
159 }
160}
161
162pub trait McuRuntime {
170 fn now(&self) -> Duration;
172
173 fn wait(&mut self, duration: Duration);
175}
176
177#[derive(Debug)]
179pub enum AdapterError<DisplayError, ResetError> {
180 Display(mipidsi::InitError<DisplayError, ResetError>),
182 Platform(platform::SetPlatformError),
184 App(PlatformError),
186}
187
188impl<DisplayError: fmt::Debug, ResetError: fmt::Debug> fmt::Display
189 for AdapterError<DisplayError, ResetError>
190{
191 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
192 match self {
193 Self::Display(error) => write!(formatter, "display initialization failed: {error:?}"),
194 Self::Platform(error) => write!(formatter, "could not install Slint platform: {error}"),
195 Self::App(error) => write!(formatter, "could not create Slint app: {error}"),
196 }
197 }
198}
199
200impl<DisplayError: fmt::Debug, ResetError: fmt::Debug> core::error::Error
201 for AdapterError<DisplayError, ResetError>
202{
203}
204
205pub type BuildWithEventLoopResult<App, DI, MODEL, RST, TOUCH, RUNTIME> = Result<
207 (
208 App,
209 McuEventLoop<mipidsi::Display<DI, MODEL, RST>, TOUCH, RUNTIME>,
210 ),
211 AdapterError<<DI as Interface>::Error, <RST as embedded_hal::digital::ErrorType>::Error>,
212>;
213
214pub struct AdapterBuilder<DI, MODEL, RST, TOUCH, RUNTIME>
221where
222 DI: Interface,
223 MODEL: Model,
224 MODEL::ColorFormat: InterfacePixelFormat<DI::Word>,
225{
226 display: mipidsi::Builder<DI, MODEL, RST>,
227 touch: TOUCH,
228 runtime: RUNTIME,
229 frame_interval: Duration,
230 touch_poll_interval: Option<Duration>,
231 out_of_bounds_touch: OutOfBoundsTouch,
232 touch_mode: TouchMode,
233}
234
235impl<DI, MODEL, RST, TOUCH, RUNTIME> AdapterBuilder<DI, MODEL, RST, TOUCH, RUNTIME>
236where
237 DI: Interface,
238 MODEL: Model,
239 MODEL::ColorFormat: InterfacePixelFormat<DI::Word>,
240{
241 #[must_use]
246 pub const fn new(
247 display: mipidsi::Builder<DI, MODEL, RST>,
248 touch: TOUCH,
249 runtime: RUNTIME,
250 ) -> Self {
251 Self {
252 display,
253 touch,
254 runtime,
255 frame_interval: DEFAULT_POLL_INTERVAL,
256 touch_poll_interval: Some(DEFAULT_POLL_INTERVAL),
257 out_of_bounds_touch: OutOfBoundsTouch::Clamp,
258 touch_mode: TouchMode::Single,
259 }
260 }
261
262 #[must_use]
267 pub const fn poll_interval(mut self, interval: Duration) -> Self {
268 self.frame_interval = interval;
269 self.touch_poll_interval = Some(interval);
270 self
271 }
272
273 #[must_use]
279 pub const fn frame_interval(mut self, interval: Duration) -> Self {
280 self.frame_interval = interval;
281 self
282 }
283
284 #[must_use]
289 pub const fn touch_poll_interval(mut self, interval: Duration) -> Self {
290 self.touch_poll_interval = Some(interval);
291 self
292 }
293
294 #[must_use]
296 pub const fn out_of_bounds_touch(mut self, policy: OutOfBoundsTouch) -> Self {
297 self.out_of_bounds_touch = policy;
298 self
299 }
300
301 #[must_use]
307 pub const fn touch_mode(mut self, mode: TouchMode) -> Self {
308 self.touch_mode = mode;
309 self
310 }
311}
312
313impl<DI, MODEL, RST, TOUCH, RUNTIME> AdapterBuilder<DI, MODEL, RST, TOUCH, RUNTIME>
314where
315 DI: Interface + 'static,
316 DI::Error: fmt::Debug + 'static,
317 MODEL: Model + 'static,
318 MODEL::ColorFormat: InterfacePixelFormat<DI::Word> + From<Rgb565> + Copy + 'static,
319 RST: OutputPin + 'static,
320 TOUCH: TouchInput + 'static,
321 TOUCH::Error: fmt::Debug + 'static,
322 RUNTIME: McuRuntime + 'static,
323{
324 pub fn build<App>(
336 self,
337 delay: &mut impl DelayNs,
338 app_factory: impl FnOnce() -> Result<App, PlatformError>,
339 ) -> Result<App, AdapterError<DI::Error, RST::Error>> {
340 self.build_with_event_loop(delay, app_factory)
341 .map(|(app, _event_loop)| app)
342 }
343
344 pub fn build_with_event_loop<App>(
357 self,
358 delay: &mut impl DelayNs,
359 app_factory: impl FnOnce() -> Result<App, PlatformError>,
360 ) -> BuildWithEventLoopResult<App, DI, MODEL, RST, TOUCH, RUNTIME> {
361 let display = self.display.init(delay).map_err(AdapterError::Display)?;
362 let display_size = display.size();
363 let window = MinimalSoftwareWindow::new(PARTIAL_REPAINT_BUFFER_TYPE);
364 let line_buffer = vec![Rgb565Pixel::default(); display_size.width as usize];
365 let started_at = self.runtime.now();
366 let timing =
367 EventLoopTiming::new(started_at, self.frame_interval, self.touch_poll_interval);
368
369 let backend = Rc::new(McuBackend {
370 window: window.clone(),
371 display: RefCell::new(DisplayState {
372 display,
373 line_buffer,
374 full_repaint_pending: false,
375 }),
376 touch: RefCell::new(TouchTracker::new(
377 self.touch,
378 display_size.width,
379 display_size.height,
380 self.out_of_bounds_touch,
381 self.touch_mode,
382 )),
383 runtime: RefCell::new(self.runtime),
384 started_at,
385 timing: RefCell::new(timing),
386 });
387
388 platform::set_platform(Box::new(McuPlatform {
389 backend: backend.clone(),
390 }))
391 .map_err(AdapterError::Platform)?;
392 let app = app_factory().map_err(AdapterError::App)?;
393 window.set_size(PhysicalSize::new(display_size.width, display_size.height));
394
395 Ok((app, McuEventLoop { backend }))
396 }
397}
398
399pub struct AdapterBuilderWithoutTouch<DI, MODEL, RST, RUNTIME>
405where
406 DI: Interface,
407 MODEL: Model,
408 MODEL::ColorFormat: InterfacePixelFormat<DI::Word>,
409{
410 inner: AdapterBuilder<DI, MODEL, RST, NoTouch, RUNTIME>,
411}
412
413impl<DI, MODEL, RST, RUNTIME> AdapterBuilderWithoutTouch<DI, MODEL, RST, RUNTIME>
414where
415 DI: Interface,
416 MODEL: Model,
417 MODEL::ColorFormat: InterfacePixelFormat<DI::Word>,
418{
419 #[must_use]
424 pub const fn new(display: mipidsi::Builder<DI, MODEL, RST>, runtime: RUNTIME) -> Self {
425 let mut inner = AdapterBuilder::new(display, NoTouch, runtime);
426 inner.touch_poll_interval = None;
427 Self { inner }
428 }
429
430 #[must_use]
435 pub fn poll_interval(mut self, interval: Duration) -> Self {
436 self.inner.frame_interval = interval;
437 self
438 }
439
440 #[must_use]
445 pub fn frame_interval(mut self, interval: Duration) -> Self {
446 self.inner.frame_interval = interval;
447 self
448 }
449}
450
451impl<DI, MODEL, RST, RUNTIME> AdapterBuilderWithoutTouch<DI, MODEL, RST, RUNTIME>
452where
453 DI: Interface + 'static,
454 DI::Error: fmt::Debug + 'static,
455 MODEL: Model + 'static,
456 MODEL::ColorFormat: InterfacePixelFormat<DI::Word> + From<Rgb565> + Copy + 'static,
457 RST: OutputPin + 'static,
458 RUNTIME: McuRuntime + 'static,
459{
460 pub fn build<App>(
465 self,
466 delay: &mut impl DelayNs,
467 app_factory: impl FnOnce() -> Result<App, PlatformError>,
468 ) -> Result<App, AdapterError<DI::Error, RST::Error>> {
469 self.inner.build(delay, app_factory)
470 }
471
472 pub fn build_with_event_loop<App>(
478 self,
479 delay: &mut impl DelayNs,
480 app_factory: impl FnOnce() -> Result<App, PlatformError>,
481 ) -> BuildWithEventLoopResult<App, DI, MODEL, RST, NoTouch, RUNTIME> {
482 self.inner.build_with_event_loop(delay, app_factory)
483 }
484}
485
486struct DisplayState<DISPLAY> {
487 display: DISPLAY,
488 line_buffer: Vec<Rgb565Pixel>,
489 full_repaint_pending: bool,
490}
491
492#[derive(Clone, Copy, Debug, Eq, PartialEq)]
493struct DueWork {
494 frame: bool,
495 touch: bool,
496}
497
498struct EventLoopTiming {
499 frame_interval: Duration,
500 touch_poll_interval: Option<Duration>,
501 next_frame_at: Duration,
502 next_touch_poll_at: Option<Duration>,
503 frame_pending: bool,
504}
505
506impl EventLoopTiming {
507 fn new(
508 started_at: Duration,
509 frame_interval: Duration,
510 touch_poll_interval: Option<Duration>,
511 ) -> Self {
512 Self {
513 frame_interval,
514 touch_poll_interval,
515 next_frame_at: started_at,
516 next_touch_poll_at: touch_poll_interval.map(|_| started_at),
517 frame_pending: true,
518 }
519 }
520
521 fn due_work(&self, now: Duration) -> DueWork {
522 DueWork {
523 frame: now >= self.next_frame_at,
524 touch: self
525 .next_touch_poll_at
526 .is_some_and(|deadline| now >= deadline),
527 }
528 }
529
530 fn frame_processed(&mut self, iteration_started_at: Duration) {
531 self.next_frame_at = iteration_started_at.saturating_add(self.frame_interval);
532 self.frame_pending = false;
533 }
534
535 fn touch_polled(&mut self, iteration_started_at: Duration) {
536 self.next_touch_poll_at = self
537 .touch_poll_interval
538 .map(|interval| iteration_started_at.saturating_add(interval));
539 }
540
541 fn mark_frame_pending(&mut self) {
542 self.frame_pending = true;
543 }
544
545 fn next_wait(
546 &self,
547 now: Duration,
548 timer_wait: Option<Duration>,
549 has_active_animations: bool,
550 ) -> Duration {
551 let mut wait = timer_wait;
552
553 if let Some(touch_deadline) = self.next_touch_poll_at {
554 wait = earlier(wait, touch_deadline.saturating_sub(now));
555 }
556
557 if has_active_animations || self.frame_pending {
558 wait = earlier(wait, self.next_frame_at.saturating_sub(now));
559 }
560
561 wait.unwrap_or_else(|| self.frame_interval.max(DEFAULT_IDLE_POLL_INTERVAL))
566 }
567}
568
569fn earlier(current: Option<Duration>, candidate: Duration) -> Option<Duration> {
570 Some(current.map_or(candidate, |current| current.min(candidate)))
571}
572
573struct McuBackend<DISPLAY, TOUCH, RUNTIME> {
574 window: Rc<MinimalSoftwareWindow>,
575 display: RefCell<DisplayState<DISPLAY>>,
576 touch: RefCell<TouchTracker<TOUCH>>,
577 runtime: RefCell<RUNTIME>,
578 started_at: Duration,
579 timing: RefCell<EventLoopTiming>,
580}
581
582pub struct McuEventLoop<DISPLAY, TOUCH, RUNTIME> {
588 backend: Rc<McuBackend<DISPLAY, TOUCH, RUNTIME>>,
589}
590
591impl<DISPLAY, TOUCH, RUNTIME> McuEventLoop<DISPLAY, TOUCH, RUNTIME>
592where
593 DISPLAY: DrawTarget + OriginDimensions,
594 DISPLAY::Color: From<Rgb565>,
595 DISPLAY::Error: fmt::Debug,
596 TOUCH: TouchInput,
597 TOUCH::Error: fmt::Debug,
598 RUNTIME: McuRuntime,
599{
600 pub fn step(&self) -> Result<Duration, PlatformError> {
606 self.backend.run_iteration()
607 }
608
609 #[must_use]
611 pub fn is_running(&self) -> bool {
612 self.backend.window.is_visible()
613 }
614}
615
616struct McuPlatform<DISPLAY, TOUCH, RUNTIME> {
617 backend: Rc<McuBackend<DISPLAY, TOUCH, RUNTIME>>,
618}
619
620impl<DISPLAY, TOUCH, RUNTIME> McuBackend<DISPLAY, TOUCH, RUNTIME>
621where
622 DISPLAY: DrawTarget + OriginDimensions,
623 DISPLAY::Color: From<Rgb565>,
624 DISPLAY::Error: fmt::Debug,
625 TOUCH: TouchInput,
626 TOUCH::Error: fmt::Debug,
627 RUNTIME: McuRuntime,
628{
629 fn run_iteration(&self) -> Result<Duration, PlatformError> {
630 let iteration_started_at = self.runtime.borrow().now();
631 let timer_due =
632 platform::duration_until_next_timer_update().is_some_and(|wait| wait.is_zero());
633 let due = self.timing.borrow().due_work(iteration_started_at);
634 let recovery_pending = self.display.borrow().full_repaint_pending;
635
636 if !due.frame {
640 self.timing.borrow_mut().mark_frame_pending();
641 }
642
643 if due.frame || timer_due || recovery_pending {
644 platform::update_timers_and_animations();
645 }
646
647 if due.touch {
648 self.timing.borrow_mut().touch_polled(iteration_started_at);
649 if self.dispatch_touch()? {
650 self.timing.borrow_mut().mark_frame_pending();
651 }
652 }
653
654 if due.frame || timer_due || recovery_pending {
655 self.render()?;
656 self.timing
657 .borrow_mut()
658 .frame_processed(iteration_started_at);
659 if self.display.borrow().full_repaint_pending {
660 self.window.request_redraw();
661 self.timing.borrow_mut().mark_frame_pending();
662 }
663 }
664
665 let now = self.runtime.borrow().now();
666 Ok(self.next_wait(now))
667 }
668
669 fn dispatch_touch(&self) -> Result<bool, PlatformError> {
670 let updates = self
671 .touch
672 .borrow_mut()
673 .poll()
674 .map_err(|error| PlatformError::from(format!("touch input failed: {error:?}")))?;
675
676 match updates {
677 TouchUpdates::Single(update) => {
678 let button = PointerEventButton::Left;
679 let event = match update {
680 TouchUpdate::None => return Ok(false),
681 TouchUpdate::Pressed(position) => {
682 WindowEvent::PointerPressed { position, button }
683 }
684 TouchUpdate::Moved(position) => WindowEvent::PointerMoved { position },
685 TouchUpdate::Released(position) => {
686 WindowEvent::PointerReleased { position, button }
687 }
688 };
689 let released = matches!(event, WindowEvent::PointerReleased { .. });
690 self.window.try_dispatch_event(event)?;
691 if released {
692 self.window.try_dispatch_event(WindowEvent::PointerExited)?;
693 }
694 Ok(true)
695 }
696 TouchUpdates::Multi(updates) => {
697 if updates.is_empty() {
698 return Ok(false);
699 }
700
701 let window = WindowInner::from_pub(self.window.window());
706 for update in updates.iter() {
707 let phase = match update.phase {
708 MultiTouchPhase::Started => TouchPhase::Started,
709 MultiTouchPhase::Moved => TouchPhase::Moved,
710 MultiTouchPhase::Ended => TouchPhase::Ended,
711 };
712 window.process_touch_input(
713 i32::from(update.id),
714 LogicalPoint::new(update.position.x, update.position.y),
715 phase,
716 );
717 }
718 Ok(true)
719 }
720 }
721 }
722
723 fn render(&self) -> Result<bool, PlatformError> {
724 let mut display_error = None;
725 let rendered = self.window.draw_if_needed(|renderer| {
726 let mut state = self.display.borrow_mut();
727 let DisplayState {
728 display,
729 line_buffer,
730 full_repaint_pending,
731 } = &mut *state;
732 let recovering = *full_repaint_pending;
733
734 if recovering {
735 renderer.set_repaint_buffer_type(RepaintBufferType::NewBuffer);
736 }
737
738 renderer.render_by_line(MipidsiLineBuffer {
739 display,
740 line_buffer,
741 error: &mut display_error,
742 });
743
744 if display_error.is_some() {
745 *full_repaint_pending = true;
746 renderer.set_repaint_buffer_type(RepaintBufferType::NewBuffer);
747 } else if recovering {
748 renderer.set_repaint_buffer_type(PARTIAL_REPAINT_BUFFER_TYPE);
752 renderer.render_by_line(CachePrimingLineBuffer { line_buffer });
753 *full_repaint_pending = false;
754 }
755 });
756
757 if let Some(error) = display_error {
758 self.window.request_redraw();
761 self.timing.borrow_mut().mark_frame_pending();
762 Err(PlatformError::from(format!(
763 "display rendering failed: {error:?}"
764 )))
765 } else {
766 Ok(rendered)
767 }
768 }
769
770 fn next_wait(&self, now: Duration) -> Duration {
771 self.timing.borrow().next_wait(
772 now,
773 platform::duration_until_next_timer_update(),
774 self.window.has_active_animations(),
775 )
776 }
777}
778
779impl<DISPLAY, TOUCH, RUNTIME> Platform for McuPlatform<DISPLAY, TOUCH, RUNTIME>
780where
781 DISPLAY: DrawTarget + OriginDimensions + 'static,
782 DISPLAY::Color: From<Rgb565> + 'static,
783 DISPLAY::Error: fmt::Debug + 'static,
784 TOUCH: TouchInput + 'static,
785 TOUCH::Error: fmt::Debug + 'static,
786 RUNTIME: McuRuntime + 'static,
787{
788 fn create_window_adapter(&self) -> Result<Rc<dyn WindowAdapter>, PlatformError> {
789 Ok(self.backend.window.clone())
790 }
791
792 fn duration_since_start(&self) -> Duration {
793 self.backend
794 .runtime
795 .borrow()
796 .now()
797 .saturating_sub(self.backend.started_at)
798 }
799
800 fn run_event_loop(&self) -> Result<(), PlatformError> {
801 while self.backend.window.is_visible() {
802 let wait = self.backend.run_iteration()?;
803 if !wait.is_zero() {
804 self.backend.runtime.borrow_mut().wait(wait);
805 }
806 }
807 Ok(())
808 }
809}
810
811struct CachePrimingLineBuffer<'a> {
812 line_buffer: &'a mut [Rgb565Pixel],
813}
814
815impl LineBufferProvider for CachePrimingLineBuffer<'_> {
816 type TargetPixel = Rgb565Pixel;
817
818 fn process_line(
819 &mut self,
820 _line: usize,
821 range: core::ops::Range<usize>,
822 render_fn: impl FnOnce(&mut [Self::TargetPixel]),
823 ) {
824 render_fn(&mut self.line_buffer[range]);
825 }
826}
827
828struct MipidsiLineBuffer<'a, DISPLAY>
829where
830 DISPLAY: DrawTarget,
831{
832 display: &'a mut DISPLAY,
833 line_buffer: &'a mut [Rgb565Pixel],
834 error: &'a mut Option<DISPLAY::Error>,
835}
836
837impl<DISPLAY> LineBufferProvider for MipidsiLineBuffer<'_, DISPLAY>
838where
839 DISPLAY: DrawTarget,
840 DISPLAY::Color: From<Rgb565>,
841{
842 type TargetPixel = Rgb565Pixel;
843
844 fn process_line(
845 &mut self,
846 line: usize,
847 range: core::ops::Range<usize>,
848 render_fn: impl FnOnce(&mut [Self::TargetPixel]),
849 ) {
850 render_fn(&mut self.line_buffer[range.clone()]);
851
852 if self.error.is_some() {
853 return;
854 }
855
856 let area = Rectangle::new(
857 Point::new(range.start as i32, line as i32),
858 Size::new(range.len() as u32, 1),
859 );
860 let colors = self.line_buffer[range].iter().map(|pixel| {
861 let rgb565: Rgb565 = RawU16::new(pixel.0).into();
862 rgb565.into()
863 });
864 if let Err(error) = self.display.fill_contiguous(&area, colors) {
865 *self.error = Some(error);
866 }
867 }
868}
869
870struct TouchTracker<T> {
871 touch: T,
872 width: u32,
873 height: u32,
874 max_x: u16,
875 max_y: u16,
876 out_of_bounds: OutOfBoundsTouch,
877 tracking: TouchTracking,
878}
879
880impl<T> TouchTracker<T> {
881 fn new(
882 touch: T,
883 width: u32,
884 height: u32,
885 out_of_bounds: OutOfBoundsTouch,
886 mode: TouchMode,
887 ) -> Self {
888 Self {
889 touch,
890 width,
891 height,
892 max_x: width.saturating_sub(1).min(u16::MAX.into()) as u16,
893 max_y: height.saturating_sub(1).min(u16::MAX.into()) as u16,
894 out_of_bounds,
895 tracking: match mode {
896 TouchMode::Single => TouchTracking::Single { last: None },
897 TouchMode::Multi => TouchTracking::Multi {
898 active: [None; MAX_TOUCH_CONTACTS],
899 samples: [TouchContact::default(); MAX_TOUCH_CONTACTS],
900 },
901 },
902 }
903 }
904}
905
906impl<T: TouchInput> TouchTracker<T> {
907 fn poll(&mut self) -> Result<TouchUpdates, T::Error> {
908 let Self {
909 touch,
910 width,
911 height,
912 max_x,
913 max_y,
914 out_of_bounds,
915 tracking,
916 } = self;
917
918 match tracking {
919 TouchTracking::Single { last } => {
920 let current = touch.read_touch()?.and_then(|point| {
921 logical_position(point, *width, *height, *max_x, *max_y, *out_of_bounds)
922 });
923 Ok(TouchUpdates::Single(match (*last, current) {
924 (None, None) => TouchUpdate::None,
925 (None, Some(position)) => {
926 *last = Some(position);
927 TouchUpdate::Pressed(position)
928 }
929 (Some(previous), None) => {
930 *last = None;
931 TouchUpdate::Released(previous)
932 }
933 (Some(previous), Some(position)) if previous == position => TouchUpdate::None,
934 (Some(_), Some(position)) => {
935 *last = Some(position);
936 TouchUpdate::Moved(position)
937 }
938 }))
939 }
940 TouchTracking::Multi { active, samples } => {
941 let sample_count = touch.read_touches(samples)?.min(samples.len());
942 let mut current = [None; MAX_TOUCH_CONTACTS];
943
944 for sample in samples[..sample_count].iter().copied() {
945 let Some(position) = logical_position(
946 sample.position,
947 *width,
948 *height,
949 *max_x,
950 *max_y,
951 *out_of_bounds,
952 ) else {
953 continue;
954 };
955
956 if current
957 .iter()
958 .flatten()
959 .any(|contact: &TrackedContact| contact.id == sample.id)
960 {
961 continue;
962 }
963
964 if let Some(slot) = current.iter_mut().find(|slot| slot.is_none()) {
965 *slot = Some(TrackedContact {
966 id: sample.id,
967 position,
968 });
969 }
970 }
971
972 let mut updates = MultiTouchUpdates::new();
973 for previous in active.iter().flatten().copied() {
974 if find_contact(¤t, previous.id).is_none() {
975 updates.push(MultiTouchUpdate {
976 id: previous.id,
977 position: previous.position,
978 phase: MultiTouchPhase::Ended,
979 });
980 }
981 }
982
983 for contact in current.iter().flatten().copied() {
984 match find_contact(active, contact.id) {
985 None => updates.push(MultiTouchUpdate {
986 id: contact.id,
987 position: contact.position,
988 phase: MultiTouchPhase::Started,
989 }),
990 Some(previous) if previous.position != contact.position => {
991 updates.push(MultiTouchUpdate {
992 id: contact.id,
993 position: contact.position,
994 phase: MultiTouchPhase::Moved,
995 });
996 }
997 Some(_) => {}
998 }
999 }
1000
1001 *active = current;
1002 Ok(TouchUpdates::Multi(updates))
1003 }
1004 }
1005 }
1006}
1007
1008fn logical_position(
1009 point: TouchPoint,
1010 width: u32,
1011 height: u32,
1012 max_x: u16,
1013 max_y: u16,
1014 out_of_bounds: OutOfBoundsTouch,
1015) -> Option<LogicalPosition> {
1016 match out_of_bounds {
1017 OutOfBoundsTouch::Clamp => Some(LogicalPosition::new(
1018 point.x.min(max_x) as f32,
1019 point.y.min(max_y) as f32,
1020 )),
1021 OutOfBoundsTouch::Ignore if u32::from(point.x) >= width || u32::from(point.y) >= height => {
1022 None
1023 }
1024 OutOfBoundsTouch::Ignore => Some(LogicalPosition::new(point.x as f32, point.y as f32)),
1025 }
1026}
1027
1028fn find_contact(
1029 contacts: &[Option<TrackedContact>; MAX_TOUCH_CONTACTS],
1030 id: u8,
1031) -> Option<TrackedContact> {
1032 contacts
1033 .iter()
1034 .flatten()
1035 .find(|contact| contact.id == id)
1036 .copied()
1037}
1038
1039enum TouchTracking {
1040 Single {
1041 last: Option<LogicalPosition>,
1042 },
1043 Multi {
1044 active: [Option<TrackedContact>; MAX_TOUCH_CONTACTS],
1045 samples: [TouchContact; MAX_TOUCH_CONTACTS],
1046 },
1047}
1048
1049#[derive(Clone, Copy, Debug, PartialEq)]
1050struct TrackedContact {
1051 id: u8,
1052 position: LogicalPosition,
1053}
1054
1055#[derive(Debug, PartialEq)]
1056enum TouchUpdates {
1057 Single(TouchUpdate),
1058 Multi(MultiTouchUpdates),
1059}
1060
1061#[derive(Clone, Copy, Debug, PartialEq)]
1062enum TouchUpdate {
1063 None,
1064 Pressed(LogicalPosition),
1065 Moved(LogicalPosition),
1066 Released(LogicalPosition),
1067}
1068
1069const MAX_MULTI_TOUCH_UPDATES: usize = MAX_TOUCH_CONTACTS * 2;
1070
1071#[derive(Clone, Copy, Debug, PartialEq)]
1072struct MultiTouchUpdate {
1073 id: u8,
1074 position: LogicalPosition,
1075 phase: MultiTouchPhase,
1076}
1077
1078#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1079enum MultiTouchPhase {
1080 Started,
1081 Moved,
1082 Ended,
1083}
1084
1085#[derive(Debug, PartialEq)]
1086struct MultiTouchUpdates {
1087 updates: [Option<MultiTouchUpdate>; MAX_MULTI_TOUCH_UPDATES],
1088 len: usize,
1089}
1090
1091impl MultiTouchUpdates {
1092 fn new() -> Self {
1093 Self {
1094 updates: [None; MAX_MULTI_TOUCH_UPDATES],
1095 len: 0,
1096 }
1097 }
1098
1099 fn push(&mut self, update: MultiTouchUpdate) {
1100 if self.len < self.updates.len() {
1101 self.updates[self.len] = Some(update);
1102 self.len += 1;
1103 }
1104 }
1105
1106 fn is_empty(&self) -> bool {
1107 self.len == 0
1108 }
1109
1110 fn iter(&self) -> impl Iterator<Item = MultiTouchUpdate> + '_ {
1111 self.updates[..self.len].iter().flatten().copied()
1112 }
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117 extern crate std;
1118
1119 use std::{cell::Cell, collections::VecDeque};
1120
1121 use embedded_graphics_core::{Pixel, pixelcolor::RgbColor};
1122 use slint::ComponentHandle;
1123
1124 use super::*;
1125
1126 slint::slint! {
1127 export component RecoveryTestWindow inherits Window {
1128 width: 100px;
1129 height: 100px;
1130 in property <bool> alternate;
1131 in-out property <int> clicks;
1132 in-out property <int> gestures-started;
1133 background: black;
1134
1135 Rectangle {
1136 x: 1px;
1137 y: 1px;
1138 width: 1px;
1139 height: 1px;
1140 background: alternate ? red : blue;
1141 }
1142
1143 TouchArea {
1144 x: 0px;
1145 y: 0px;
1146 width: 20px;
1147 height: 20px;
1148 z: 1;
1149
1150 clicked => {
1151 root.clicks += 1;
1152 }
1153 }
1154
1155 ScaleRotateGestureHandler {
1156 y: 20px;
1157 height: 80px;
1158
1159 started => {
1160 root.gestures-started += 1;
1161 }
1162 }
1163 }
1164 }
1165
1166 struct FakeTouch {
1167 samples: VecDeque<Option<TouchPoint>>,
1168 }
1169
1170 impl TouchInput for FakeTouch {
1171 type Error = core::convert::Infallible;
1172
1173 fn read_touch(&mut self) -> Result<Option<TouchPoint>, Self::Error> {
1174 Ok(self.samples.pop_front().flatten())
1175 }
1176 }
1177
1178 fn poll_single<T>(tracker: &mut TouchTracker<T>) -> TouchUpdate
1179 where
1180 T: TouchInput,
1181 T::Error: fmt::Debug,
1182 {
1183 match tracker.poll().unwrap() {
1184 TouchUpdates::Single(update) => update,
1185 TouchUpdates::Multi(_) => panic!("single-touch tracker returned multi-touch updates"),
1186 }
1187 }
1188
1189 struct FakeMultiTouch {
1190 samples: VecDeque<Vec<TouchContact>>,
1191 }
1192
1193 impl TouchInput for FakeMultiTouch {
1194 type Error = core::convert::Infallible;
1195
1196 fn read_touch(&mut self) -> Result<Option<TouchPoint>, Self::Error> {
1197 Ok(self
1198 .samples
1199 .pop_front()
1200 .and_then(|contacts| contacts.first().map(|contact| contact.position)))
1201 }
1202
1203 fn read_touches(&mut self, contacts: &mut [TouchContact]) -> Result<usize, Self::Error> {
1204 let Some(sample) = self.samples.pop_front() else {
1205 return Ok(0);
1206 };
1207 let count = sample.len().min(contacts.len());
1208 contacts[..count].copy_from_slice(&sample[..count]);
1209 Ok(count)
1210 }
1211 }
1212
1213 fn contact(id: u8, x: u16, y: u16) -> TouchContact {
1214 TouchContact::new(id, TouchPoint::new(x, y))
1215 }
1216
1217 fn poll_multi<T>(tracker: &mut TouchTracker<T>) -> MultiTouchUpdates
1218 where
1219 T: TouchInput,
1220 T::Error: fmt::Debug,
1221 {
1222 match tracker.poll().unwrap() {
1223 TouchUpdates::Multi(updates) => updates,
1224 TouchUpdates::Single(_) => panic!("multi-touch tracker returned a single update"),
1225 }
1226 }
1227
1228 #[test]
1229 fn touch_samples_become_pointer_transitions() {
1230 let touch = FakeTouch {
1231 samples: [
1232 None,
1233 Some(TouchPoint::new(10, 20)),
1234 Some(TouchPoint::new(11, 21)),
1235 Some(TouchPoint::new(11, 21)),
1236 None,
1237 ]
1238 .into(),
1239 };
1240 let mut tracker =
1241 TouchTracker::new(touch, 320, 240, OutOfBoundsTouch::Clamp, TouchMode::Single);
1242
1243 assert_eq!(poll_single(&mut tracker), TouchUpdate::None);
1244 assert_eq!(
1245 poll_single(&mut tracker),
1246 TouchUpdate::Pressed(LogicalPosition::new(10.0, 20.0))
1247 );
1248 assert_eq!(
1249 poll_single(&mut tracker),
1250 TouchUpdate::Moved(LogicalPosition::new(11.0, 21.0))
1251 );
1252 assert_eq!(poll_single(&mut tracker), TouchUpdate::None);
1253 assert_eq!(
1254 poll_single(&mut tracker),
1255 TouchUpdate::Released(LogicalPosition::new(11.0, 21.0))
1256 );
1257 }
1258
1259 #[test]
1260 fn touch_coordinates_are_clamped_to_the_display() {
1261 let touch = FakeTouch {
1262 samples: [Some(TouchPoint::new(u16::MAX, u16::MAX))].into(),
1263 };
1264 let mut tracker =
1265 TouchTracker::new(touch, 320, 240, OutOfBoundsTouch::Clamp, TouchMode::Single);
1266
1267 assert_eq!(
1268 poll_single(&mut tracker),
1269 TouchUpdate::Pressed(LogicalPosition::new(319.0, 239.0))
1270 );
1271 }
1272
1273 #[test]
1274 fn ignored_out_of_bounds_touch_releases_an_active_contact() {
1275 let touch = FakeTouch {
1276 samples: [
1277 Some(TouchPoint::new(400, 20)),
1278 Some(TouchPoint::new(10, 20)),
1279 Some(TouchPoint::new(400, 20)),
1280 Some(TouchPoint::new(400, 20)),
1281 Some(TouchPoint::new(11, 21)),
1282 ]
1283 .into(),
1284 };
1285 let mut tracker =
1286 TouchTracker::new(touch, 320, 240, OutOfBoundsTouch::Ignore, TouchMode::Single);
1287
1288 assert_eq!(poll_single(&mut tracker), TouchUpdate::None);
1289 assert_eq!(
1290 poll_single(&mut tracker),
1291 TouchUpdate::Pressed(LogicalPosition::new(10.0, 20.0))
1292 );
1293 assert_eq!(
1294 poll_single(&mut tracker),
1295 TouchUpdate::Released(LogicalPosition::new(10.0, 20.0))
1296 );
1297 assert_eq!(poll_single(&mut tracker), TouchUpdate::None);
1298 assert_eq!(
1299 poll_single(&mut tracker),
1300 TouchUpdate::Pressed(LogicalPosition::new(11.0, 21.0))
1301 );
1302 }
1303
1304 #[test]
1305 fn multi_touch_tracks_stable_ids_across_snapshots() {
1306 let touch = FakeMultiTouch {
1307 samples: [
1308 vec![contact(1, 10, 10)],
1309 vec![contact(1, 10, 10), contact(7, 20, 10)],
1310 vec![contact(7, 20, 10), contact(1, 11, 10)],
1311 vec![contact(7, 20, 10)],
1312 vec![],
1313 ]
1314 .into(),
1315 };
1316 let mut tracker =
1317 TouchTracker::new(touch, 320, 240, OutOfBoundsTouch::Clamp, TouchMode::Multi);
1318
1319 assert_eq!(
1320 poll_multi(&mut tracker).iter().collect::<Vec<_>>(),
1321 vec![MultiTouchUpdate {
1322 id: 1,
1323 position: LogicalPosition::new(10.0, 10.0),
1324 phase: MultiTouchPhase::Started,
1325 }]
1326 );
1327 assert_eq!(
1328 poll_multi(&mut tracker).iter().collect::<Vec<_>>(),
1329 vec![MultiTouchUpdate {
1330 id: 7,
1331 position: LogicalPosition::new(20.0, 10.0),
1332 phase: MultiTouchPhase::Started,
1333 }]
1334 );
1335 assert_eq!(
1336 poll_multi(&mut tracker).iter().collect::<Vec<_>>(),
1337 vec![MultiTouchUpdate {
1338 id: 1,
1339 position: LogicalPosition::new(11.0, 10.0),
1340 phase: MultiTouchPhase::Moved,
1341 }]
1342 );
1343 assert_eq!(
1344 poll_multi(&mut tracker).iter().collect::<Vec<_>>(),
1345 vec![MultiTouchUpdate {
1346 id: 1,
1347 position: LogicalPosition::new(11.0, 10.0),
1348 phase: MultiTouchPhase::Ended,
1349 }]
1350 );
1351 assert_eq!(
1352 poll_multi(&mut tracker).iter().collect::<Vec<_>>(),
1353 vec![MultiTouchUpdate {
1354 id: 7,
1355 position: LogicalPosition::new(20.0, 10.0),
1356 phase: MultiTouchPhase::Ended,
1357 }]
1358 );
1359 }
1360
1361 #[test]
1362 fn ignored_multi_touch_contact_ends_at_its_last_valid_position() {
1363 let touch = FakeMultiTouch {
1364 samples: [
1365 vec![contact(3, 10, 20)],
1366 vec![contact(3, 400, 20)],
1367 vec![contact(3, 400, 20)],
1368 ]
1369 .into(),
1370 };
1371 let mut tracker =
1372 TouchTracker::new(touch, 320, 240, OutOfBoundsTouch::Ignore, TouchMode::Multi);
1373
1374 let _ = poll_multi(&mut tracker);
1375 assert_eq!(
1376 poll_multi(&mut tracker).iter().collect::<Vec<_>>(),
1377 vec![MultiTouchUpdate {
1378 id: 3,
1379 position: LogicalPosition::new(10.0, 20.0),
1380 phase: MultiTouchPhase::Ended,
1381 }]
1382 );
1383 assert!(poll_multi(&mut tracker).is_empty());
1384 }
1385
1386 #[test]
1387 fn multi_mode_adapts_an_existing_single_touch_driver() {
1388 let touch = FakeTouch {
1389 samples: [Some(TouchPoint::new(12, 34)), None].into(),
1390 };
1391 let mut tracker =
1392 TouchTracker::new(touch, 320, 240, OutOfBoundsTouch::Clamp, TouchMode::Multi);
1393
1394 assert_eq!(
1395 poll_multi(&mut tracker).iter().collect::<Vec<_>>(),
1396 vec![MultiTouchUpdate {
1397 id: 0,
1398 position: LogicalPosition::new(12.0, 34.0),
1399 phase: MultiTouchPhase::Started,
1400 }]
1401 );
1402 assert_eq!(
1403 poll_multi(&mut tracker).iter().collect::<Vec<_>>(),
1404 vec![MultiTouchUpdate {
1405 id: 0,
1406 position: LogicalPosition::new(12.0, 34.0),
1407 phase: MultiTouchPhase::Ended,
1408 }]
1409 );
1410 }
1411
1412 #[test]
1413 fn public_types_are_send_free_and_no_std_friendly() {
1414 static_assertions::assert_impl_all!(TouchPoint: Copy, Send, Sync);
1415 static_assertions::assert_impl_all!(TouchContact: Copy, Send, Sync);
1416 static_assertions::assert_impl_all!(TouchMode: Copy, Send, Sync);
1417 static_assertions::assert_impl_all!(NoTouch: Copy, Send, Sync);
1418 static_assertions::assert_impl_all!(OutOfBoundsTouch: Copy, Send, Sync);
1419 }
1420
1421 #[derive(Clone, Default)]
1422 struct FakeRuntime {
1423 now: Rc<Cell<Duration>>,
1424 }
1425
1426 impl FakeRuntime {
1427 fn advance(&self, duration: Duration) {
1428 self.now.set(self.now.get().saturating_add(duration));
1429 }
1430 }
1431
1432 impl McuRuntime for FakeRuntime {
1433 fn now(&self) -> Duration {
1434 self.now.get()
1435 }
1436
1437 fn wait(&mut self, duration: Duration) {
1438 self.advance(duration);
1439 }
1440 }
1441
1442 fn wait_after_work(work: Duration, timer_wait: Option<Duration>) -> Duration {
1443 let runtime = FakeRuntime::default();
1444 let started_at = runtime.now();
1445 let mut timing = EventLoopTiming::new(started_at, Duration::from_millis(16), None);
1446 timing.frame_processed(started_at);
1447 runtime.advance(work);
1448 timing.next_wait(runtime.now(), timer_wait, true)
1449 }
1450
1451 #[test]
1452 fn frame_pacing_subtracts_iteration_work_time() {
1453 assert_eq!(
1454 wait_after_work(Duration::from_millis(4), None),
1455 Duration::from_millis(12)
1456 );
1457 assert_eq!(
1458 wait_after_work(Duration::from_millis(14), None),
1459 Duration::from_millis(2)
1460 );
1461 assert_eq!(
1462 wait_after_work(Duration::from_millis(20), None),
1463 Duration::ZERO
1464 );
1465 }
1466
1467 #[test]
1468 fn slint_timer_deadline_wins_over_remaining_frame_time() {
1469 assert_eq!(
1470 wait_after_work(Duration::from_millis(4), Some(Duration::from_millis(3))),
1471 Duration::from_millis(3)
1472 );
1473 }
1474
1475 #[test]
1476 fn touch_and_frame_deadlines_are_independent() {
1477 let mut timing = EventLoopTiming::new(
1478 Duration::ZERO,
1479 Duration::from_millis(33),
1480 Some(Duration::from_millis(5)),
1481 );
1482 timing.frame_processed(Duration::ZERO);
1483 timing.touch_polled(Duration::ZERO);
1484
1485 assert_eq!(
1486 timing.due_work(Duration::from_millis(5)),
1487 DueWork {
1488 frame: false,
1489 touch: true,
1490 }
1491 );
1492 assert_eq!(
1493 timing.due_work(Duration::from_millis(33)),
1494 DueWork {
1495 frame: true,
1496 touch: true,
1497 }
1498 );
1499 }
1500
1501 #[test]
1502 fn no_touch_timer_is_not_capped_by_frame_interval() {
1503 let mut timing = EventLoopTiming::new(Duration::ZERO, Duration::from_millis(16), None);
1504 timing.frame_processed(Duration::ZERO);
1505
1506 assert_eq!(
1507 timing.next_wait(
1508 Duration::from_millis(4),
1509 Some(Duration::from_secs(1)),
1510 false,
1511 ),
1512 Duration::from_secs(1)
1513 );
1514 }
1515
1516 #[test]
1517 fn no_touch_idle_ui_uses_a_low_frequency_fallback() {
1518 let mut timing = EventLoopTiming::new(Duration::ZERO, Duration::from_millis(16), None);
1519 timing.frame_processed(Duration::ZERO);
1520
1521 assert_eq!(
1522 timing.next_wait(Duration::from_millis(4), None, false),
1523 DEFAULT_IDLE_POLL_INTERVAL
1524 );
1525 }
1526
1527 #[test]
1528 fn early_wakeup_checks_for_redraw_at_the_frame_deadline() {
1529 let mut timing = EventLoopTiming::new(Duration::ZERO, Duration::from_millis(16), None);
1530 timing.frame_processed(Duration::ZERO);
1531
1532 let early_wakeup = Duration::from_millis(4);
1533 assert!(!timing.due_work(early_wakeup).frame);
1534 timing.mark_frame_pending();
1535
1536 assert_eq!(
1537 timing.next_wait(early_wakeup, None, false),
1538 Duration::from_millis(12)
1539 );
1540 }
1541
1542 #[derive(Default)]
1543 struct RecordingDisplay {
1544 pixels: Vec<Pixel<Rgb565>>,
1545 }
1546
1547 impl OriginDimensions for RecordingDisplay {
1548 fn size(&self) -> Size {
1549 Size::new(4, 4)
1550 }
1551 }
1552
1553 impl DrawTarget for RecordingDisplay {
1554 type Color = Rgb565;
1555 type Error = core::convert::Infallible;
1556
1557 fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
1558 where
1559 I: IntoIterator<Item = Pixel<Self::Color>>,
1560 {
1561 self.pixels.extend(pixels);
1562 Ok(())
1563 }
1564 }
1565
1566 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1567 struct InjectedDisplayError;
1568
1569 struct FailingDisplay {
1570 areas: Vec<Rectangle>,
1571 attempts: usize,
1572 fail_on_attempt: Option<usize>,
1573 }
1574
1575 impl FailingDisplay {
1576 fn fail_on(attempt: usize) -> Self {
1577 Self {
1578 areas: Vec::new(),
1579 attempts: 0,
1580 fail_on_attempt: Some(attempt),
1581 }
1582 }
1583
1584 fn clear_recording(&mut self) {
1585 self.areas.clear();
1586 self.attempts = 0;
1587 }
1588 }
1589
1590 impl OriginDimensions for FailingDisplay {
1591 fn size(&self) -> Size {
1592 Size::new(100, 100)
1593 }
1594 }
1595
1596 impl DrawTarget for FailingDisplay {
1597 type Color = Rgb565;
1598 type Error = InjectedDisplayError;
1599
1600 fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
1601 where
1602 I: IntoIterator<Item = Pixel<Self::Color>>,
1603 {
1604 for _ in pixels {}
1605 Ok(())
1606 }
1607
1608 fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error>
1609 where
1610 I: IntoIterator<Item = Self::Color>,
1611 {
1612 let attempt = self.attempts;
1613 self.attempts += 1;
1614 self.areas.push(*area);
1615
1616 if self.fail_on_attempt == Some(attempt) {
1617 self.fail_on_attempt = None;
1618 return Err(InjectedDisplayError);
1619 }
1620
1621 for _ in colors {}
1622 Ok(())
1623 }
1624 }
1625
1626 #[test]
1627 fn platform_integration_recovers_display_and_dispatches_multi_touch() {
1628 let window = MinimalSoftwareWindow::new(PARTIAL_REPAINT_BUFFER_TYPE);
1629 let runtime = FakeRuntime::default();
1630 let touch = FakeMultiTouch {
1631 samples: [
1632 vec![contact(1, 10, 10)],
1633 vec![],
1634 vec![contact(1, 20, 50)],
1635 vec![contact(1, 20, 50), contact(2, 50, 50)],
1636 vec![contact(1, 10, 50), contact(2, 70, 50)],
1637 ]
1638 .into(),
1639 };
1640 let backend = Rc::new(McuBackend {
1641 window: window.clone(),
1642 display: RefCell::new(DisplayState {
1643 display: FailingDisplay::fail_on(1),
1644 line_buffer: vec![Rgb565Pixel::default(); 100],
1645 full_repaint_pending: false,
1646 }),
1647 touch: RefCell::new(TouchTracker::new(
1648 touch,
1649 100,
1650 100,
1651 OutOfBoundsTouch::Clamp,
1652 TouchMode::Multi,
1653 )),
1654 runtime: RefCell::new(runtime),
1655 started_at: Duration::ZERO,
1656 timing: RefCell::new(EventLoopTiming::new(
1657 Duration::ZERO,
1658 DEFAULT_POLL_INTERVAL,
1659 None,
1660 )),
1661 });
1662
1663 platform::set_platform(Box::new(McuPlatform {
1664 backend: backend.clone(),
1665 }))
1666 .unwrap();
1667 let app = RecoveryTestWindow::new().unwrap();
1668 window.set_size(PhysicalSize::new(100, 100));
1669 app.show().unwrap();
1670
1671 let first_error = backend.render().unwrap_err();
1672 assert!(format!("{first_error}").contains("display rendering failed"));
1673 assert!(backend.display.borrow().full_repaint_pending);
1674
1675 backend.display.borrow_mut().display.clear_recording();
1676 assert!(backend.render().unwrap());
1677 {
1678 let state = backend.display.borrow();
1679 assert!(!state.full_repaint_pending);
1680 assert_eq!(state.display.areas.len(), 100);
1681 assert!(
1682 state
1683 .display
1684 .areas
1685 .iter()
1686 .all(|area| area.size == Size::new(100, 1))
1687 );
1688 }
1689
1690 backend.display.borrow_mut().display.clear_recording();
1691 app.set_alternate(true);
1692 assert!(backend.render().unwrap());
1693 let state = backend.display.borrow();
1694 assert!(!state.display.areas.is_empty());
1695 assert!(state.display.areas.len() < 100);
1696 assert!(
1697 state
1698 .display
1699 .areas
1700 .iter()
1701 .all(|area| area.size.width < 100 || area.size.height < 100)
1702 );
1703 drop(state);
1704
1705 assert!(backend.dispatch_touch().unwrap());
1706 assert!(backend.dispatch_touch().unwrap());
1707 assert!(backend.dispatch_touch().unwrap());
1708 assert!(backend.dispatch_touch().unwrap());
1709 assert!(backend.dispatch_touch().unwrap());
1710 assert_eq!(app.get_clicks(), 1);
1711 assert_eq!(app.get_gestures_started(), 1);
1712 }
1713
1714 #[test]
1715 fn line_renderer_writes_only_the_dirty_range() {
1716 let mut display = RecordingDisplay::default();
1717 let mut buffer = [Rgb565Pixel::default(); 4];
1718 let mut error = None;
1719 let mut provider = MipidsiLineBuffer {
1720 display: &mut display,
1721 line_buffer: &mut buffer,
1722 error: &mut error,
1723 };
1724
1725 provider.process_line(3, 1..3, |line| {
1726 line[0] = Rgb565Pixel(0xf800);
1727 line[1] = Rgb565Pixel(0x07e0);
1728 });
1729
1730 assert!(error.is_none());
1731 assert_eq!(
1732 display.pixels,
1733 [
1734 Pixel(Point::new(1, 3), Rgb565::RED),
1735 Pixel(Point::new(2, 3), Rgb565::GREEN),
1736 ]
1737 );
1738 }
1739}