1use super::{Buffer, Rect, Drawable, Pixel, Pixels, Coord, Style};
2
3pub struct Canvas<'a, S: Style> {
4 buffer: &'a mut Buffer<S>,
5 pub frame: Rect,
6}
7
8impl<'a, S: Style> Canvas<'a, S> {
9 pub fn new(buffer: &'a mut Buffer<S>, frame: Rect) -> Self {
10 Self {
11 buffer,
12 frame,
13 }
14 }
15}
16
17impl<'a, S: Style> Drawable<S> for Canvas<'a, S> {
18 fn fill(&mut self, text: char, style: S) {
19 self.buffer.rect(self.frame, text, style);
20 }
21
22 fn rect(&mut self, rect: Rect, text: char, style: S) {
23 self.buffer.rect(Rect::new(rect.x + self.frame.x, rect.y + self.frame.y, rect.width, rect.height), text, style);
24 }
25
26 fn string(&mut self, x: u16, y: u16, text: String, style: S) {
27 let mut current_x = x;
28 let mut current_y = y;
29
30 for c in text.chars() {
31 self.pixel(
32 current_x,
33 current_y,
34 Pixel {
35 text: Some(c),
36 style,
37 },
38 );
39
40 current_x += 1;
41 if current_x >= self.frame.width {
42 current_x = 0;
43 current_y += 1;
44 }
45 }
46 }
47
48 fn pixels(&mut self, x: u16, y: u16, pixels: &Pixels<S>) {
49 let mut current_x = x;
50 let mut current_y = y;
51
52 for p in pixels.iter(){
53 self.pixel(
54 current_x,
55 current_y,
56 *p
57 );
58
59 current_x += 1;
60 if current_x >= self.frame.width {
61 current_x = 0;
62 current_y += 1;
63 }
64 }
65 }
66
67 fn pixel(&mut self, x: u16, y: u16, pixel: Pixel<S>) {
68 self.buffer.pixel(self.frame.x + x, self.frame.y + y, pixel);
69 }
70
71 fn pixel_at_index(&mut self, index: usize, pixel: Pixel<S>) {
72 let index = Coord::from_index(index, self.frame.width).as_index(self.buffer.width);
73 self.buffer.pixel_at_index(index, pixel);
74 }
75}
76
77