1use crate::cache::{self, Cached};
2use crate::core::Size;
3use crate::geometry::{self, Frame};
45pub use cache::Group;
67/// A simple cache that stores generated geometry to avoid recomputation.
8///
9/// A [`Cache`] will not redraw its geometry unless the dimensions of its layer
10/// change or it is explicitly cleared.
11pub struct Cache<Renderer>
12where
13Renderer: geometry::Renderer,
14{
15 raw: crate::Cache<Data<<Renderer::Geometry as Cached>::Cache>>,
16}
1718#[derive(Debug, Clone)]
19struct Data<T> {
20 bounds: Size,
21 geometry: T,
22}
2324impl<Renderer> Cache<Renderer>
25where
26Renderer: geometry::Renderer,
27{
28/// Creates a new empty [`Cache`].
29pub fn new() -> Self {
30 Cache {
31 raw: cache::Cache::new(),
32 }
33 }
3435/// Creates a new empty [`Cache`] with the given [`Group`].
36 ///
37 /// Caches within the same group may reuse internal rendering storage.
38 ///
39 /// You should generally group caches that are likely to change
40 /// together.
41pub fn with_group(group: Group) -> Self {
42 Cache {
43 raw: crate::Cache::with_group(group),
44 }
45 }
4647/// Clears the [`Cache`], forcing a redraw the next time it is used.
48pub fn clear(&self) {
49self.raw.clear();
50 }
5152/// Draws geometry using the provided closure and stores it in the
53 /// [`Cache`].
54 ///
55 /// The closure will only be called when
56 /// - the bounds have changed since the previous draw call.
57 /// - the [`Cache`] is empty or has been explicitly cleared.
58 ///
59 /// Otherwise, the previously stored geometry will be returned. The
60 /// [`Cache`] is not cleared in this case. In other words, it will keep
61 /// returning the stored geometry if needed.
62pub fn draw(
63&self,
64 renderer: &Renderer,
65 bounds: Size,
66 draw_fn: impl FnOnce(&mut Frame<Renderer>),
67 ) -> Renderer::Geometry {
68use std::ops::Deref;
6970let state = self.raw.state();
7172let previous = match state.borrow().deref() {
73 cache::State::Empty { previous } => {
74 previous.as_ref().map(|data| data.geometry.clone())
75 }
76 cache::State::Filled { current } => {
77if current.bounds == bounds {
78return Cached::load(¤t.geometry);
79 }
8081Some(current.geometry.clone())
82 }
83 };
8485let mut frame = Frame::new(renderer, bounds);
86 draw_fn(&mut frame);
8788let geometry = frame.into_geometry().cache(self.raw.group(), previous);
89let result = Cached::load(&geometry);
9091*state.borrow_mut() = cache::State::Filled {
92 current: Data { bounds, geometry },
93 };
9495 result
96 }
97}
9899impl<Renderer> std::fmt::Debug for Cache<Renderer>
100where
101Renderer: geometry::Renderer,
102 <Renderer::Geometry as Cached>::Cache: std::fmt::Debug,
103{
104fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105write!(f, "{:?}", &self.raw)
106 }
107}
108109impl<Renderer> Default for Cache<Renderer>
110where
111Renderer: geometry::Renderer,
112{
113fn default() -> Self {
114Self::new()
115 }
116}