-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathplotter.rs
More file actions
81 lines (68 loc) · 2.46 KB
/
plotter.rs
File metadata and controls
81 lines (68 loc) · 2.46 KB
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
//! **plotter** provides the `Plotter` object which handles plot creation and lifecycles
//!
//! Each plot runs asynchronously in a background thread. A `Plotter` creates and tracks these background threads.
//!
//! For now, `Plotter::plot2d` is the only supported plotting function. It takes a `PlotBuilder2D` containing all needed information.
//!
//! The `Plotter::join` function allows the thread that owns the `Plotter` to wait until the user has closed all open plot windows before continuing.
use std::thread;
use plotbuilder::PlotBuilder2D;
use plot::Plot;
use draw;
pub struct Plotter {
plots: Vec<thread::JoinHandle<()>>,
}
impl Plotter {
/// `new` creates a new `Plotter` object to manage asynchronous plots
pub fn new() -> Plotter {
Plotter { plots: Vec::new() }
}
/// `plot2d` is currently the only supported plotting function. It takes a `PlotBuilder2D` containing all needed information.
pub fn plot2d(&mut self, plotbuilder: PlotBuilder2D, drawable: Box<draw::Drawable>) {
self.plots.push(thread::spawn(
move || { Plot::new2d(plotbuilder, drawable); },
));
}
/// The `disown` function allows the thread that owns the `Plotter` to keep going without either `join`ing manually or letting the `Drop` trait force a `join`.
pub fn disown(self) {
::std::mem::forget(self);
}
/// The `join` function allows the thread that owns the `Plotter` to wait until the user has closed all open plot windows before continuing.
pub fn join(mut self) {
self._join();
}
/// The internal version of `join` that only really takes a mutable reference to allow `join`ing during `Drop`.
fn _join(&mut self) {
let mut plots = vec![];
::std::mem::swap(&mut self.plots, &mut plots);
for t in plots {
let _ = t.join();
}
}
}
impl Drop for Plotter {
fn drop(&mut self) {
self._join();
}
}
#[cfg(test)]
mod test {
use super::*;
use plotbuilder::*;
use util::*;
use draw_sdl::DrawSDL;
use sdl2_mt;
#[test]
fn plot2d_test() {
let x = linspace(0, 10, 100);
let y = (&x).iter().map(|x| x.sin()).collect();
let xy = zip2(&x, &y);
let sdlh = sdl2_mt::init();
let sdl2_window = DrawSDL::new(sdlh);
let mut pb1 = PlotBuilder2D::new();
pb1.add_simple_xy(xy);
let mut plt = Plotter::new();
plt.plot2d(pb1, sdl2_window);
plt.disown();
}
}