Debian Codegraph @

helix-term/src/ui/picker/handlers.rs

raw symbols SCIP
1 use std::{
2 path::Path,
3 sync::{atomic, Arc},
4 time::Duration,
5 };
6
7 use helix_event::AsyncHook;
8 use tokio::time::Instant;
9
10 use crate::{job, ui::overlay::Overlay};
11
12 use super::{CachedPreview, DynQueryCallback, Picker};
13
14 pub(super) struct PreviewHighlightHandler<T: 'static + Send + Sync, D: 'static + Send + Sync> {
15 trigger: Option<Arc<Path>>,
16 phantom_data: std::marker::PhantomData<(T, D)>,
17 }
18
19 impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Default for PreviewHighlightHandler<T, D> {
20 fn default() -> Self {
21 Self {
22 trigger: None,
23 phantom_data: Default::default(),
24 }
25 }
26 }
27
28 impl<T: 'static + Send + Sync, D: 'static + Send + Sync> AsyncHook
29 for PreviewHighlightHandler<T, D>
30 {
31 type Event = Arc<Path>;
32
33 fn handle_event(
34 &mut self,
35 path: Self::Event,
36 timeout: Option<tokio::time::Instant>,
37 ) -> Option<tokio::time::Instant> {
38 if self
39 .trigger
40 .as_ref()
41 .is_some_and(|trigger| trigger == &path)
42 {
43 // If the path hasn't changed, don't reset the debounce
44 timeout
45 } else {
46 self.trigger = Some(path);
47 Some(Instant::now() + Duration::from_millis(150))
48 }
49 }
50
51 fn finish_debounce(&mut self) {
52 let Some(path) = self.trigger.take() else {
53 return;
54 };
55
56 job::dispatch_blocking(move |editor, compositor| {
57 let Some(Overlay {
58 content: picker, ..
59 }) = compositor.find::<Overlay<Picker<T, D>>>()
60 else {
61 return;
62 };
63
64 let Some(CachedPreview::Document(ref mut doc)) = picker.preview_cache.get_mut(&path)
65 else {
66 return;
67 };
68
69 if doc.syntax().is_some() {
70 return;
71 }
72
73 let Some(language) = doc.language_config().map(|config| config.language()) else {
74 return;
75 };
76
77 let loader = editor.syn_loader.load();
78 let text = doc.text().clone();
79
80 tokio::task::spawn_blocking(move || {
81 let syntax = match helix_core::Syntax::new(text.slice(..), language, &loader) {
82 Ok(syntax) => syntax,
83 Err(err) => {
84 log::info!("highlighting picker preview failed: {err}");
85 return;
86 }
87 };
88
89 job::dispatch_blocking(move |editor, compositor| {
90 let Some(Overlay {
91 content: picker, ..
92 }) = compositor.find::<Overlay<Picker<T, D>>>()
93 else {
94 log::info!("picker closed before syntax highlighting finished");
95 return;
96 };
97 let Some(CachedPreview::Document(ref mut doc)) =
98 picker.preview_cache.get_mut(&path)
99 else {
100 return;
101 };
102 let diagnostics = helix_view::Editor::doc_diagnostics(
103 &editor.language_servers,
104 &editor.diagnostics,
105 doc,
106 );
107 doc.replace_diagnostics(diagnostics, &[], None);
108 doc.syntax = Some(syntax);
109 });
110 });
111 });
112 }
113 }
114
115 pub(super) struct DynamicQueryChange {
116 pub query: Arc<str>,
117 pub is_paste: bool,
118 }
119
120 pub(super) struct DynamicQueryHandler<T: 'static + Send + Sync, D: 'static + Send + Sync> {
121 callback: Arc<DynQueryCallback<T, D>>,
122 // Duration used as a debounce.
123 // Defaults to 100ms if not provided via `Picker::with_dynamic_query`. Callers may want to set
124 // this higher if the dynamic query is expensive - for example global search.
125 debounce: Duration,
126 last_query: Arc<str>,
127 query: Option<Arc<str>>,
128 }
129
130 impl<T: 'static + Send + Sync, D: 'static + Send + Sync> DynamicQueryHandler<T, D> {
131 pub(super) fn new(callback: DynQueryCallback<T, D>, duration_ms: Option<u64>) -> Self {
132 Self {
133 callback: Arc::new(callback),
134 debounce: Duration::from_millis(duration_ms.unwrap_or(100)),
135 last_query: "".into(),
136 query: None,
137 }
138 }
139 }
140
141 impl<T: 'static + Send + Sync, D: 'static + Send + Sync> AsyncHook for DynamicQueryHandler<T, D> {
142 type Event = DynamicQueryChange;
143
144 fn handle_event(&mut self, change: Self::Event, _timeout: Option<Instant>) -> Option<Instant> {
145 let DynamicQueryChange { query, is_paste } = change;
146 if query == self.last_query {
147 // If the search query reverts to the last one we requested, no need to
148 // make a new request.
149 self.query = None;
150 None
151 } else {
152 self.query = Some(query);
153 if is_paste {
154 self.finish_debounce();
155 None
156 } else {
157 Some(Instant::now() + self.debounce)
158 }
159 }
160 }
161
162 fn finish_debounce(&mut self) {
163 let Some(query) = self.query.take() else {
164 return;
165 };
166 self.last_query = query.clone();
167 let callback = self.callback.clone();
168
169 job::dispatch_blocking(move |editor, compositor| {
170 let Some(Overlay {
171 content: picker, ..
172 }) = compositor.find::<Overlay<Picker<T, D>>>()
173 else {
174 return;
175 };
176 // Increment the version number to cancel any ongoing requests.
177 picker.version.fetch_add(1, atomic::Ordering::Relaxed);
178 picker.matcher.restart(false);
179 let injector = picker.injector();
180 let get_options = (callback)(&query, editor, picker.editor_data.clone(), &injector);
181 tokio::spawn(async move {
182 if let Err(err) = get_options.await {
183 log::info!("Dynamic request failed: {err}");
184 }
185 // NOTE: the Drop implementation of Injector will request a redraw when the
186 // injector falls out of scope here, clearing the "running" indicator.
187 });
188 })
189 }
190 }