Debian Codegraph @

helix-term/src/handlers/document_colors.rs

raw symbols SCIP
1 use std::{collections::HashSet, time::Duration};
2
3 use futures_util::{stream::FuturesUnordered, StreamExt};
4 use helix_core::{syntax::config::LanguageServerFeature, text_annotations::InlineAnnotation};
5 use helix_event::{cancelable_future, register_hook};
6 use helix_lsp::lsp;
7 use helix_view::{
8 document::DocumentColorSwatches,
9 events::{DocumentDidChange, DocumentDidOpen, LanguageServerExited, LanguageServerInitialized},
10 handlers::{lsp::DocumentColorsEvent, Handlers},
11 DocumentId, Editor, Theme,
12 };
13 use tokio::time::Instant;
14
15 use crate::job;
16
17 #[derive(Default)]
18 pub(super) struct DocumentColorsHandler {
19 docs: HashSet<DocumentId>,
20 }
21
22 const DOCUMENT_CHANGE_DEBOUNCE: Duration = Duration::from_millis(250);
23
24 impl helix_event::AsyncHook for DocumentColorsHandler {
25 type Event = DocumentColorsEvent;
26
27 fn handle_event(&mut self, event: Self::Event, _timeout: Option<Instant>) -> Option<Instant> {
28 let DocumentColorsEvent(doc_id) = event;
29 self.docs.insert(doc_id);
30 Some(Instant::now() + DOCUMENT_CHANGE_DEBOUNCE)
31 }
32
33 fn finish_debounce(&mut self) {
34 let docs = std::mem::take(&mut self.docs);
35
36 job::dispatch_blocking(move |editor, _compositor| {
37 for doc in docs {
38 request_document_colors(editor, doc);
39 }
40 });
41 }
42 }
43
44 fn request_document_colors(editor: &mut Editor, doc_id: DocumentId) {
45 if !editor.config().lsp.display_color_swatches {
46 return;
47 }
48
49 let Some(doc) = editor.document_mut(doc_id) else {
50 return;
51 };
52
53 let cancel = doc.color_swatch_controller.restart();
54
55 let mut seen_language_servers = HashSet::new();
56 let mut futures: FuturesUnordered<_> = doc
57 .language_servers_with_feature(LanguageServerFeature::DocumentColors)
58 .filter(|ls| seen_language_servers.insert(ls.id()))
59 .map(|language_server| {
60 let text = doc.text().clone();
61 let offset_encoding = language_server.offset_encoding();
62 let future = language_server
63 .text_document_document_color(doc.identifier(), None)
64 .unwrap();
65
66 async move {
67 let colors: Vec<_> = future
68 .await?
69 .into_iter()
70 .filter_map(|color_info| {
71 let pos = helix_lsp::util::lsp_pos_to_pos(
72 &text,
73 color_info.range.start,
74 offset_encoding,
75 )?;
76 Some((pos, color_info.color))
77 })
78 .collect();
79 anyhow::Ok(colors)
80 }
81 })
82 .collect();
83
84 if futures.is_empty() {
85 return;
86 }
87
88 tokio::spawn(async move {
89 let mut all_colors = Vec::new();
90 loop {
91 match cancelable_future(futures.next(), &cancel).await {
92 Some(Some(Ok(items))) => all_colors.extend(items),
93 Some(Some(Err(err))) => log::error!("document color request failed: {err}"),
94 Some(None) => break,
95 // The request was cancelled.
96 None => return,
97 }
98 }
99 job::dispatch(move |editor, _| attach_document_colors(editor, doc_id, all_colors)).await;
100 });
101 }
102
103 fn attach_document_colors(
104 editor: &mut Editor,
105 doc_id: DocumentId,
106 mut doc_colors: Vec<(usize, lsp::Color)>,
107 ) {
108 if !editor.config().lsp.display_color_swatches {
109 return;
110 }
111
112 let Some(doc) = editor.documents.get_mut(&doc_id) else {
113 return;
114 };
115
116 if doc_colors.is_empty() {
117 doc.color_swatches.take();
118 return;
119 }
120
121 doc_colors.sort_by_key(|(pos, _)| *pos);
122
123 let mut color_swatches = Vec::with_capacity(doc_colors.len());
124 let mut color_swatches_padding = Vec::with_capacity(doc_colors.len());
125 let mut colors = Vec::with_capacity(doc_colors.len());
126
127 for (pos, color) in doc_colors {
128 color_swatches_padding.push(InlineAnnotation::new(pos, " "));
129 color_swatches.push(InlineAnnotation::new(pos, "■"));
130 colors.push(Theme::rgb_highlight(
131 (color.red * 255.) as u8,
132 (color.green * 255.) as u8,
133 (color.blue * 255.) as u8,
134 ));
135 }
136
137 doc.color_swatches = Some(DocumentColorSwatches {
138 color_swatches,
139 colors,
140 color_swatches_padding,
141 });
142 }
143
144 pub(super) fn register_hooks(handlers: &Handlers) {
145 register_hook!(move |event: &mut DocumentDidOpen<'_>| {
146 // when a document is initially opened, request colors for it
147 request_document_colors(event.editor, event.doc);
148
149 Ok(())
150 });
151
152 let tx = handlers.document_colors.clone();
153 register_hook!(move |event: &mut DocumentDidChange<'_>| {
154 // Update the color swatch' positions, helping ensure they are displayed in the
155 // proper place.
156 let apply_color_swatch_changes = |annotations: &mut Vec<InlineAnnotation>| {
157 event.changes.update_positions(
158 annotations
159 .iter_mut()
160 .map(|annotation| (&mut annotation.char_idx, helix_core::Assoc::After)),
161 );
162 };
163
164 if let Some(DocumentColorSwatches {
165 color_swatches,
166 colors: _colors,
167 color_swatches_padding,
168 }) = &mut event.doc.color_swatches
169 {
170 apply_color_swatch_changes(color_swatches);
171 apply_color_swatch_changes(color_swatches_padding);
172 }
173
174 // Avoid re-requesting document colors if the change is a ghost transaction (completion)
175 // because the language server will not know about the updates to the document and will
176 // give out-of-date locations.
177 if !event.ghost_transaction {
178 // Cancel the ongoing request, if present.
179 event.doc.color_swatch_controller.cancel();
180 helix_event::send_blocking(&tx, DocumentColorsEvent(event.doc.id()));
181 }
182
183 Ok(())
184 });
185
186 register_hook!(move |event: &mut LanguageServerInitialized<'_>| {
187 let doc_ids: Vec<_> = event.editor.documents().map(|doc| doc.id()).collect();
188
189 for doc_id in doc_ids {
190 request_document_colors(event.editor, doc_id);
191 }
192
193 Ok(())
194 });
195
196 register_hook!(move |event: &mut LanguageServerExited<'_>| {
197 // Clear and re-request all color swatches when a server exits.
198 for doc in event.editor.documents_mut() {
199 if doc.supports_language_server(event.server_id) {
200 doc.color_swatches.take();
201 }
202 }
203
204 let doc_ids: Vec<_> = event.editor.documents().map(|doc| doc.id()).collect();
205
206 for doc_id in doc_ids {
207 request_document_colors(event.editor, doc_id);
208 }
209
210 Ok(())
211 });
212 }