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
use std::{
fmt::Debug,
sync::{Arc, Weak},
time::Duration,
};
use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};
use crate::{AnyFrontend, AnySendSync, Callback};
#[derive(Debug, Clone)]
#[must_use]
pub struct Timer {
native: Arc<Mutex<dyn NativeTimer>>,
}
#[derive(Debug, Clone)]
#[must_use]
pub struct WeakTimer(Weak<Mutex<dyn NativeTimer>>);
impl WeakTimer {
#[must_use]
pub fn upgrade(&self) -> Option<Timer> {
self.0.upgrade().map(|native| Timer { native })
}
}
impl Timer {
pub fn from_native<N: NativeTimer>(native: N) -> Self {
Self {
native: Arc::new(Mutex::new(native)),
}
}
#[must_use]
pub fn native<N: NativeTimer>(&self) -> Option<MappedMutexGuard<'_, N>> {
let guard = self.native.lock();
MutexGuard::try_map(guard, |native| native.as_mut_any().downcast_mut()).ok()
}
pub fn downgrade(&self) -> WeakTimer {
WeakTimer(Arc::downgrade(&self.native))
}
}
pub trait NativeTimer: AnySendSync {}
#[must_use]
#[derive(Debug, Clone)]
pub struct UnscheduledTimer<'a> {
frontend: &'a dyn AnyFrontend,
callback: Callback,
period: Duration,
repeating: bool,
}
impl<'a> UnscheduledTimer<'a> {
pub(crate) fn new(period: Duration, callback: Callback, frontend: &'a dyn AnyFrontend) -> Self {
Self {
frontend,
callback,
period,
repeating: false,
}
}
pub fn repeating(mut self) -> Self {
self.repeating = true;
self
}
pub fn schedule(self) -> Timer {
self.frontend
.schedule_timer(self.callback, self.period, self.repeating)
}
}