-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstopwatch.rs
66 lines (60 loc) · 1.88 KB
/
stopwatch.rs
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
use narui::*;
use std::{
sync::mpsc::RecvTimeoutError,
time::{Duration, SystemTime},
};
#[derive(Clone)]
enum Message {
Stop,
ButtonClick,
}
#[widget]
pub fn stopwatch(#[default(100.)] font_size: f32, context: &mut WidgetContext) -> Fragment {
let time = context.listenable(0.0);
let button_text = context.listenable("start");
let thread_handle = context.thread(
move |context, rx| loop {
match rx.recv().unwrap() {
Message::Stop => return,
Message::ButtonClick => {}
}
context.shout(button_text, "stop");
let start = SystemTime::now();
loop {
let now = SystemTime::now();
context.shout(time, now.duration_since(start).unwrap().as_secs_f32());
match rx.recv_timeout(Duration::from_secs_f32(1. / 100.)) {
Ok(Message::Stop) => return,
Ok(Message::ButtonClick) => break,
Err(RecvTimeoutError::Timeout) => {}
_ => panic!(),
}
}
context.shout(button_text, "reset");
match rx.recv().unwrap() {
Message::Stop => return,
Message::ButtonClick => {}
}
context.shout(time, 0.0);
},
Message::Stop,
(),
);
rsx! {
<column>
<text size=font_size>{format!("{:.2}", context.listen(time))}</text>
<button on_click=move |_context: &CallbackContext| { thread_handle.read().send(Message::ButtonClick).unwrap(); }>
<text>{context.listen(button_text)}</text>
</button>
</column>
}
}
fn main() {
env_logger::init();
app::render(
app::WindowBuilder::new().with_title("narui stopwatch demo"),
rsx_toplevel! {
<stopwatch />
},
);
}