From 143bb8ea8463a614fef347c4ea4f3d5aed7dc94e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1niel=20Buga?= Date: Wed, 8 Jul 2020 10:22:51 +0200 Subject: [PATCH] Wrapper to cache the bounding box of a view --- src/layout/linear/mod.rs | 5 ++-- src/utils/cached.rs | 50 ++++++++++++++++++++++++++++++++++++++++ src/utils/mod.rs | 1 + 3 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 src/utils/cached.rs diff --git a/src/layout/linear/mod.rs b/src/layout/linear/mod.rs index d931da9..de17486 100644 --- a/src/layout/linear/mod.rs +++ b/src/layout/linear/mod.rs @@ -91,6 +91,7 @@ pub use orientation::{Horizontal, Orientation, Vertical}; pub use secondary_alignment::SecondaryAlignment; pub use spacing::{ElementSpacing, FixedMargin}; +use crate::utils::cached::Cached; use layout_element::LayoutElement; use spacing::Tight; @@ -221,10 +222,10 @@ where /// Views will be laid out sequentially, keeping the order in which they were added to the /// layout. #[inline] - pub fn add_view(self, view: V) -> LinearLayout> { + pub fn add_view(self, view: V) -> LinearLayout, LE>> { LinearLayout { direction: self.direction, - views: self.views.add_view(view), + views: self.views.add_view(Cached::new(view)), } } diff --git a/src/utils/cached.rs b/src/utils/cached.rs new file mode 100644 index 0000000..6d9ba6c --- /dev/null +++ b/src/utils/cached.rs @@ -0,0 +1,50 @@ +//! Bounding box cache wrapper +use crate::prelude::*; +use embedded_graphics::{primitives::Rectangle, DrawTarget}; + +/// Cache the bounding box of the wrapped [`View`] +pub struct Cached { + bounds: Rectangle, + view: V, +} + +impl Cached { + /// Calculate a View's bounding box and store it for reuse + #[inline] + pub fn new(v: V) -> Self { + let bounds = v.bounds(); + + Self { view: v, bounds } + } + + /// Unwrap the inner View + #[inline] + pub fn into_inner(self) -> V { + self.view + } +} + +impl View for Cached { + #[inline] + fn translate(&mut self, by: Point) { + self.bounds.translate(by); + self.view.translate(by); + } + + #[inline] + fn bounds(&self) -> Rectangle { + self.bounds + } +} + +impl<'a, V, C> Drawable for &'a Cached +where + C: PixelColor, + V: View, + &'a V: Drawable, +{ + #[inline] + fn draw>(self, display: &mut D) -> Result<(), D::Error> { + self.view.draw(display) + } +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs index f3344b6..74f1ae5 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,5 +1,6 @@ //! Utility collection module +pub mod cached; pub mod display_area; pub mod object_chain; pub mod rect_helper;