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
// Pushrod Widget Library
// Timer Widget
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

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};

/// This is the callback type that is used when an `on_timeout` callback is triggered from this
/// `Widget`.
pub type TimerCallbackType =
    Option<Box<dyn FnMut(&mut TimerWidget, &[WidgetContainer], &[LayoutContainer])>>;

/// Private function used to return the current time in milliseconds.
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())
}

/// This is the storage object for the `TimerWidget`.  It stores the config, properties, callback registry,
/// an enabled flag, timeout, a last-time-triggered value, and a timeout callback store.
pub struct TimerWidget {
    config: WidgetConfig,
    system_properties: HashMap<i32, String>,
    callback_registry: CallbackRegistry,
    enabled: bool,
    timeout: u64,
    initiated: u64,
    on_timeout: TimerCallbackType,
}

/// Creates a new `TimerWidget`.  This `Widget` will call a function defined in `on_timeout` when
/// a specific number of milliseconds has elapsed.
impl TimerWidget {
    /// Creates a new `TimerWidget` object to call the `on_timeout` timeout callback every `timeout`
    /// milliseconds.  Setting `enabled` to `true` will automatically enable the timer, where as
    /// `false` will add the timer, but it will not be enabled.
    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,
        }
    }

    /// Re-enables the timer.  This will also reset the elapsed timer.
    pub fn enable(&mut self) {
        self.initiated = time_ms();
        self.enabled = true;
    }

    /// Disables the timer.  Once disabled, the `on_timeout` callback will never be called.
    pub fn disable(&mut self) {
        self.enabled = false;
    }

    /// Returns the `enabled` state.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Assigns the callback closure that will be used when a timer tick is triggered.
    pub fn on_timeout<F>(&mut self, callback: F)
    where
        F: FnMut(&mut TimerWidget, &[WidgetContainer], &[LayoutContainer]) + 'static,
    {
        self.on_timeout = Some(Box::new(callback));
    }

    /// Internal function that triggers the `on_timeout` 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);
        }
    }
}

/// This is the `Widget` implementation of the `TimerWidget`.
impl Widget for TimerWidget {
    /// The `TimerWidget` responds to the `tick` callback, which is used to determine the timer
    /// display ticks.  This function is _only_ called when the timer tick occurs, so if there is a
    /// function inside the drawing loop that drops frames, this timer may not get called reliably.
    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!();
}