Debian Codegraph @

helix-event/src/debounce.rs

raw symbols SCIP
1 //! Utilities for declaring an async (usually debounced) hook
2
3 use std::time::Duration;
4
5 use futures_executor::block_on;
6 use tokio::sync::mpsc::{self, error::TrySendError, Sender};
7 use tokio::time::Instant;
8
9 /// Async hooks provide a convenient framework for implementing (debounced)
10 /// async event handlers. Most synchronous event hooks will likely need to
11 /// debounce their events, coordinate multiple different hooks and potentially
12 /// track some state. `AsyncHooks` facilitate these use cases by running as
13 /// a background tokio task that waits for events (usually an enum) to be
14 /// sent through a channel.
15 pub trait AsyncHook: Sync + Send + 'static + Sized {
16 type Event: Sync + Send + 'static;
17 /// Called immediately whenever an event is received, this function can
18 /// consume the event immediately or debounce it. In case of debouncing,
19 /// it can either define a new debounce timeout or continue the current one
20 fn handle_event(&mut self, event: Self::Event, timeout: Option<Instant>) -> Option<Instant>;
21
22 /// Called whenever the debounce timeline is reached
23 fn finish_debounce(&mut self);
24
25 fn spawn(self) -> mpsc::Sender<Self::Event> {
26 // the capacity doesn't matter too much here, unless the cpu is totally overwhelmed
27 // the cap will never be reached since we always immediately drain the channel
28 // so it should only be reached in case of total CPU overload.
29 // However, a bounded channel is much more efficient so it's nice to use here
30 let (tx, rx) = mpsc::channel(128);
31 // only spawn worker if we are inside runtime to avoid having to spawn a runtime for unrelated unit tests
32 if tokio::runtime::Handle::try_current().is_ok() {
33 tokio::spawn(run(self, rx));
34 }
35 tx
36 }
37 }
38
39 async fn run<Hook: AsyncHook>(mut hook: Hook, mut rx: mpsc::Receiver<Hook::Event>) {
40 let mut deadline = None;
41 loop {
42 let event = match deadline {
43 Some(deadline_) => {
44 let res = tokio::time::timeout_at(deadline_, rx.recv()).await;
45 match res {
46 Ok(event) => event,
47 Err(_) => {
48 hook.finish_debounce();
49 deadline = None;
50 continue;
51 }
52 }
53 }
54 None => rx.recv().await,
55 };
56 let Some(event) = event else {
57 break;
58 };
59 deadline = hook.handle_event(event, deadline);
60 }
61 }
62
63 pub fn send_blocking<T>(tx: &Sender<T>, data: T) {
64 // block_on has some overhead and in practice the channel should basically
65 // never be full anyway so first try sending without blocking
66 if let Err(TrySendError::Full(data)) = tx.try_send(data) {
67 // set a timeout so that we just drop a message instead of freezing the editor in the worst case
68 let _ = block_on(tx.send_timeout(data, Duration::from_millis(10)));
69 }
70 }