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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use crate::render::callbacks::CallbackRegistry;
use crate::render::widget::*;
use crate::render::widget_cache::WidgetContainer;
use crate::render::widget_config::WidgetConfig;
use crate::render::layout_cache::LayoutContainer;
use crate::render::{make_points_origin, make_size};
use std::any::Any;
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
pub type TimerCallbackType =
Option<Box<dyn FnMut(&mut TimerWidget, &[WidgetContainer], &[LayoutContainer])>>;
fn time_ms() -> u64 {
let since_the_epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
(since_the_epoch.as_secs() * 1_000) + u64::from(since_the_epoch.subsec_millis())
}
pub struct TimerWidget {
config: WidgetConfig,
system_properties: HashMap<i32, String>,
callback_registry: CallbackRegistry,
enabled: bool,
timeout: u64,
initiated: u64,
on_timeout: TimerCallbackType,
}
impl TimerWidget {
pub fn new(timeout: u64, enabled: bool) -> Self {
Self {
config: WidgetConfig::new(make_points_origin(), make_size(0, 0)),
system_properties: HashMap::new(),
callback_registry: CallbackRegistry::new(),
enabled,
timeout,
initiated: time_ms(),
on_timeout: None,
}
}
pub fn enable(&mut self) {
self.initiated = time_ms();
self.enabled = true;
}
pub fn disable(&mut self) {
self.enabled = false;
}
pub fn is_enabled(&self) -> bool {
self.enabled
}
pub fn on_timeout<F>(&mut self, callback: F)
where
F: FnMut(&mut TimerWidget, &[WidgetContainer], &[LayoutContainer]) + 'static,
{
self.on_timeout = Some(Box::new(callback));
}
fn call_timeout_callback(&mut self, widgets: &[WidgetContainer], layouts: &[LayoutContainer]) {
if let Some(mut cb) = self.on_timeout.take() {
cb(self, widgets, layouts);
self.on_timeout = Some(cb);
}
}
}
impl Widget for TimerWidget {
fn tick(&mut self, _widgets: &[WidgetContainer], _layouts: &[LayoutContainer]) {
if !self.enabled {
return;
}
let elapsed = time_ms() - self.initiated;
if elapsed > self.timeout {
self.initiated = time_ms();
self.call_timeout_callback(_widgets, _layouts);
}
}
default_widget_functions!();
default_widget_properties!();
}