tui_temp_fork/widgets/canvas/
line.rs

1use super::Shape;
2use crate::style::Color;
3
4/// Shape to draw a line from (x1, y1) to (x2, y2) with the given color
5pub struct Line {
6    pub x1: f64,
7    pub y1: f64,
8    pub x2: f64,
9    pub y2: f64,
10    pub color: Color,
11}
12
13pub struct LineIterator {
14    x: f64,
15    y: f64,
16    dx: f64,
17    dy: f64,
18    dir_x: f64,
19    dir_y: f64,
20    current: f64,
21    end: f64,
22}
23
24impl Iterator for LineIterator {
25    type Item = (f64, f64);
26
27    fn next(&mut self) -> Option<Self::Item> {
28        if self.current < self.end {
29            let pos = (
30                self.x + (self.current * self.dx) / self.end * self.dir_x,
31                self.y + (self.current * self.dy) / self.end * self.dir_y,
32            );
33            self.current += 1.0;
34            Some(pos)
35        } else {
36            None
37        }
38    }
39}
40
41impl<'a> IntoIterator for &'a Line {
42    type Item = (f64, f64);
43    type IntoIter = LineIterator;
44
45    fn into_iter(self) -> Self::IntoIter {
46        let dx = self.x1.max(self.x2) - self.x1.min(self.x2);
47        let dy = self.y1.max(self.y2) - self.y1.min(self.y2);
48        let dir_x = if self.x1 <= self.x2 { 1.0 } else { -1.0 };
49        let dir_y = if self.y1 <= self.y2 { 1.0 } else { -1.0 };
50        let end = dx.max(dy);
51        LineIterator {
52            x: self.x1,
53            y: self.y1,
54            dx,
55            dy,
56            dir_x,
57            dir_y,
58            current: 0.0,
59            end,
60        }
61    }
62}
63
64impl<'a> Shape<'a> for Line {
65    fn color(&self) -> Color {
66        self.color
67    }
68
69    fn points(&'a self) -> Box<dyn Iterator<Item = (f64, f64)> + 'a> {
70        Box::new(self.into_iter())
71    }
72}