1use std::cell::RefCell;
5use std::collections::BTreeMap;
6use std::marker::PhantomData;
7use std::panic::{self, AssertUnwindSafe, Location};
8use std::rc::Rc;
9use std::time::{Duration, Instant};
10
11use crabshell_reactive::{Owner, Signal, untrack};
12
13use crate::cx::Cx;
14use crate::input::panic_message;
15
16const MIN_PERIOD: Duration = Duration::from_millis(1);
18const MAX_PERIOD: Duration = Duration::from_secs(u32::MAX as u64);
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub struct Timer {
26 id: u64,
27 _not_send: PhantomData<*const ()>,
29}
30
31struct Entry {
32 owner: Owner,
33 label: Rc<str>,
35 period: Duration,
36 repeats: bool,
37 deadline: Option<Instant>,
39 running: Signal<bool>,
41 callback: Option<Box<dyn FnMut()>>,
43}
44
45thread_local! {
46 static TIMERS: RefCell<(u64, BTreeMap<u64, Entry>)> = const { RefCell::new((0, BTreeMap::new())) };
48}
49
50impl Cx {
51 #[track_caller]
66 pub fn after(&self, delay: Duration, f: impl FnMut() + 'static) -> Timer {
67 let label = format!("cx.after at {}", Location::caller());
68 add(self, label, delay.min(MAX_PERIOD), false, Box::new(f))
69 }
70
71 #[track_caller]
76 pub fn interval(&self, period: Duration, f: impl FnMut() + 'static) -> Timer {
77 let label = format!("cx.interval at {}", Location::caller());
78 let period = period.clamp(MIN_PERIOD, MAX_PERIOD);
79 add(self, label, period, true, Box::new(f))
80 }
81}
82
83fn add(cx: &Cx, label: String, period: Duration, repeats: bool, f: Box<dyn FnMut()>) -> Timer {
84 let running = cx.signal(true);
85 let entry = Entry {
86 owner: cx.owner(),
87 label: label.into(),
88 period,
89 repeats,
90 deadline: Some(Instant::now() + period),
91 running,
92 callback: Some(f),
93 };
94 let id = TIMERS.with(|timers| {
95 let (next, table) = &mut *timers.borrow_mut();
96 *next += 1;
97 table.insert(*next, entry);
98 *next
99 });
100 Timer {
101 id,
102 _not_send: PhantomData,
103 }
104}
105
106impl Timer {
107 pub fn stop(&self) {
109 self.set_deadline(|_| None);
110 }
111
112 pub fn stopped(self) -> Timer {
115 self.stop();
116 self
117 }
118
119 pub fn restart(&self) {
123 self.set_deadline(|period| Some(Instant::now() + period));
124 }
125
126 pub fn running(&self) -> bool {
129 let running = TIMERS.with(|timers| timers.borrow().1.get(&self.id).map(|entry| entry.running));
130 running
131 .and_then(|running| running.try_get())
132 .unwrap_or(false)
133 }
134
135 fn set_deadline(&self, deadline: impl FnOnce(Duration) -> Option<Instant>) {
136 let changed = TIMERS.with(|timers| {
137 let mut timers = timers.borrow_mut();
138 let entry = timers.1.get_mut(&self.id)?;
139 if entry.owner.is_disposed() {
140 return None;
141 }
142 entry.deadline = deadline(entry.period);
143 Some((entry.running, entry.deadline.is_some()))
144 });
145 if let Some((signal, running)) = changed {
146 set_running(signal, running);
147 }
148 }
149}
150
151fn set_running(signal: Signal<bool>, running: bool) {
154 if untrack(|| signal.try_with(|&was| was != running)) == Some(true) {
155 signal.try_set(running);
156 }
157}
158
159pub fn next_timer() -> Option<Instant> {
163 sweep();
164 TIMERS.with(|timers| {
165 let timers = timers.borrow();
166 timers.1.values().filter_map(|entry| entry.deadline).min()
167 })
168}
169
170pub fn fire_timers(now: Instant) {
174 sweep();
175 let mut due: Vec<(Instant, u64)> = TIMERS.with(|timers| {
176 let timers = timers.borrow();
177 let due = timers.1.iter().filter_map(|(&id, entry)| {
178 let deadline = entry.deadline.filter(|&deadline| deadline <= now)?;
179 Some((deadline, id))
180 });
181 due.collect()
182 });
183 due.sort_unstable();
184 for (_, id) in due {
185 fire(id, now);
186 }
187}
188
189fn fire(id: u64, now: Instant) {
190 let taken = TIMERS.with(|timers| {
193 let mut timers = timers.borrow_mut();
194 let entry = timers.1.get_mut(&id)?;
195 let deadline = entry.deadline.filter(|&deadline| deadline <= now)?;
198 if entry.owner.is_disposed() {
199 return None;
200 }
201 let callback = entry.callback.take()?;
202 entry.deadline = entry.repeats.then(|| {
203 let next = deadline + entry.period;
204 if next > now { next } else { now + entry.period }
205 });
206 let entry = &*entry;
207 Some((
208 callback,
209 Rc::clone(&entry.label),
210 entry.owner,
211 entry.running,
212 entry.deadline.is_some(),
213 ))
214 });
215 let Some((mut callback, label, owner, running, again)) = taken else {
216 return;
217 };
218 if !again {
219 set_running(running, false);
220 }
221 let panicked = panic::catch_unwind(AssertUnwindSafe(&mut callback)).err();
222 if let Some(payload) = &panicked {
223 let place = owner
224 .name()
225 .map(|name| format!(" in {name}"))
226 .unwrap_or_default();
227 tracing::error!(
228 "timer {label}{place} panicked and stops: {}",
229 panic_message(payload.as_ref())
230 );
231 }
232 let orphan = TIMERS.with(|timers| {
233 let mut timers = timers.borrow_mut();
234 let Some(entry) = timers.1.get_mut(&id) else {
235 return Some(callback);
236 };
237 if panicked.is_some() {
238 entry.deadline = None;
239 }
240 entry.callback = Some(callback);
241 None
242 });
243 if panicked.is_some() {
244 set_running(running, false);
245 }
246 if let Some(callback) = orphan {
248 drop_isolated(&label, callback);
249 }
250}
251
252fn sweep() {
255 let gone: Vec<Entry> = TIMERS.with(|timers| {
256 let mut timers = timers.borrow_mut();
257 let ids: Vec<u64> = timers
258 .1
259 .iter()
260 .filter(|(_, entry)| entry.owner.is_disposed())
261 .map(|(&id, _)| id)
262 .collect();
263 ids.iter().filter_map(|id| timers.1.remove(id)).collect()
264 });
265 for entry in gone {
266 if let Some(callback) = entry.callback {
267 drop_isolated(&entry.label, callback);
268 }
269 }
270}
271
272fn drop_isolated(label: &str, callback: Box<dyn FnMut()>) {
274 if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(callback))) {
275 tracing::error!(
276 "dropping timer {label} panicked: {}",
277 panic_message(payload.as_ref())
278 );
279 }
280}