Skip to main content

crabshell_ui/
timer.rs

1//! Timers: callbacks that run once after a delay or again every period,
2//! from a table the platform wakes for only while a timer runs.
3
4use 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
16/// The shortest interval, so a period of 0 can't spin the loop.
17const MIN_PERIOD: Duration = Duration::from_millis(1);
18/// The longest delay or period, so adding it to now can't overflow.
19const MAX_PERIOD: Duration = Duration::from_secs(u32::MAX as u64);
20
21/// A timer made by [`Cx::after`] or [`Cx::interval`]. It is a `Copy`
22/// handle, like a signal, so closures capture it without cloning. Calls on
23/// a timer whose context is gone do nothing.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub struct Timer {
26  id: u64,
27  /// The table is per thread, like the reactive runtime.
28  _not_send: PhantomData<*const ()>,
29}
30
31struct Entry {
32  owner: Owner,
33  /// Names the timer in log lines, as `cx.after at src/main.rs:12`.
34  label: Rc<str>,
35  period: Duration,
36  repeats: bool,
37  /// When it fires next. `None` while stopped.
38  deadline: Option<Instant>,
39  /// Whether it is running, for bindings to read.
40  running: Signal<bool>,
41  /// `None` while the callback runs.
42  callback: Option<Box<dyn FnMut()>>,
43}
44
45thread_local! {
46  /// Ids are never reused, so a stale handle never reaches a newer timer.
47  static TIMERS: RefCell<(u64, BTreeMap<u64, Entry>)> = const { RefCell::new((0, BTreeMap::new())) };
48}
49
50impl Cx {
51  /// Runs `f` once, `delay` from now. The timer belongs to this context
52  /// and goes with it; [`Timer::restart`] runs it again.
53  ///
54  /// ```
55  /// use std::time::Duration;
56  /// use crabshell_ui::Cx;
57  ///
58  /// fn osd(cx: &Cx) {
59  ///     let hide = cx.after(Duration::from_millis(1500), || {}).stopped();
60  ///     // Show the OSD while `hide.running()`, and call `hide.restart()`
61  ///     // on each change.
62  /// #   let _ = hide;
63  /// }
64  /// ```
65  #[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  /// Runs `f` every `period`, the first time `period` from now. A late
72  /// wakeup fires once and keeps the schedule; after a stall longer than
73  /// a period the next fire is a period from then, never a burst. The
74  /// timer belongs to this context and goes with it.
75  #[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  /// Stops the timer before it fires again.
108  pub fn stop(&self) {
109    self.set_deadline(|_| None);
110  }
111
112  /// The timer, stopped before it ever fires, so it waits for its first
113  /// [`restart`](Self::restart): `cx.after(delay, f).stopped()`.
114  pub fn stopped(self) -> Timer {
115    self.stop();
116    self
117  }
118
119  /// Counts the delay or period again from now, so a timer restarted on
120  /// every change fires only once the changes stop. It also starts a
121  /// one-shot that fired or was stopped.
122  pub fn restart(&self) {
123    self.set_deadline(|period| Some(Instant::now() + period));
124  }
125
126  /// Whether the timer will fire. Read in a binding, it reruns the binding
127  /// when that changes.
128  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
151/// Writes `running` only when it changes, since a signal notifies on
152/// every write.
153fn 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
159/// When the earliest running timer, or animation asleep in a pause, is
160/// due, for the platform to wake then. `None` means none runs and nothing
161/// needs waking. Timers and animations whose context is gone are freed
162/// first, so they never wake the loop.
163pub fn next_timer() -> Option<Instant> {
164  sweep();
165  let timer = TIMERS.with(|timers| {
166    let timers = timers.borrow();
167    timers.1.values().filter_map(|entry| entry.deadline).min()
168  });
169  timer.into_iter().chain(crate::animation::next_wake()).min()
170}
171
172/// Runs every timer due at `now`, earliest first, and puts the animations
173/// whose pause has ended back on the animation clock. A timer started
174/// while they run first fires at a later call. One whose callback panics
175/// is logged and stops; the others still fire.
176pub fn fire_timers(now: Instant) {
177  crate::animation::wake(now);
178  sweep();
179  let mut due: Vec<(Instant, u64)> = TIMERS.with(|timers| {
180    let timers = timers.borrow();
181    let due = timers.1.iter().filter_map(|(&id, entry)| {
182      let deadline = entry.deadline.filter(|&deadline| deadline <= now)?;
183      Some((deadline, id))
184    });
185    due.collect()
186  });
187  due.sort_unstable();
188  for (_, id) in due {
189    fire(id, now);
190  }
191}
192
193fn fire(id: u64, now: Instant) {
194  // The callback runs with the table released, so it may start, stop or
195  // restart any timer, itself included.
196  let taken = TIMERS.with(|timers| {
197    let mut timers = timers.borrow_mut();
198    let entry = timers.1.get_mut(&id)?;
199    // An earlier callback may have stopped it, restarted it or dropped
200    // its context.
201    let deadline = entry.deadline.filter(|&deadline| deadline <= now)?;
202    if entry.owner.is_disposed() {
203      return None;
204    }
205    let callback = entry.callback.take()?;
206    entry.deadline = entry.repeats.then(|| {
207      let next = deadline + entry.period;
208      if next > now { next } else { now + entry.period }
209    });
210    let entry = &*entry;
211    Some((
212      callback,
213      Rc::clone(&entry.label),
214      entry.owner,
215      entry.running,
216      entry.deadline.is_some(),
217    ))
218  });
219  let Some((mut callback, label, owner, running, again)) = taken else {
220    return;
221  };
222  if !again {
223    set_running(running, false);
224  }
225  let panicked = panic::catch_unwind(AssertUnwindSafe(&mut callback)).err();
226  if let Some(payload) = &panicked {
227    let place = owner
228      .name()
229      .map(|name| format!(" in {name}"))
230      .unwrap_or_default();
231    tracing::error!(
232      "timer {label}{place} panicked and stops: {}",
233      panic_message(payload.as_ref())
234    );
235  }
236  let orphan = TIMERS.with(|timers| {
237    let mut timers = timers.borrow_mut();
238    let Some(entry) = timers.1.get_mut(&id) else {
239      return Some(callback);
240    };
241    if panicked.is_some() {
242      entry.deadline = None;
243    }
244    entry.callback = Some(callback);
245    None
246  });
247  if panicked.is_some() {
248    set_running(running, false);
249  }
250  // Freed while it ran, by a sweep inside it.
251  if let Some(callback) = orphan {
252    drop_isolated(&label, callback);
253  }
254}
255
256/// Frees the timers whose context is gone, dropping their callbacks with
257/// the table released.
258fn sweep() {
259  let gone: Vec<Entry> = TIMERS.with(|timers| {
260    let mut timers = timers.borrow_mut();
261    let ids: Vec<u64> = timers
262      .1
263      .iter()
264      .filter(|(_, entry)| entry.owner.is_disposed())
265      .map(|(&id, _)| id)
266      .collect();
267    ids.iter().filter_map(|id| timers.1.remove(id)).collect()
268  });
269  for entry in gone {
270    if let Some(callback) = entry.callback {
271      drop_isolated(&entry.label, callback);
272    }
273  }
274}
275
276/// Drops a callback, and the user's values it holds, isolated.
277fn drop_isolated(label: &str, callback: Box<dyn FnMut()>) {
278  if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(move || drop(callback))) {
279    tracing::error!(
280      "dropping timer {label} panicked: {}",
281      panic_message(payload.as_ref())
282    );
283  }
284}