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
use prototty_render::*;

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy)]
pub enum AlignX {
    Left,
    Centre,
    Right,
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy)]
pub enum AlignY {
    Top,
    Centre,
    Bottom,
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy)]
pub struct Align {
    pub x: AlignX,
    pub y: AlignY,
}

impl Align {
    pub fn new(x: AlignX, y: AlignY) -> Self {
        Self { x, y }
    }
}

#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy)]
pub struct Aligned<V> {
    pub view: V,
    pub align: Align,
}

impl<V> Aligned<V> {
    pub fn new(view: V, align: Align) -> Self {
        Self { view, align }
    }
    pub fn centre(view: V) -> Self {
        Self::new(view, Align::new(AlignX::Centre, AlignY::Centre))
    }
}

impl<T: Clone, V: View<T>> View<T> for Aligned<V> {
    fn view<G: ViewGrid, R: ViewTransformRgb24>(
        &mut self,
        data: T,
        context: ViewContext<R>,
        grid: &mut G,
    ) {
        let data_size = self.view.visible_bounds(data.clone(), context);
        let x_offset = match self.align.x {
            AlignX::Left => 0,
            AlignX::Centre => (context.size.x() as i32 - data_size.x() as i32) / 2,
            AlignX::Right => context.size.x() as i32 - data_size.x() as i32,
        };
        let y_offset = match self.align.y {
            AlignY::Top => 0,
            AlignY::Centre => (context.size.y() as i32 - data_size.y() as i32) / 2,
            AlignY::Bottom => context.size.y() as i32 - data_size.y() as i32,
        };
        self.view.view(
            data,
            context.add_offset(Coord::new(x_offset, y_offset)),
            grid,
        );
    }
}