plotters_unsable/element/
mod.rs

1/*!
2    Defines the drawing elements, the high-level drawing unit in Plotters drawing system
3
4    ## Introduction
5    An element is the drawing unit for Plotter's high-level drawing API.
6    Different from low-level drawing API, an element is a logic unit of component in the image.
7    There are few built-in elements, including `Circle`, `Pixel`, `Rectangle`, `Path`, `Text`, etc.
8
9    All element can be drawn onto the drawing area using API `DrawingArea::draw(...)`.
10    Plotters use "iterator of elements" as the abstraction of any type of plot.
11
12    ## Implementing your own element
13    You can also define your own element, `CandleStick` is a good sample of implementing complex
14    element. There are two trait required for an element:
15
16    - `PointCollection` - the struct should be able to return an iterator of key-points under guest coordinate
17    - `Drawable` - the struct should be able to use performe drawing on a drawing backend with pixel-based coordinate
18
19    An example of element that draws a red "X" in a red rectangle onto the backend:
20
21    ```rust
22    use std::iter::{Once, once};
23    use plotters::element::{PointCollection, Drawable};
24    use plotters::drawing::backend::{BackendCoord, DrawingErrorKind};
25    use plotters::prelude::*;
26
27    // Any example drawing a red X
28    struct RedBoxedX((i32, i32));
29
30    // For any reference to RedX, we can convert it into an iterator of points
31    impl <'a> PointCollection<'a, (i32, i32)> for &'a RedBoxedX {
32        type Borrow = &'a (i32, i32);
33        type IntoIter = Once<&'a (i32, i32)>;
34        fn point_iter(self) -> Self::IntoIter {
35            once(&self.0)
36        }
37    }
38
39    // How to actually draw this element
40    impl <DB:DrawingBackend> Drawable<DB> for RedBoxedX {
41        fn draw<I:Iterator<Item = BackendCoord>>(
42            &self,
43            mut pos: I,
44            backend: &mut DB
45        ) -> Result<(), DrawingErrorKind<DB::ErrorType>> {
46            let pos = pos.next().unwrap();
47            backend.draw_rect(pos, (pos.0 + 10, pos.1 + 12), &Red, false)?;
48            backend.draw_text("X", &("Arial", 20).into(), pos, &Red)
49        }
50    }
51
52    fn main() -> Result<(), Box<dyn std::error::Error>> {
53        let root = BitMapBackend::new(
54            "examples/outputs/element-0.png",
55            (640, 480)
56        ).into_drawing_area();
57        root.draw(&RedBoxedX((200, 200)))?;
58        Ok(())
59    }
60    ```
61      ![](https://raw.githubusercontent.com/38/plotters/master/examples/outputs/element-0.png)
62
63      ## Composable Elements
64      You also have an convenient way to build an element that isn't built into the Plotters library by
65      combining existing elements into a logic group. To build an composable elemnet, you need to use an
66      logic empty element that draws nothing to the backend but denotes the relative zero point of the logical
67      group. Any element defined with pixel based offset coordinate can be added into the group later using
68      the `+` operator.
69
70      For example, the red boxed X element can be implemented with Composable element in the following way:
71    ```rust
72    use plotters::prelude::*;
73    fn main() -> Result<(), Box<dyn std::error::Error>> {
74        let root = BitMapBackend::new(
75            "examples/outputs/element-1.png",
76            (640, 480)
77        ).into_drawing_area();
78        let font:FontDesc = ("Arial", 20).into();
79        root.draw(&(EmptyElement::at((200, 200))
80                + Text::new("X", (0, 0), &"Arial".into_font().resize(20.0).color(&Red))
81                + Rectangle::new([(0,0), (10, 12)], &Red)
82        ))?;
83        Ok(())
84    }
85    ```
86    ![](https://raw.githubusercontent.com/38/plotters/master/examples/outputs/element-1.png)
87
88    ## Dynamic Elements
89    By default, Plotters uses static dispatch for all the elements and series. For example,
90    the `ChartContext::draw_series` method accepts an iterator of `T` where type `T` implements
91    all the traits a element should implement. Although, we can use the series of composable element
92    for complex series drawing. But sometimes, we still want to make the series heterogyous, which means
93    the iterator should be able to holds elements in different type.
94    For example, a point series with corss and circle. This requires the dynamically dispatched elements.
95    In plotters, all the elements can be converted into `DynElement`, the dynamic dispatch container for
96    all elements (include exernal implemented ones).
97    Plotters automatically implements `IntoDynElement` for all elements, by doing so, any dynamic element should have
98    `into_dyn` function which would wrap the element into a dynmanic element wrapper.
99
100    For example, the following code counts the number of factors of integer and mark all prime numbers in cross.
101    ```rust
102    use plotters::prelude::*;
103    fn num_of_factor(n: i32) -> i32 {
104        let mut ret = 2;
105        for i in 2..n {
106            if i * i > n {
107                break;
108            }
109
110            if n % i == 0 {
111                if i * i != n {
112                    ret += 2;
113                } else {
114                    ret += 1;
115                }
116            }
117        }
118        return ret;
119    }
120    fn main() -> Result<(), Box<dyn std::error::Error>> {
121        let root =
122            BitMapBackend::new("examples/outputs/element-3.png", (640, 480))
123            .into_drawing_area();
124        root.fill(&White)?;
125        let mut chart = ChartBuilder::on(&root)
126            .x_label_area_size(40)
127            .y_label_area_size(40)
128            .margin(5)
129            .build_ranged(0..50, 0..10)?;
130
131        chart
132            .configure_mesh()
133            .disable_x_mesh()
134            .disable_y_mesh()
135            .draw()?;
136
137        chart.draw_series((0..50).map(|x| {
138            let center = (x, num_of_factor(x));
139            // Although the arms of if statement has different types,
140            // but they can be placed into a dynamic element wrapper,
141            // by doing so, the type is unified.
142            if center.1 == 2 {
143                Cross::new(center, 4, Into::<ShapeStyle>::into(&Red).filled()).into_dyn()
144            } else {
145                Circle::new(center, 4, Into::<ShapeStyle>::into(&Green).filled()).into_dyn()
146            }
147        }))?;
148
149        Ok(())
150    }
151    ```
152    ![](https://raw.githubusercontent.com/38/plotters/master/examples/outputs/element-3.png)
153*/
154use crate::drawing::backend::{BackendCoord, DrawingBackend, DrawingErrorKind};
155use std::borrow::Borrow;
156
157mod basic_shapes;
158pub use basic_shapes::*;
159
160mod text;
161pub use text::*;
162
163mod points;
164pub use points::*;
165
166mod composable;
167pub use composable::{ComposedElement, EmptyElement};
168
169mod candlestick;
170pub use candlestick::CandleStick;
171
172/// A type which is logically a collection of points, under any given coordinate system
173pub trait PointCollection<'a, Coord> {
174    /// The item in point iterator
175    type Borrow: Borrow<Coord>;
176
177    /// The point iterator
178    type IntoIter: IntoIterator<Item = Self::Borrow>;
179
180    /// framework to do the coordinate mapping
181    fn point_iter(self) -> Self::IntoIter;
182}
183
184/// The trait indicates we are able to draw it on a drawing area
185pub trait Drawable<DB: DrawingBackend> {
186    /// Actually draws the element. The key points is already translated into the
187    /// image cooridnate and can be used by DC directly
188    fn draw<I: Iterator<Item = BackendCoord>>(
189        &self,
190        pos: I,
191        backend: &mut DB,
192    ) -> Result<(), DrawingErrorKind<DB::ErrorType>>;
193}
194
195trait DynDrawable<DB: DrawingBackend> {
196    fn draw_dyn(
197        &self,
198        points: &mut Iterator<Item = BackendCoord>,
199        backend: &mut DB,
200    ) -> Result<(), DrawingErrorKind<DB::ErrorType>>;
201}
202
203impl<DB: DrawingBackend, T: Drawable<DB>> DynDrawable<DB> for T {
204    fn draw_dyn(
205        &self,
206        points: &mut Iterator<Item = BackendCoord>,
207        backend: &mut DB,
208    ) -> Result<(), DrawingErrorKind<DB::ErrorType>> {
209        T::draw(self, points, backend)
210    }
211}
212
213/// The container for a dynamically dispatched element
214pub struct DynElement<DB, Coord>
215where
216    DB: DrawingBackend,
217    Coord: Clone,
218{
219    points: Vec<Coord>,
220    drawable: Box<dyn DynDrawable<DB>>,
221}
222
223impl<'a, DB: DrawingBackend, Coord: Clone> PointCollection<'a, Coord>
224    for &'a DynElement<DB, Coord>
225{
226    type Borrow = &'a Coord;
227    type IntoIter = std::slice::Iter<'a, Coord>;
228    fn point_iter(self) -> Self::IntoIter {
229        self.points.iter()
230    }
231}
232
233impl<DB: DrawingBackend, Coord: Clone> Drawable<DB> for DynElement<DB, Coord> {
234    fn draw<I: Iterator<Item = BackendCoord>>(
235        &self,
236        mut pos: I,
237        backend: &mut DB,
238    ) -> Result<(), DrawingErrorKind<DB::ErrorType>> {
239        self.drawable.draw_dyn(&mut pos, backend)
240    }
241}
242
243/// The trait that makes the conversion from the statically dispatched element
244/// to the dynamically dispatched element
245pub trait IntoDynElement<DB: DrawingBackend, Coord: Clone> {
246    /// Make the conversion
247    fn into_dyn(self) -> DynElement<DB, Coord>;
248}
249
250impl<T, DB, Coord> IntoDynElement<DB, Coord> for T
251where
252    T: Drawable<DB> + 'static,
253    for<'a> &'a T: PointCollection<'a, Coord>,
254    Coord: Clone,
255    DB: DrawingBackend,
256{
257    fn into_dyn(self) -> DynElement<DB, Coord> {
258        DynElement {
259            points: self
260                .point_iter()
261                .into_iter()
262                .map(|x| x.borrow().clone())
263                .collect(),
264            drawable: Box::new(self),
265        }
266    }
267}