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
73
74
75
76
77
78
79
80
81
82
83
84
85
use crate::color::Color;
use crate::graphics::*;
use crate::input::*;
use crate::widget::*;
use std::io;

pub struct Canvas {
    pub background: Option<Color>,
    pub foreground: Option<Color>,
    pub drawings: Vec<Drawing>,
    pub elements: ElementaryWidget,
}

impl Canvas {
    pub fn new() -> Canvas {
        Default::default()
    }

    pub fn set_layout<L: Layout + 'static>(mut self, layout: L) -> Self {
        self.elements.set_layout(layout);
        self
    }

    pub fn add_element<E: LayoutElement + 'static, I: IntoLayoutElement<E>>(
        mut self,
        item: I,
    ) -> Self {
        self.elements.add_element(item);
        self
    }

    pub fn set_color(mut self, foreground: Option<Color>, background: Option<Color>) -> Self {
        self.foreground = foreground;
        self.background = background;
        self
    }

    pub fn add_drawing(mut self, drawing: Drawing) -> Self {
        self.drawings.push(drawing);
        self
    }
}

impl Default for Canvas {
    fn default() -> Canvas {
        Canvas {
            background: None,
            foreground: None,
            elements: ElementaryWidget::new(),
            drawings: vec![],
        }
    }
}

impl Widget for Canvas {
    fn render(&self, painter: &mut Painter) -> io::Result<()> {
        trace!("Drawing into {:?}", painter.get_area());

        if let Some(c) = self.background {
            painter.fill(c)?;
        }

        let mystyle = Style {
            foreground: self.foreground,
            background: self.background,
            ..Default::default()
        };
        let scope = painter.get_area();
        let painter = &mut PainterScope::new(painter, scope, mystyle);

        for ref mut drawing in self.drawings.iter() {
            painter.paint(drawing.clone())?;
        }

        self.elements.render(painter)
    }

    fn arrange(&mut self, window: Window) {
        self.elements.arrange(window)
    }

    fn consume(&mut self, input: Vec<GrinInput>) -> Vec<GrinInput> {
        self.elements.consume(input)
    }
}