pushrod/widgets/
timer_widget.rs

1// Pushrod Widget Library
2// Timer Widget
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::render::callbacks::CallbackRegistry;
17use crate::render::widget::*;
18use crate::render::widget_cache::WidgetContainer;
19use crate::render::widget_config::WidgetConfig;
20
21use crate::render::layout_cache::LayoutContainer;
22use crate::render::{make_points_origin, make_size};
23use std::any::Any;
24use std::collections::HashMap;
25use std::time::{SystemTime, UNIX_EPOCH};
26
27/// This is the callback type that is used when an `on_timeout` callback is triggered from this
28/// `Widget`.
29pub type TimerCallbackType =
30    Option<Box<dyn FnMut(&mut TimerWidget, &[WidgetContainer], &[LayoutContainer])>>;
31
32/// Private function used to return the current time in milliseconds.
33fn time_ms() -> u64 {
34    let since_the_epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
35
36    (since_the_epoch.as_secs() * 1_000) + u64::from(since_the_epoch.subsec_millis())
37}
38
39/// This is the storage object for the `TimerWidget`.  It stores the config, properties, callback registry,
40/// an enabled flag, timeout, a last-time-triggered value, and a timeout callback store.
41pub struct TimerWidget {
42    config: WidgetConfig,
43    system_properties: HashMap<i32, String>,
44    callback_registry: CallbackRegistry,
45    enabled: bool,
46    timeout: u64,
47    initiated: u64,
48    on_timeout: TimerCallbackType,
49}
50
51/// Creates a new `TimerWidget`.  This `Widget` will call a function defined in `on_timeout` when
52/// a specific number of milliseconds has elapsed.
53impl TimerWidget {
54    /// Creates a new `TimerWidget` object to call the `on_timeout` timeout callback every `timeout`
55    /// milliseconds.  Setting `enabled` to `true` will automatically enable the timer, where as
56    /// `false` will add the timer, but it will not be enabled.
57    pub fn new(timeout: u64, enabled: bool) -> Self {
58        Self {
59            config: WidgetConfig::new(make_points_origin(), make_size(0, 0)),
60            system_properties: HashMap::new(),
61            callback_registry: CallbackRegistry::new(),
62            enabled,
63            timeout,
64            initiated: time_ms(),
65            on_timeout: None,
66        }
67    }
68
69    /// Re-enables the timer.  This will also reset the elapsed timer.
70    pub fn enable(&mut self) {
71        self.initiated = time_ms();
72        self.enabled = true;
73    }
74
75    /// Disables the timer.  Once disabled, the `on_timeout` callback will never be called.
76    pub fn disable(&mut self) {
77        self.enabled = false;
78    }
79
80    /// Returns the `enabled` state.
81    pub fn is_enabled(&self) -> bool {
82        self.enabled
83    }
84
85    /// Assigns the callback closure that will be used when a timer tick is triggered.
86    pub fn on_timeout<F>(&mut self, callback: F)
87    where
88        F: FnMut(&mut TimerWidget, &[WidgetContainer], &[LayoutContainer]) + 'static,
89    {
90        self.on_timeout = Some(Box::new(callback));
91    }
92
93    /// Internal function that triggers the `on_timeout` callback.
94    fn call_timeout_callback(&mut self, widgets: &[WidgetContainer], layouts: &[LayoutContainer]) {
95        if let Some(mut cb) = self.on_timeout.take() {
96            cb(self, widgets, layouts);
97            self.on_timeout = Some(cb);
98        }
99    }
100}
101
102/// This is the `Widget` implementation of the `TimerWidget`.
103impl Widget for TimerWidget {
104    /// The `TimerWidget` responds to the `tick` callback, which is used to determine the timer
105    /// display ticks.  This function is _only_ called when the timer tick occurs, so if there is a
106    /// function inside the drawing loop that drops frames, this timer may not get called reliably.
107    fn tick(&mut self, _widgets: &[WidgetContainer], _layouts: &[LayoutContainer]) {
108        if !self.enabled {
109            return;
110        }
111
112        let elapsed = time_ms() - self.initiated;
113
114        if elapsed > self.timeout {
115            self.initiated = time_ms();
116            self.call_timeout_callback(_widgets, _layouts);
117        }
118    }
119
120    default_widget_functions!();
121    default_widget_properties!();
122}