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
use crate::view::{View, ViewWrapper};
use crate::views::NamedView;
use crate::Printer;
use crate::Vec2;
use std::cell::Cell;

/// Wrapper around a view that remembers its position.
pub struct TrackedView<T: View> {
    /// Wrapped view.
    pub view: T,
    /// Last position the view was located.
    offset: Cell<Vec2>,
}

impl<T: View> TrackedView<T> {
    /// Return the last offset at which the view was drawn.
    pub fn offset(&self) -> Vec2 {
        self.offset.get()
    }

    /// Creates a new `TrackedView` around `view`.
    pub fn new(view: T) -> Self {
        TrackedView {
            view,
            offset: Cell::new(Vec2::zero()),
        }
    }

    /// Same as [`with_name`](TrackedView::with_name)
    #[deprecated(note = "`with_id` is being renamed to `with_name`")]
    pub fn with_id(self, id: &str) -> NamedView<Self> {
        self.with_name(id)
    }

    /// Wraps itself in a `NamedView` for easy retrieval.
    pub fn with_name(self, name: &str) -> NamedView<Self> {
        NamedView::new(name, self)
    }

    inner_getters!(self.view: T);
}

impl<T: View> ViewWrapper for TrackedView<T> {
    wrap_impl!(self.view: T);

    fn wrap_draw(&self, printer: &Printer<'_, '_>) {
        self.offset.set(printer.offset);
        self.view.draw(printer);
    }
}